opencode-swarm 7.172.0 → 7.172.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 (85) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{coder-settlement-0k46xqk2.js → coder-settlement-pw4jbrez.js} +11 -11
  4. package/dist/cli/{config-doctor-x41bxjp6.js → config-doctor-ab0ckcsc.js} +2 -2
  5. package/dist/cli/{core-3spww0at.js → core-ty98bsnz.js} +3 -3
  6. package/dist/cli/{curation-policy-92qhvewe.js → curation-policy-cvjd6kz8.js} +5 -5
  7. package/dist/cli/{curator-drift-fqvxe2zw.js → curator-drift-b0pbzjxv.js} +4 -4
  8. package/dist/cli/curator-llm-factory-69vje2m7.js +72 -0
  9. package/dist/cli/{curator-eyz6gg74.js → curator-rvrhbsy2.js} +36 -36
  10. package/dist/cli/{evidence-summary-service-kf0vb1hf.js → evidence-summary-service-wmer0c5b.js} +15 -15
  11. package/dist/cli/{gate-evidence-89wvxgs9.js → gate-evidence-6d0f6ekr.js} +6 -6
  12. package/dist/cli/guardrail-explain-z06dyan0.js +73 -0
  13. package/dist/cli/{guardrail-log-kfjk62sz.js → guardrail-log-bmyxcdfk.js} +7 -7
  14. package/dist/cli/{guardrail-reset-d8m1h5sz.js → guardrail-reset-9wmbhwff.js} +36 -36
  15. package/dist/cli/{hive-promoter-0ekf5zp1.js → hive-promoter-mc8xssba.js} +36 -36
  16. package/dist/cli/{index-8wnjcav5.js → index-008sppht.js} +3 -3
  17. package/dist/cli/{index-12w05bxk.js → index-31fes86t.js} +2 -2
  18. package/dist/cli/{index-63t4m2t5.js → index-3r17j2gc.js} +133 -23
  19. package/dist/cli/{index-2rdj9mdh.js → index-66tshqdp.js} +4 -4
  20. package/dist/cli/{index-6jshhpjw.js → index-93z2fhyp.js} +2 -2
  21. package/dist/cli/{index-mj07x42s.js → index-9bg5vc22.js} +2 -2
  22. package/dist/cli/{index-k441jgzk.js → index-9p00xent.js} +1 -1
  23. package/dist/cli/{index-efkckdaw.js → index-bdqefjxg.js} +1 -1
  24. package/dist/cli/{index-1vsmh63p.js → index-br08k19k.js} +74 -74
  25. package/dist/cli/{index-5hambjmn.js → index-c5wyannc.js} +30 -18
  26. package/dist/cli/{index-0y2ygy5f.js → index-dg5znyqw.js} +7 -7
  27. package/dist/cli/{index-7q1m8rsw.js → index-edext37b.js} +7 -7
  28. package/dist/cli/{index-dpb1xs5m.js → index-gdrdtbw6.js} +2 -2
  29. package/dist/cli/{index-nqbmk4b9.js → index-h91jjw6t.js} +1 -1
  30. package/dist/cli/{index-nyrhz1h1.js → index-ha3wsy2e.js} +1 -1
  31. package/dist/cli/{index-328eg2bb.js → index-hx0pas8b.js} +3 -3
  32. package/dist/cli/{index-677gzqmd.js → index-hydccmm1.js} +1 -1
  33. package/dist/cli/{index-53ges0rk.js → index-j8warkkj.js} +7 -7
  34. package/dist/cli/{index-8k09fkqj.js → index-jc0as97z.js} +4 -4
  35. package/dist/cli/{index-br3r0y73.js → index-jmn35na4.js} +3 -3
  36. package/dist/cli/{index-1s3t3jdc.js → index-jzrx2sx2.js} +1 -1
  37. package/dist/cli/{index-6fb3y9pm.js → index-ma38q4rf.js} +1 -1
  38. package/dist/cli/{index-v6msnkz2.js → index-mq69g46a.js} +2 -2
  39. package/dist/cli/{index-s723hx7z.js → index-nzpw41w6.js} +1 -1
  40. package/dist/cli/{index-39x78qk0.js → index-pmg1k4mv.js} +8 -8
  41. package/dist/cli/{index-w1d5nsdc.js → index-q58xegd7.js} +2 -2
  42. package/dist/cli/{index-z81mxyhm.js → index-qfz31dcy.js} +5 -5
  43. package/dist/cli/{index-y8y2bjsy.js → index-re1ey51s.js} +4 -4
  44. package/dist/cli/{index-tfmb620d.js → index-rhe9zbe2.js} +36 -36
  45. package/dist/cli/{index-29j9sjbw.js → index-sakgsnxj.js} +1 -1
  46. package/dist/cli/{index-r08tgb71.js → index-tm6z0wgj.js} +2 -2
  47. package/dist/cli/{index-34jdempk.js → index-tr3tbtgw.js} +2 -2
  48. package/dist/cli/{index-zbw6h4xn.js → index-twpzfwga.js} +1 -1
  49. package/dist/cli/{index-jvg7hvjp.js → index-vqs7dxp7.js} +3 -3
  50. package/dist/cli/{index-25fa4krx.js → index-w0141tkw.js} +8 -8
  51. package/dist/cli/{index-gmw8a1qa.js → index-wf6pbrg7.js} +1 -1
  52. package/dist/cli/{index-a2kv054j.js → index-ws3ggk1h.js} +6 -6
  53. package/dist/cli/{index-xn9tm7sr.js → index-y21gyrt6.js} +38 -38
  54. package/dist/cli/{index-v2fge66b.js → index-y5x1swr8.js} +7 -7
  55. package/dist/cli/{index-dga9j6s1.js → index-yf1mvexg.js} +2 -2
  56. package/dist/cli/{index-3kqzzwvd.js → index-zcjdw8dw.js} +1 -1
  57. package/dist/cli/index.js +37 -37
  58. package/dist/cli/{knowledge-escalator-qtz01ffw.js → knowledge-escalator-k4ab3f1f.js} +12 -12
  59. package/dist/cli/{knowledge-events-8w0mvkzc.js → knowledge-events-aqy4hb15.js} +10 -10
  60. package/dist/cli/{knowledge-link-3xp7h4xn.js → knowledge-link-51m3c09s.js} +4 -4
  61. package/dist/cli/{knowledge-store-p5ps09qg.js → knowledge-store-xgkga9xj.js} +5 -5
  62. package/dist/cli/{knowledge-validator-rc63wfkp.js → knowledge-validator-vvgs8m7m.js} +7 -7
  63. package/dist/cli/{mcp-pmfg7wpk.js → mcp-qvgka4c8.js} +1 -1
  64. package/dist/cli/{pending-delegations-1sg6g7et.js → pending-delegations-1xvmbw29.js} +11 -11
  65. package/dist/cli/{pr-subscriptions-yd804apk.js → pr-subscriptions-13xqrhwx.js} +11 -11
  66. package/dist/cli/{pr-workflow-gate-pf3ssffq.js → pr-workflow-gate-6qzpckxa.js} +36 -36
  67. package/dist/cli/{runner-rry4z6j2.js → runner-k2t9n662.js} +5 -5
  68. package/dist/cli/{scan-cursor-j93ek248.js → scan-cursor-q5nycpzb.js} +6 -6
  69. package/dist/cli/{schema-hvptm5hf.js → schema-a8gskpey.js} +1 -1
  70. package/dist/cli/{scope-persistence-3tfvswtk.js → scope-persistence-q0n6y3n7.js} +14 -14
  71. package/dist/cli/{server-rbvx63t6.js → server-wmbahe8h.js} +36 -36
  72. package/dist/cli/{skill-generator-r9wc6xt1.js → skill-generator-z76whwng.js} +14 -14
  73. package/dist/cli/{snapshot-coordination-init-7w5em40w.js → snapshot-coordination-init-k2fgw463.js} +36 -36
  74. package/dist/cli/{telemetry-vw919tfm.js → telemetry-zed80n86.js} +1 -1
  75. package/dist/cli/{workspace-snapshot-x54wxr6a.js → workspace-snapshot-93dx9rbt.js} +3 -3
  76. package/dist/cli/{worktree-collision-ownership-yetwf2ch.js → worktree-collision-ownership-deyrgr70.js} +12 -12
  77. package/dist/cli/{worktree-isolation-sxfj78hv.js → worktree-isolation-9rjxaxp6.js} +36 -36
  78. package/dist/index.js +11 -11
  79. package/dist/plan/index.d.ts +1 -0
  80. package/dist/plan/ledger.d.ts +10 -0
  81. package/dist/plan/manager.d.ts +38 -2
  82. package/dist/tools/phase-complete.d.ts +1 -1
  83. package/package.json +1 -1
  84. package/dist/cli/curator-llm-factory-jnsjqq99.js +0 -72
  85. package/dist/cli/guardrail-explain-rz4kaqyp.js +0 -73
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.172.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","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"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.172.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@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"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -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{_internals7.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}.${_internals7.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+=_internals7.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals7.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals7.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,_internals7;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:315"],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:651","src/plan/manager.ts:1715","src/plan/manager.ts:1761","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:123","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:209","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1077","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:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1448","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:140","src/tools/write-pr-review-artifact.ts:160","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:1901","src/plan/manager.ts:2090"],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:125","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:460","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:578","src/plan/ledger.ts:1756"],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/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;_internals7={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(_internals8.platform()==="win32"){let taskkill;try{if(taskkill=_internals8.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals8.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 _internals8.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 state=inspectSpawnCwd(cwd);if(state==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state==="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,_internals8,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}};_internals8={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{_internals7.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}.${_internals7.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+=_internals7.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals7.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals7.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,_internals7;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:315"],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:661","src/plan/manager.ts:1979","src/plan/manager.ts:2033","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:123","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:209","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1448","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:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1448","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:140","src/tools/write-pr-review-artifact.ts:160","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:2226","src/plan/manager.ts:2374"],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:125","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:460","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:578","src/plan/ledger.ts:1763"],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/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;_internals7={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(_internals8.platform()==="win32"){let taskkill;try{if(taskkill=_internals8.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals8.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 _internals8.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 state=inspectSpawnCwd(cwd);if(state==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state==="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,_internals8,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}};_internals8={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 _internals9.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=_internals9.validateSwarmPath(directory,filename);let read=async()=>{if(reader!==void 0)return reader(resolvedPath);return await bunFile(resolvedPath).text()};return useArtifactCache?await _internals9.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 _internals9,TOKENS_PER_CHAR=0.33;var init_utils2=__esm(()=>{init_utils();init_atomic_write();init_bun_compat();init_swarm_artifact_cache();_internals9={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(`
@@ -466,7 +466,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
466
466
  lease_expires_at = excluded.lease_expires_at, payload = excluded.payload,
467
467
  updated_at = excluded.updated_at`,[input.namespace,input.entityKey,input.generation,input.ownerToken,input.leaseExpiresAt,input.payload,now]),{outcome:"acquired"}})}function releaseCoordinationLease(directory,namespace,entityKey,generation,ownerToken){return withCoordinationTransaction(directory,()=>{return getProjectDb(directory).run(`DELETE FROM coordination_lease
468
468
  WHERE namespace = ? AND entity_key = ? AND generation = ? AND owner_token = ?`,[namespace,entityKey,generation,ownerToken]).changes===1})}function importCoordinationOnce(directory,input,importer){if(boundedText(input.source,"source",MAX_KEY_CHARS),boundedText(input.sourceDigest,"sourceDigest",MAX_KEY_CHARS),boundedText(input.emptyNamespace,"emptyNamespace",MAX_KEY_CHARS),!Number.isSafeInteger(input.rowCount)||input.rowCount<0)throw Error("rowCount must be a nonnegative safe integer");let result=withCoordinationTransaction(directory,()=>{let db=getProjectDb(directory);if(db.query("SELECT 1 AS present FROM coordination_import WHERE source = ?").get(input.source))return"already_imported";if((db.query("SELECT COUNT(*) AS count FROM coordination_state WHERE namespace = ?").get(input.emptyNamespace)?.count??0)!==0)return"state_exists";return importer(),db.run(`INSERT INTO coordination_import
469
- (source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals13.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals13;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals13={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals14.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals14;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals14={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:431"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:428"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:415"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:269"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:655",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:659",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:663",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:718",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:766",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:948",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:956",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:981",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:667",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_read_uncertain",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:705",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:786",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:1803",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:1823",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:813",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:727",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:744",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:731",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:754",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1125",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:770",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:789",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1358",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:827",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:836",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:840",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:936",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:944",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:966",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:854",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:875",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:889",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:906",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:923",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1339",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:996",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1010",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1023",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1037",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:348",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1783",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1587",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1074",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1096",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1140",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1177",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1203",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1227",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1250",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1279",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1323",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals15,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals15.createObservation(event,data),content=_internals15.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals15.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals15;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals15.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals15.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals15.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals15.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals15.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals15.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals15.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals15.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals15.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals15.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals15.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals15.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals15.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals15.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals15.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals15.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals15.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals15.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals15.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals15.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals15.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals15.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals15.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals15.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals15.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals15.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals15.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals15.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals15.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals15.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals15.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals15.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals15.emit("close_archive_result",data)},residueHealth(data){_internals15.emit("residue_health",data)},trainingVaultHealth(data){_internals15.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals15.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals15.emit("skill_usage_health",data)},coreEventsHealth(data){_internals15.emit("core_events_health",data)},shellAuditHealth(data){_internals15.emit("shell_audit_health",data)},trajectoryHealth(data){_internals15.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals15.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals15.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals15.emit("retrieval_routed",{sessionId,...data})}},_internals15={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals16.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path14.dirname(current);if(parent===current)break;if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals16;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals16={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
469
+ (source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals13.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals13;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals13={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals14.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals14;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals14={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:431"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:428"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:415"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:269"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:655",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:659",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:663",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:718",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:766",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:948",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:956",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:981",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:667",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_read_uncertain",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:705",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:786",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:1803",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:1823",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:813",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:727",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:744",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:731",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:754",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1125",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:770",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:789",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1358",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:827",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:836",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:840",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:936",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:944",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:966",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:854",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:875",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:889",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:906",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:923",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1339",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:996",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1010",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1023",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1037",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:358",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:2056",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1594",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1074",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1096",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1140",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1177",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1203",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1227",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1250",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1279",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1323",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals15,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals15.createObservation(event,data),content=_internals15.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals15.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals15;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals15.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals15.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals15.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals15.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals15.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals15.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals15.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals15.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals15.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals15.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals15.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals15.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals15.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals15.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals15.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals15.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals15.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals15.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals15.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals15.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals15.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals15.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals15.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals15.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals15.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals15.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals15.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals15.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals15.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals15.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals15.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals15.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals15.emit("close_archive_result",data)},residueHealth(data){_internals15.emit("residue_health",data)},trainingVaultHealth(data){_internals15.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals15.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals15.emit("skill_usage_health",data)},coreEventsHealth(data){_internals15.emit("core_events_health",data)},shellAuditHealth(data){_internals15.emit("shell_audit_health",data)},trajectoryHealth(data){_internals15.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals15.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals15.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals15.emit("retrieval_routed",{sessionId,...data})}},_internals15={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals16.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path14.dirname(current);if(parent===current)break;if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals16;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals16={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
470
470
  `).map((line)=>line.trim()).filter((line)=>line.length>0)}function selectCompactionSurvivors(lines,opts){let kept=[],keptBytes=0;for(let i=lines.length-1;i>=0;i--){if(kept.length>=opts.maxEntries)break;let line=lines[i],lineBytes=Buffer.byteLength(`${line}
471
471
  `,"utf-8");if(kept.length>0&&opts.maxBytes!==void 0&&keptBytes+lineBytes>opts.maxBytes)break;kept.unshift(line),keptBytes+=lineBytes}return kept}async function appendAndCap(filePath,line,opts){let directory=path17.dirname(filePath);fs9.mkdirSync(directory,{recursive:!0});let record2=`${line.trim()}
472
472
  `,existing="";try{existing=await fs9.promises.readFile(filePath,"utf-8")}catch{}let combined=[...wholeLines(existing),line.trim()],survivors=selectCompactionSurvivors(combined,opts),dropped=combined.length-survivors.length;if(dropped>0){let compactedLines=combined.slice(dropped,combined.length-1),compacted=compactedLines.length>0?`${compactedLines.join(`
@@ -604,12 +604,12 @@ ${lines[i]}`),framingChecked=!0}else{let prefix=!framingChecked&&!fileEndsWithNe
604
604
  archive_created_at = excluded.archive_created_at, mode = excluded.mode,
605
605
  version = excluded.version, row_count = excluded.row_count,
606
606
  imported_at = excluded.imported_at`,[source,sourceHash,archivePath,archiveHash,archiveSize,archiveCreatedAt,mode,version2,events.length,new Date().toISOString()]),readSqliteLedgerEventsFromDb(db)}function readSqliteRows(db){return db.query("SELECT * FROM plan_ledger_event ORDER BY seq ASC").all().map(rowEvent)}function readSqliteLedgerEventsFromDb(db){let events=readSqliteRows(db),row=db.query("SELECT * FROM plan_ledger_import ORDER BY imported_at DESC, source ASC LIMIT 1").get();return{events,state:readState2(db),import:row?{source:String(row.source),sourceHash:String(row.source_hash),archivePath:stringOrNull(row.archive_path),archiveHash:stringOrNull(row.archive_hash),archiveSize:typeof row.archive_size==="number"?row.archive_size:null,archiveCreatedAt:stringOrNull(row.archive_created_at),mode:String(row.mode),version:stringOrNull(row.version),rowCount:Number(row.row_count??0),importedAt:String(row.imported_at)}:null}}function importSqliteLedger(first,second){let{directory,input}=withDirectory(first,second);return withImmediateTransaction(getProjectDb(directory),"full",()=>importInTransaction(getProjectDb(directory),input,!1))}function replaceSqliteLedger(first,second){let{directory,input}=withDirectory(first,second);return withImmediateTransaction(getProjectDb(directory),"full",()=>importInTransaction(getProjectDb(directory),input,!0))}function recordSqliteLedgerParity(first,second){let{directory,input}=withDirectory(first,second),db=getProjectDb(directory);return withImmediateTransaction(db,"full",()=>{let fileHash=input.fileReplayHash??input.file_replay_hash,sqliteHash=input.sqliteReplayHash??input.sqlite_replay_hash;if(fileHash===void 0||sqliteHash===void 0)throw Error("Parity requires both file_replay_hash and sqlite_replay_hash");let status=input.parityStatus??input.parity_status??(fileHash===sqliteHash?"clean":"diverged");return upsertState(db,{fileReplayHash:fileHash,sqliteReplayHash:sqliteHash,terminalProjectionHash:input.terminalProjectionHash??input.terminal_projection_hash,parityStatus:status},{}),readState2(db)})}function cutoverSqliteLedger(first,second){let{directory,input}=typeof first==="string"?{directory:first,input:second}:{directory:first.directory,input:first},db=getProjectDb(directory);return withImmediateTransaction(db,"full",()=>{let state=readState2(db);if(!state)throw Error("Cannot cut over an uninitialized SQLite plan ledger");if(state.parityStatus!=="clean"||!state.fileReplayHash||state.fileReplayHash!==state.sqliteReplayHash)throw Error("Cannot cut over SQLite plan ledger before a clean parity record");let expected=input?.expectedShadowStartedVersion??input?.expected_shadow_started_version;if(expected!==void 0&&state.shadowStartedVersion!==expected)throw new SqliteLedgerStaleWriterError(`SQLite plan-ledger shadow version changed: expected ${expected}, found ${state.shadowStartedVersion??"<missing>"}`);return db.run("UPDATE plan_ledger_state SET authority_mode = 'sqlite', updated_at = ? WHERE id = 1",[new Date().toISOString()]),readState2(db)})}function clearSqliteLedger(directory){if(!projectDbExists(directory))return;let db=getProjectDb(directory);withImmediateTransaction(db,"full",()=>{db.run("DELETE FROM plan_ledger_event"),db.run("DELETE FROM plan_ledger_import"),db.run("DELETE FROM plan_ledger_state")})}var SqliteLedgerStaleWriterError,SqliteLedgerImportError;var init_ledger_sqlite=__esm(()=>{init_durability();init_project_db();SqliteLedgerStaleWriterError=class SqliteLedgerStaleWriterError extends Error{constructor(message){super(message);this.name="SqliteLedgerStaleWriterError"}};SqliteLedgerImportError=class SqliteLedgerImportError extends Error{constructor(message){super(message);this.name="SqliteLedgerImportError"}}});import*as crypto3 from"node:crypto";import*as fs18 from"node:fs";import*as path33 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanLedgerHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path33.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path33.join(directory,".swarm",PLAN_JSON_FILENAME)}function compareCodeUnits(a,b){return a<b?-1:a>b?1:0}function readLedgerDirectory(directory){return fs18.readdirSync(directory)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanLedgerHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs18.openSync(tempPath,"w");try{fs18.writeFileSync(fd,data,"utf8"),fs18.fsyncSync(fd)}finally{fs18.closeSync(fd)}fs18.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs18.openSync(directory,"r"),fs18.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs18.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function isStructurallyValidLedgerEvent(value){let event=asRecord(value);return event!==null&&Number.isSafeInteger(event.seq)&&event.seq>0&&typeof event.timestamp==="string"&&typeof event.plan_id==="string"&&typeof event.event_type==="string"&&typeof event.source==="string"&&typeof event.plan_hash_before==="string"&&typeof event.plan_hash_after==="string"&&typeof event.schema_version==="string"}function readFileLedgerExact(directory){let ledgerPath=getLedgerPath(directory);if(!fs18.existsSync(ledgerPath))return{events:[],lines:[],truncated:!1,badSuffix:null};let bytes=fs18.readFileSync(ledgerPath),decoder=new TextDecoder("utf-8",{fatal:!0}),events=[],lenientEvents=[],lines=[],truncated=!1,badSuffix=null,start=0;for(let index=0;index<=bytes.length;index++){if(index<bytes.length&&bytes[index]!==10)continue;let end=index;if(end>start&&bytes[end-1]===13)end--;let line=bytes.subarray(start,end);if(line.length>0)try{let parsed=JSON.parse(decoder.decode(line));if(!isStructurallyValidLedgerEvent(parsed))throw Error("invalid ledger event shape");if(lenientEvents.push(parsed),!truncated)events.push(parsed);if(!truncated)lines.push(new Uint8Array(line))}catch{if(!truncated)truncated=!0,badSuffix=bytes.subarray(start).toString("utf8")}start=index+1}return{events,lines,truncated,badSuffix,lenientEvents}}function sqliteEventsAsLedger(directory){let rows=readSqliteLedgerEvents(directory).events;return{events:rows.map((row)=>row.event),lines:rows.map((row)=>row.canonicalEvent)}}function exactPrefix(prefix,complete){return prefix.length<=complete.length&&prefix.every((line,index)=>Buffer.from(line).equals(Buffer.from(complete[index])))}function eventsProjection(directory,events){let plan=reconstructPlanFromEvents(directory,structuredClone(events)),projection=new TextEncoder().encode(JSON.stringify(plan));return{replayHash:plan?computePlanLedgerHash(plan):crypto3.createHash("sha256").update(projection).digest("hex"),projectionHash:crypto3.createHash("sha256").update(projection).digest("hex"),projection}}function stateForEvents(directory,events,authorityMode){let terminal=eventsProjection(directory,events),last=events.at(-1);return{authorityMode,shadowStartedVersion:getPlanLedgerState(directory)?.shadowStartedVersion??package_default.version,parityStatus:"pending",terminalProjectionHash:terminal.projectionHash,terminalProjection:terminal.projection,lastSeq:last?.seq??0,planId:last?.plan_id??null,terminalPlanHash:last?.plan_hash_after??null}}function writePortableLedger(directory,lines){let ledgerPath=getLedgerPath(directory);fs18.mkdirSync(path33.dirname(ledgerPath),{recursive:!0});let content=Buffer.concat(lines.flatMap((line)=>[Buffer.from(line),Buffer.from(`
607
- `)])),tempPath=`${ledgerPath}.sqlite-export.${crypto3.randomBytes(16).toString("hex")}.tmp`;try{_internals32.writeFileFsyncedThenRename(tempPath,ledgerPath,content)}finally{try{fs18.unlinkSync(tempPath)}catch{}}}function archiveLegacyLedger(directory,bytes){let hash2=crypto3.createHash("sha256").update(bytes).digest("hex"),archivePath=path33.join(directory,".swarm",`plan-ledger.legacy-archive.${hash2}.jsonl`);if(!fs18.existsSync(archivePath)){let tempPath=`${archivePath}.tmp.${crypto3.randomBytes(16).toString("hex")}`;try{_internals32.writeFileFsyncedThenRename(tempPath,archivePath,bytes)}finally{try{fs18.unlinkSync(tempPath)}catch{}}fsyncRecoveryDirectory(path33.dirname(archivePath))}return{path:archivePath,hash:hash2}}function importCanonicalIntoSqlite(directory,file2,legacy){if(file2.truncated)return;let ledgerBytes=fs18.readFileSync(getLedgerPath(directory)),archive=legacy?archiveLegacyLedger(directory,ledgerBytes):null,terminal=eventsProjection(directory,file2.events);importSqliteLedger(directory,{canonicalEvents:file2.lines,state:{...stateForEvents(directory,file2.events,"file_shadow"),fileReplayHash:terminal.replayHash,sqliteReplayHash:terminal.replayHash,parityStatus:"clean"},source:"plan-ledger.jsonl",sourceHash:crypto3.createHash("sha256").update(ledgerBytes).digest("hex"),archivePath:archive?.path??null,archiveHash:archive?.hash??null,archiveSize:archive?ledgerBytes.length:null,archiveCreatedAt:archive?new Date().toISOString():null,mode:"file_shadow",version:package_default.version})}function coordinateLedger(directory){if(fs18.existsSync(path33.join(directory,".swarm","plan-ledger.resetting")))return{events:[],lines:[],truncated:!1,badSuffix:null};let file2=readFileLedgerExact(directory);if(!hasSqliteLedger(directory)){if(file2.events.length>0&&!file2.truncated)try{importCanonicalIntoSqlite(directory,file2,!0)}catch(error49){log(`[ledger] SQLite shadow import deferred after file read: ${error49 instanceof Error?error49.message:String(error49)}`)}return file2}let sqlite=sqliteEventsAsLedger(directory),state=getPlanLedgerState(directory);if(!state)throw Error("SQLite plan ledger has events but no authority state");if(state.authorityMode==="file_shadow"){if(!fs18.existsSync(getLedgerPath(directory)))return writePortableLedger(directory,sqlite.lines),{events:sqlite.events,lines:sqlite.lines,truncated:!1,badSuffix:null};if(file2.truncated){if(!exactPrefix(file2.lines,sqlite.lines))throw Error("PLAN_LEDGER_DIVERGED: malformed file prefix differs from SQLite authority");return file2}if(file2.events[0]?.seq===1&&file2.events[0]?.event_type==="plan_created"&&sqlite.events[0]?.plan_id!==file2.events[0]?.plan_id)try{replaceSqliteLedger(directory,{canonicalEvents:file2.lines,state:stateForEvents(directory,file2.events,"file_shadow"),source:"plan_identity_reinitialized",mode:"file_shadow",version:package_default.version}),sqlite=sqliteEventsAsLedger(directory)}catch(error49){return log(`[ledger] SQLite shadow re-root reconciliation deferred: ${error49 instanceof Error?error49.message:String(error49)}`),file2}if(!exactPrefix(sqlite.lines,file2.lines))throw Error("PLAN_LEDGER_DIVERGED: JSONL and SQLite committed prefixes differ");try{for(let index=sqlite.lines.length;index<file2.lines.length;index++)appendSqliteLedger(directory,{canonicalEvent:file2.lines[index],expectedSeq:index,state:stateForEvents(directory,file2.events.slice(0,index+1),"file_shadow")})}catch(error49){return log(`[ledger] SQLite shadow suffix repair deferred: ${error49 instanceof Error?error49.message:String(error49)}`),file2}sqlite=sqliteEventsAsLedger(directory);let fileProjection=eventsProjection(directory,file2.events),current=getPlanLedgerState(directory),sqliteReplayHash=sqlite.events.at(-1)?.plan_hash_after??"",sqliteProjectionHash=current.terminalProjectionHash,parityStatus=fileProjection.replayHash===sqliteReplayHash&&fileProjection.projectionHash===sqliteProjectionHash?"clean":"diverged";if(current.parityStatus!==parityStatus||current.fileReplayHash!==fileProjection.replayHash||current.sqliteReplayHash!==sqliteReplayHash)recordSqliteLedgerParity(directory,{fileReplayHash:fileProjection.replayHash,sqliteReplayHash,terminalProjectionHash:sqliteProjectionHash,parityStatus});let refreshed=getPlanLedgerState(directory);if(refreshed.parityStatus==="clean"&&refreshed.shadowStartedVersion!==null&&refreshed.shadowStartedVersion!==package_default.version)cutoverSqliteLedger(directory,{expectedShadowStartedVersion:refreshed.shadowStartedVersion});return file2}if(file2.truncated||file2.lines.length!==sqlite.lines.length||!exactPrefix(file2.lines,sqlite.lines))writePortableLedger(directory,sqlite.lines);return{events:sqlite.events,lines:sqlite.lines,truncated:!1,badSuffix:null}}function computePlanLedgerHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs18.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanLedgerHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs18.existsSync(ledgerPath)||hasSqliteLedger(directory)}async function getLatestLedgerSeq(directory){return coordinateLedger(directory).events.reduce((maximum,event)=>Math.max(maximum,event.seq),0)}async function readLedgerEvents(directory){let result=coordinateLedger(directory);return[...result.truncated?result.lenientEvents??result.events:result.events].sort((a,b)=>a.seq-b.seq)}async function initLedger(directory,planId,initialPlanHash,initialPlan){assertProjectRoot(directory);let ledgerPath=getLedgerPath(directory),planJsonPath=getPlanJsonPath(directory);if(fs18.existsSync(ledgerPath))throw Error("Ledger already initialized. Use appendLedgerEvent to add events.");let planHashAfter=initialPlanHash??"",embeddedPlan=initialPlan;if(!initialPlanHash)try{if(fs18.existsSync(planJsonPath)){let content=fs18.readFileSync(planJsonPath,"utf8"),plan=JSON.parse(content);if(planHashAfter=computePlanLedgerHash(plan),!embeddedPlan)embeddedPlan=plan}}catch{}let payload={plan_epoch:crypto3.randomUUID(),...embeddedPlan?{plan:embeddedPlan,payload_hash:planHashAfter}:{}},event={seq:1,timestamp:new Date().toISOString(),plan_id:planId,event_type:"plan_created",source:"initLedger",plan_hash_before:"",plan_hash_after:planHashAfter,schema_version:LEDGER_SCHEMA_VERSION,...payload?{payload}:{}};fs18.mkdirSync(path33.join(directory,".swarm"),{recursive:!0});let tempPath=`${ledgerPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`,line=`${JSON.stringify(event)}
607
+ `)])),tempPath=`${ledgerPath}.sqlite-export.${crypto3.randomBytes(16).toString("hex")}.tmp`;try{_internals32.writeFileFsyncedThenRename(tempPath,ledgerPath,content)}finally{try{fs18.unlinkSync(tempPath)}catch{}}}function archiveLegacyLedger(directory,bytes){let hash2=crypto3.createHash("sha256").update(bytes).digest("hex"),archivePath=path33.join(directory,".swarm",`plan-ledger.legacy-archive.${hash2}.jsonl`);if(!fs18.existsSync(archivePath)){let tempPath=`${archivePath}.tmp.${crypto3.randomBytes(16).toString("hex")}`;try{_internals32.writeFileFsyncedThenRename(tempPath,archivePath,bytes)}finally{try{fs18.unlinkSync(tempPath)}catch{}}fsyncRecoveryDirectory(path33.dirname(archivePath))}return{path:archivePath,hash:hash2}}function importCanonicalIntoSqlite(directory,file2,legacy){if(file2.truncated)return;let ledgerBytes=fs18.readFileSync(getLedgerPath(directory)),archive=legacy?archiveLegacyLedger(directory,ledgerBytes):null,terminal=eventsProjection(directory,file2.events);importSqliteLedger(directory,{canonicalEvents:file2.lines,state:{...stateForEvents(directory,file2.events,"file_shadow"),fileReplayHash:terminal.replayHash,sqliteReplayHash:terminal.replayHash,parityStatus:"clean"},source:"plan-ledger.jsonl",sourceHash:crypto3.createHash("sha256").update(ledgerBytes).digest("hex"),archivePath:archive?.path??null,archiveHash:archive?.hash??null,archiveSize:archive?ledgerBytes.length:null,archiveCreatedAt:archive?new Date().toISOString():null,mode:"file_shadow",version:package_default.version})}function coordinateLedger(directory){if(fs18.existsSync(path33.join(directory,".swarm","plan-ledger.resetting")))return{events:[],lines:[],truncated:!1,badSuffix:null};let file2=readFileLedgerExact(directory);if(!hasSqliteLedger(directory)){if(file2.events.length>0&&!file2.truncated)try{importCanonicalIntoSqlite(directory,file2,!0)}catch(error49){log(`[ledger] SQLite shadow import deferred after file read: ${error49 instanceof Error?error49.message:String(error49)}`)}return file2}let sqlite=sqliteEventsAsLedger(directory),state=getPlanLedgerState(directory);if(!state)throw Error("SQLite plan ledger has events but no authority state");if(state.authorityMode==="file_shadow"){if(!fs18.existsSync(getLedgerPath(directory)))return writePortableLedger(directory,sqlite.lines),{events:sqlite.events,lines:sqlite.lines,truncated:!1,badSuffix:null};if(file2.truncated){if(!exactPrefix(file2.lines,sqlite.lines))throw Error("PLAN_LEDGER_DIVERGED: malformed file prefix differs from SQLite authority");return file2}if(file2.events[0]?.seq===1&&file2.events[0]?.event_type==="plan_created"&&sqlite.events[0]?.plan_id!==file2.events[0]?.plan_id)try{replaceSqliteLedger(directory,{canonicalEvents:file2.lines,state:stateForEvents(directory,file2.events,"file_shadow"),source:"plan_identity_reinitialized",mode:"file_shadow",version:package_default.version}),sqlite=sqliteEventsAsLedger(directory)}catch(error49){return log(`[ledger] SQLite shadow re-root reconciliation deferred: ${error49 instanceof Error?error49.message:String(error49)}`),file2}if(!exactPrefix(sqlite.lines,file2.lines))throw Error("PLAN_LEDGER_DIVERGED: JSONL and SQLite committed prefixes differ");try{for(let index=sqlite.lines.length;index<file2.lines.length;index++)appendSqliteLedger(directory,{canonicalEvent:file2.lines[index],expectedSeq:index,state:stateForEvents(directory,file2.events.slice(0,index+1),"file_shadow")})}catch(error49){return log(`[ledger] SQLite shadow suffix repair deferred: ${error49 instanceof Error?error49.message:String(error49)}`),file2}sqlite=sqliteEventsAsLedger(directory);let fileProjection=eventsProjection(directory,file2.events),current=getPlanLedgerState(directory),sqliteReplayHash=sqlite.events.at(-1)?.plan_hash_after??"",sqliteProjectionHash=current.terminalProjectionHash,parityStatus=fileProjection.replayHash===sqliteReplayHash&&fileProjection.projectionHash===sqliteProjectionHash?"clean":"diverged";if(current.parityStatus!==parityStatus||current.fileReplayHash!==fileProjection.replayHash||current.sqliteReplayHash!==sqliteReplayHash)recordSqliteLedgerParity(directory,{fileReplayHash:fileProjection.replayHash,sqliteReplayHash,terminalProjectionHash:sqliteProjectionHash,parityStatus});let refreshed=getPlanLedgerState(directory);if(refreshed.parityStatus==="clean"&&refreshed.shadowStartedVersion!==null&&refreshed.shadowStartedVersion!==package_default.version)cutoverSqliteLedger(directory,{expectedShadowStartedVersion:refreshed.shadowStartedVersion});return file2}if(file2.truncated||file2.lines.length!==sqlite.lines.length||!exactPrefix(file2.lines,sqlite.lines))writePortableLedger(directory,sqlite.lines);return{events:sqlite.events,lines:sqlite.lines,truncated:!1,badSuffix:null}}function computePlanLedgerHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs18.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanLedgerHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs18.existsSync(ledgerPath)||hasSqliteLedger(directory)}async function getLatestLedgerSeq(directory){return coordinateLedger(directory).events.reduce((maximum,event)=>Math.max(maximum,event.seq),0)}async function readLedgerEvents(directory){let result=coordinateLedger(directory);return[...result.truncated?result.lenientEvents??result.events:result.events].sort((a,b)=>a.seq-b.seq)}async function initLedger(directory,planId,initialPlanHash,initialPlan){assertProjectRoot(directory);let ledgerPath=getLedgerPath(directory),planJsonPath=getPlanJsonPath(directory);if(fs18.existsSync(ledgerPath))throw Error("Ledger already initialized. Use appendLedgerEvent to add events.");let planHashAfter=initialPlanHash??"",embeddedPlan=initialPlan;if(!initialPlanHash)try{if(fs18.existsSync(planJsonPath)){let initBytes=fs18.readFileSync(planJsonPath),content=new TextDecoder("utf-8",{fatal:!0}).decode(initBytes),plan=JSON.parse(content);if(planHashAfter=computePlanLedgerHash(plan),!embeddedPlan)embeddedPlan=plan}}catch{}let payload={plan_epoch:crypto3.randomUUID(),...embeddedPlan?{plan:embeddedPlan,payload_hash:planHashAfter}:{}},event={seq:1,timestamp:new Date().toISOString(),plan_id:planId,event_type:"plan_created",source:"initLedger",plan_hash_before:"",plan_hash_after:planHashAfter,schema_version:LEDGER_SCHEMA_VERSION,...payload?{payload}:{}};fs18.mkdirSync(path33.join(directory,".swarm"),{recursive:!0});let tempPath=`${ledgerPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`,line=`${JSON.stringify(event)}
608
608
  `;writeFileFsyncedThenRename(tempPath,ledgerPath,line);let initialized=readFileLedgerExact(directory);if(hasSqliteLedger(directory)){let priorMode=getPlanLedgerState(directory)?.authorityMode??"file_shadow";try{replaceSqliteLedger(directory,{canonicalEvents:initialized.lines,state:stateForEvents(directory,initialized.events,priorMode),source:"plan_identity_reinitialized",mode:priorMode,version:package_default.version})}catch(error49){if(priorMode!=="file_shadow")throw error49;log(`[ledger] SQLite shadow re-root deferred after file commit: ${error49 instanceof Error?error49.message:String(error49)}`)}}else importCanonicalIntoSqlite(directory,initialized,!1)}async function readLedgerEventsForEpoch(directory){let integrity=await _internals32.readLedgerEventsWithIntegrity(directory,{failClosedOnReadError:!0});if(integrity.truncated)throw Error(`PLAN_LEDGER_TRUNCATED: ${getLedgerPath(directory)} has a malformed line; plan epoch identity cannot be resolved. Preserve this file and quarantine the corrupted suffix before retrying.`);return integrity.events}async function readPlanEpochIdentity(directory,authoritativePlan){if(assertProjectRoot(directory),!await ledgerExists(directory))return null;let events=await readLedgerEventsForEpoch(directory);if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");return resolvePlanEpochIdentity(events,authoritativePlan)}async function getOrAdoptPlanEpochUnderLock(directory,authoritativePlan){assertProjectRoot(directory);let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanLedgerHash(authoritativePlan),lastStaleWriterError;for(let attempt=0;attempt<4;attempt++){if(!await ledgerExists(directory))try{await initLedger(directory,planId,payloadHash,authoritativePlan)}catch(error49){if(!(error49 instanceof Error&&error49.message.includes("Ledger already initialized")))throw error49}let events=await readLedgerEventsForEpoch(directory),existing=resolvePlanEpochIdentity(events,authoritativePlan);if(existing)return existing;if(events.length===0)throw Error("Plan ledger is empty; cannot adopt a plan epoch.");let rootEvent=events[0],rootEventHash=computeLedgerEventHash(rootEvent),tail=events[events.length-1],planEpoch=_internals32.randomUUID(),adoptionPayload={plan:authoritativePlan,payload_hash:payloadHash,plan_epoch:planEpoch,root_event_hash:rootEventHash};try{let appended=await _internals32.appendLedgerEvent(directory,{event_type:"snapshot",source:"plan_epoch_adopted",plan_id:planId,payload:adoptionPayload},{expectedSeq:tail.seq,expectedLedgerHash:tail.plan_hash_after,planHashAfter:payloadHash}),verifiedEvents=await readLedgerEventsForEpoch(directory),verified=verifiedEvents[verifiedEvents.length-1],verifiedPayload=asRecord(verified?.payload);if(!verified||verified.seq!==appended.seq||verified.event_type!=="snapshot"||verified.source!=="plan_epoch_adopted"||verified.plan_id!==planId||verifiedPayload?.plan_epoch!==planEpoch||verifiedPayload?.root_event_hash!==rootEventHash||verifiedPayload?.payload_hash!==payloadHash)throw Error(`Plan epoch adoption read verification failed for ${planId}.`);return{planId,planIdentityHash,planEpoch,rootEventHash,payloadHash,source:"plan_epoch_adopted"}}catch(error49){if(error49 instanceof LedgerStaleWriterError){lastStaleWriterError=error49;continue}throw error49}}throw Error(`Unable to settle plan epoch for ${planId} after repeated stale-writer retries.`,{cause:lastStaleWriterError})}async function appendLedgerEvent(directory,eventInput,options){return assertProjectRoot(directory),withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","append-ledger-event",async()=>{let ledgerPath=getLedgerPath(directory);if(options?.expectedLedgerHash!==void 0&&options.expectedSeq===void 0)throw Error("expectedLedgerHash requires expectedSeq so stale-projection recovery is bound to one exact ledger tail");let latestSeq=await getLatestLedgerSeq(directory),nextSeq=latestSeq+1,ledgerHashBefore;if(options?.expectedLedgerHash!==void 0){let events=await readLedgerEvents(directory),tail=events[events.length-1];if(!tail||tail.plan_hash_after!==options.expectedLedgerHash)throw new LedgerStaleWriterError(`Stale writer: expected ledger hash ${options.expectedLedgerHash} but found ${tail?.plan_hash_after??"<missing>"}`);ledgerHashBefore=tail.plan_hash_after}let planHashBefore=computeCurrentPlanHash(directory);if(options?.expectedSeq!==void 0&&options.expectedSeq!==latestSeq)throw new LedgerStaleWriterError(`Stale writer: expected seq ${options.expectedSeq} but found ${latestSeq}`);if(options?.expectedHash!==void 0&&options.expectedHash!==planHashBefore)throw new LedgerStaleWriterError(`Stale writer: expected hash ${options.expectedHash} but found ${planHashBefore}`);let planHashAfter=options?.planHashAfter??planHashBefore,event={...eventInput,seq:nextSeq,timestamp:new Date().toISOString(),plan_hash_before:ledgerHashBefore??planHashBefore,plan_hash_after:planHashAfter,schema_version:LEDGER_SCHEMA_VERSION};fs18.mkdirSync(path33.join(directory,".swarm"),{recursive:!0});let canonicalEvent=new TextEncoder().encode(serializeLedgerEvent(event));if((getPlanLedgerState(directory)?.authorityMode??"file_shadow")==="sqlite"){try{let existing=sqliteEventsAsLedger(directory);appendSqliteLedger(directory,{canonicalEvent,expectedSeq:latestSeq,state:stateForEvents(directory,[...existing.events,event],"sqlite")})}catch(error49){if(error49 instanceof SqliteLedgerStaleWriterError)throw new LedgerStaleWriterError(error49.message);throw error49}try{writePortableLedger(directory,sqliteEventsAsLedger(directory).lines)}catch(error49){criticalWarn(`[ledger] SQLite committed event ${event.seq}, but refreshing the portable plan-ledger.jsonl export failed: ${error49 instanceof Error?error49.message:String(error49)}. SQLite remains authoritative; a later read will retry the export.`)}}else{let tempPath=`${ledgerPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;if(!fs18.existsSync(ledgerPath))throw Error("Ledger not initialized. Call initLedger() first.");let existingContent=fs18.readFileSync(ledgerPath);writeFileFsyncedThenRename(tempPath,ledgerPath,Buffer.concat([existingContent,Buffer.from(canonicalEvent),Buffer.from(`
609
609
  `)]));try{appendSqliteLedger(directory,{canonicalEvent,expectedSeq:latestSeq,state:{authorityMode:"file_shadow",parityStatus:"pending"}})}catch(error49){log(`[ledger] SQLite shadow append deferred after file commit: ${error49 instanceof Error?error49.message:String(error49)}`)}}return event})}async function appendLedgerEventWithRetry(directory,eventInput,options){let maxRetries=options.maxRetries??3,backoffBase=options.backoffMs??10,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter})}catch(error49){if(!(error49 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error49;attempt++;let delayMs=backoffBase*2**(attempt-1);if(await new Promise((resolve18)=>setTimeout(resolve18,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function takeSnapshotWithRetry(directory,plan,options){let telemetrySource=options?.source??"save_plan_tool",snapshotOptions={planHashAfter:options?.planHashAfter},lastError;for(let attempt=1;attempt<=4;attempt++)try{await takeSnapshotEvent(directory,plan,snapshotOptions);return}catch(err){if(lastError=err instanceof Error?err:Error(String(err)),attempt<4)await new Promise((r)=>setTimeout(r,10*2**(attempt-1)))}criticalWarn(`[takeSnapshotWithRetry] Snapshot failed after 3 retries (4 attempts): ${lastError.message}`);try{emit("snapshot_failed",{error:lastError.message,retries:3,source:telemetrySource})}catch{}}async function takeSnapshotEvent(directory,plan,options){let payloadHash=options?.payloadHashOverride??(options?.source==="critic_approved"?computePlanStructureHash(plan):computePlanLedgerHash(plan)),snapshotPayload={plan,payload_hash:payloadHash};if(options?.approvalMetadata)snapshotPayload.approval=options.approvalMetadata;let planId=derivePlanId(plan);return appendLedgerEvent(directory,{event_type:"snapshot",source:options?.source??"takeSnapshotEvent",plan_id:planId,payload:snapshotPayload},{planHashAfter:options?.planHashAfter,expectedSeq:options?.expectedSeq,expectedLedgerHash:options?.expectedLedgerHash})}async function replaceTruncatedLedgerWithRecoveryRoot(directory,plan,expected){assertProjectRoot(directory);let validated=PlanSchema.parse(plan);return withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","reconcile-truncated-ledger",async()=>{let ledgerPath=getLedgerPath(directory);if(!fs18.existsSync(ledgerPath))throw new LedgerStaleWriterError("Stale writer: canonical ledger disappeared before truncated-ledger recovery");let events=await readLedgerEvents(directory),tail=events[events.length-1];if(!tail||tail.seq!==expected.seq||tail.plan_hash_after!==expected.ledgerHash||events[0]?.plan_id!==derivePlanId(validated))throw new LedgerStaleWriterError("Stale writer: ledger identity or tail changed before truncated-ledger recovery");let integrity=await readLedgerEventsWithIntegrity(directory);if(!integrity.truncated||integrity.badSuffix===null)throw new LedgerStaleWriterError("Stale writer: ledger is no longer truncated; retry against its current tail");let originalBytes=fs18.readFileSync(ledgerPath),archiveSha256=crypto3.createHash("sha256").update(originalBytes).digest("hex"),swarmDir=path33.dirname(ledgerPath),archiveSuffix=`.${archiveSha256.slice(0,12)}.jsonl`,archiveName=`plan-ledger.reconcile-archive.${Date.now()}.${Math.floor(Math.random()*1e9)}${archiveSuffix}`,archivePath=path33.join(swarmDir,archiveName),archiveNeedsWrite=!0;for(let candidate of _internals32.readLedgerDirectory(swarmDir).sort(compareCodeUnits)){if(!candidate.startsWith("plan-ledger.reconcile-archive.")||!candidate.endsWith(archiveSuffix))continue;let candidatePath=path33.join(swarmDir,candidate);if(fs18.readFileSync(candidatePath).equals(originalBytes)){archiveName=candidate,archivePath=candidatePath,archiveNeedsWrite=!1;break}}let archiveTempPath=`${archivePath}.tmp.${crypto3.randomBytes(16).toString("hex")}`,canonicalTempPath=`${ledgerPath}.reconcile.${crypto3.randomBytes(16).toString("hex")}.tmp`,planHash=computePlanLedgerHash(validated),rawBadSuffix=findRawMalformedSuffix(originalBytes);if(rawBadSuffix.length===0)throw new LedgerStaleWriterError("Stale writer: raw ledger bytes no longer contain the malformed suffix detected during replay");let badSuffixSha256=crypto3.createHash("sha256").update(rawBadSuffix).digest("hex"),recoveryRoot={seq:1,timestamp:new Date().toISOString(),plan_id:derivePlanId(validated),event_type:"plan_created",source:"save_plan_truncated_ledger_reconcile",plan_hash_before:"",plan_hash_after:planHash,schema_version:LEDGER_SCHEMA_VERSION,payload:{plan:validated,payload_hash:planHash,recovery:{kind:"truncated_ledger_reconcile",archived_ledger:`.swarm/${archiveName}`,archived_sha256:archiveSha256,bad_suffix_sha256:badSuffixSha256,prior_tail_seq:expected.seq,prior_tail_hash:expected.ledgerHash}}};try{if(archiveNeedsWrite)_internals32.writeFileFsyncedThenRename(archiveTempPath,archivePath,originalBytes);_internals32.fsyncRecoveryDirectory(swarmDir),_internals32.writeFileFsyncedThenRename(canonicalTempPath,ledgerPath,`${JSON.stringify(recoveryRoot)}
610
610
  `)}finally{for(let tempPath of[archiveTempPath,canonicalTempPath])try{fs18.unlinkSync(tempPath)}catch{}}return{archivePath,archiveSha256,recoveryRoot}})}async function clearPlanLedgerForReset(directory){assertProjectRoot(directory),await withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","reset-plan-ledger",async()=>{let marker=path33.join(directory,".swarm","plan-ledger.resetting");fs18.writeFileSync(marker,`resetting
611
- `,"utf8");try{clearSqliteLedger(directory);try{fs18.unlinkSync(getLedgerPath(directory))}catch(error49){if(error49?.code!=="ENOENT")throw error49}}finally{try{fs18.unlinkSync(marker)}catch{}}})}async function replacePlanLedgerWithRoot(directory,plan,source){assertProjectRoot(directory);let validated=PlanSchema.parse(plan);await withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","replace-plan-ledger-root",async()=>{let ledgerPath=getLedgerPath(directory);if(fs18.existsSync(ledgerPath))archiveLegacyLedger(directory,fs18.readFileSync(ledgerPath));let planHash=computePlanLedgerHash(validated),root={seq:1,timestamp:new Date().toISOString(),plan_id:derivePlanId(validated),event_type:"plan_created",source,plan_hash_before:"",plan_hash_after:planHash,schema_version:LEDGER_SCHEMA_VERSION,payload:{plan:validated,payload_hash:planHash,plan_epoch:crypto3.randomUUID()}},line=new TextEncoder().encode(serializeLedgerEvent(root)),priorMode=getPlanLedgerState(directory)?.authorityMode??"file_shadow";if(priorMode==="file_shadow"){writePortableLedger(directory,[line]);try{replaceSqliteLedger(directory,{canonicalEvents:[line],state:stateForEvents(directory,[root],priorMode),source:source==="savePlan_identity_migration"?"plan_identity_reinitialized":"checkpoint_rollback",mode:priorMode,version:package_default.version})}catch(error49){log(`[ledger] SQLite shadow re-root deferred after authoritative file commit: ${error49 instanceof Error?error49.message:String(error49)}`)}return}replaceSqliteLedger(directory,{canonicalEvents:[line],state:stateForEvents(directory,[root],priorMode),source:"checkpoint_rollback",mode:priorMode,version:package_default.version});try{writePortableLedger(directory,[line])}catch(error49){criticalWarn(`[ledger] SQLite committed rollback root, but refreshing the portable plan-ledger.jsonl export failed: ${error49 instanceof Error?error49.message:String(error49)}. SQLite remains authoritative; a later read will retry the export.`)}})}async function replayFromLedger(directory,options){let{plan}=await replayFromLedgerWithStatus(directory,options);return plan}async function peekPlanFromLedger(directory,_options){if(fs18.existsSync(path33.join(directory,".swarm","plan-ledger.resetting")))return{plan:null,truncated:!1,badSuffix:null};let file2=readFileLedgerExact(directory),events=file2.events,truncated=file2.truncated,badSuffix=file2.badSuffix,sqliteReadOnly=readSqliteLedgerEventsReadOnly(directory);if(fs18.existsSync(path33.join(directory,".swarm","plan-ledger.resetting")))return{plan:null,truncated:!1,badSuffix:null};if(sqliteReadOnly.events.length>0){let sqlite={events:sqliteReadOnly.events.map((row)=>row.event)};if(sqliteReadOnly.state?.authorityMode==="sqlite"||events.length===0)events=sqlite.events,truncated=!1,badSuffix=null}if(events.length===0)return{plan:null,truncated,badSuffix};return{plan:reconstructPlanFromEvents(directory,events),truncated,badSuffix}}async function replayFromLedgerWithStatus(directory,_options){let{events,truncated,badSuffix}=await readLedgerEventsWithIntegrity(directory);if(events.length===0)return{plan:null,truncated,badSuffix};if(truncated&&badSuffix!==null)await quarantineLedgerSuffix(directory,badSuffix);return{plan:reconstructPlanFromEvents(directory,events),truncated,badSuffix}}function reconstructPlanFromEvents(directory,events){let targetPlanId=events[0].plan_id,relevantEvents=events.filter((e)=>e.plan_id===targetPlanId);{let snapshotEvents=relevantEvents.filter((e)=>e.event_type==="snapshot");if(snapshotEvents.length>0){let latestSnapshotEvent=snapshotEvents[snapshotEvents.length-1],plan2=latestSnapshotEvent.payload.plan,eventsAfterSnapshot=relevantEvents.filter((e)=>e.seq>latestSnapshotEvent.seq);for(let event of eventsAfterSnapshot)if(plan2=applyEventToPlan(plan2,event),plan2===null)return null;return plan2}}let createdEvent=relevantEvents.find((e)=>e.event_type==="plan_created");if(createdEvent?.payload&&typeof createdEvent.payload==="object"&&"plan"in createdEvent.payload){let parseResult=PlanSchema.safeParse(createdEvent.payload.plan);if(parseResult.success){let plan2=parseResult.data,eventsAfterCreated=relevantEvents.filter((e)=>e.seq>createdEvent.seq);for(let event of eventsAfterCreated){if(plan2===null)return null;plan2=applyEventToPlan(plan2,event)}return plan2}}let planJsonPath=getPlanJsonPath(directory);if(!fs18.existsSync(planJsonPath))return null;let plan;try{let content=fs18.readFileSync(planJsonPath,"utf8");plan=JSON.parse(content)}catch{return null}for(let event of relevantEvents){if(plan===null)return null;plan=applyEventToPlan(plan,event)}return plan}function applyEventToPlan(plan,event){switch(event.event_type){case"plan_created":if(event.payload&&typeof event.payload==="object"&&"plan"in event.payload){let parsed=PlanSchema.safeParse(event.payload.plan);if(parsed.success)return parsed.data}return plan;case"task_status_changed":if(event.task_id&&event.to_status){let parseResult=TaskStatusSchema.safeParse(event.to_status);if(!parseResult.success)return plan;for(let phase of plan.phases){let task=phase.tasks.find((t)=>t.id===event.task_id);if(task){task.status=parseResult.data;break}}}return plan;case"phase_completed":if(event.phase_id){let phase=plan.phases.find((p)=>p.id===event.phase_id);if(phase)phase.status="complete"}return plan;case"plan_exported":return plan;case"task_added":return plan;case"task_removed":if(event.task_id)for(let phase of plan.phases){let idx=phase.tasks.findIndex((t)=>t.id===event.task_id);if(idx!==-1){phase.tasks.splice(idx,1);break}}return plan;case"task_updated":return plan;case"plan_rebuilt":return plan;case"task_reordered":return plan;case"snapshot":return plan;case"plan_reset":return null;case"execution_profile_set":{let rawProfile=event.payload?.execution_profile;if(rawProfile!==void 0){let parsed=ExecutionProfileSchema.safeParse(rawProfile);if(parsed.success)return{...plan,execution_profile:parsed.data}}return plan}case"execution_profile_locked":{if(plan.execution_profile)return{...plan,execution_profile:{...plan.execution_profile,locked:!0}};return plan}default:throw Error(`applyEventToPlan: unhandled event type "${event.event_type}" at seq ${event.seq}`)}}async function readLedgerEventsWithIntegrity(directory,options){let ledgerPath=getLedgerPath(directory);if(!fs18.existsSync(ledgerPath)&&!hasSqliteLedger(directory))return{events:[],truncated:!1,badSuffix:null};try{let result=coordinateLedger(directory);return{events:[...result.events].sort((a,b)=>a.seq-b.seq),truncated:result.truncated,badSuffix:result.badSuffix}}catch(error49){if(options?.failClosedOnReadError)throw Error(`PLAN_LEDGER_UNREADABLE: ${ledgerPath} exists but could not be read (${error49 instanceof Error?error49.message:String(error49)}); plan state cannot be resolved. This is NOT an absent ledger — preserve the file and check permissions/filesystem health before retrying.`);let code=error49?.code;if(code&&["EACCES","EIO","EISDIR","EPERM"].includes(code))return{events:[],truncated:!1,badSuffix:null};throw error49}}async function quarantineLedgerSuffix(directory,badSuffix){let salvagedCount=0;for(let line of badSuffix.split(`
612
- `)){if(line.trim()==="")continue;try{JSON.parse(line),salvagedCount++}catch{}}try{assertProjectRoot(directory);let hash2=crypto3.createHash("sha256").update(badSuffix,"utf8").digest("hex").slice(0,12),swarmDir=path33.join(directory,".swarm");try{let existing=_internals32.readLedgerDirectory(swarmDir).sort(compareCodeUnits).filter((name)=>name.startsWith("plan-ledger.quarantine.")&&name.endsWith(`.${hash2}`));for(let name of existing){let existingPath=path33.join(swarmDir,name);if(fs18.readFileSync(existingPath,"utf8")===badSuffix)return{path:existingPath,salvagedCount}}}catch{}let quarantinePath=path33.join(swarmDir,`plan-ledger.quarantine.${Date.now()}.${hash2}`);return fs18.writeFileSync(quarantinePath,badSuffix,"utf8"),log(`[ledger] Corrupted suffix quarantined to ${path33.relative(directory,quarantinePath)} (salvageable events: ${salvagedCount})`),{path:quarantinePath,salvagedCount}}catch{return{path:null,salvagedCount}}}async function loadLastApprovedPlan(directory,expectedPlanId){let events=await readLedgerEvents(directory);return findLastApprovedSnapshot(events,expectedPlanId)}async function loadLastPlanCriticApprovedSnapshot(directory,expectedPlanId){let events=await readLedgerEvents(directory);return findLastApprovedSnapshot(events,expectedPlanId,(payload)=>payload.approval?.source==="plan_critic_gate")}function findLastApprovedSnapshot(events,expectedPlanId,extraFilter){if(events.length===0)return null;for(let i=events.length-1;i>=0;i--){let event=events[i];if(event.event_type!=="snapshot")continue;if(event.source!=="critic_approved")continue;if(expectedPlanId!==void 0&&event.plan_id!==expectedPlanId)continue;let payload=event.payload;if(!payload||typeof payload!=="object"||!payload.plan)continue;if(expectedPlanId!==void 0){if(derivePlanId(payload.plan)!==expectedPlanId)continue}if(extraFilter&&!extraFilter(payload))continue;return{plan:payload.plan,seq:event.seq,timestamp:event.timestamp,approval:payload.approval,payloadHash:payload.payload_hash}}return null}var LEDGER_SCHEMA_VERSION="1.1.0",LEDGER_FILENAME="plan-ledger.jsonl",LEDGER_LOCK_PATH,PLAN_JSON_FILENAME="plan.json",LedgerStaleWriterError,_internals32;var init_ledger=__esm(()=>{init_package();init_plan_schema();init_lock();init_telemetry();init_logger();init_project_boundary();init_ledger_sqlite();init_planning_profile();init_utils3();LEDGER_LOCK_PATH=path33.join(".swarm",LEDGER_FILENAME);LedgerStaleWriterError=class LedgerStaleWriterError extends Error{constructor(message){super(message);this.name="LedgerStaleWriterError"}};_internals32={computePlanLedgerHash,computePlanStructureHash,computeCurrentPlanHash,ledgerExists,getLatestLedgerSeq,readLedgerEvents,initLedger,appendLedgerEvent,appendLedgerEventWithRetry,takeSnapshotEvent,replayFromLedger,replayFromLedgerWithStatus,peekPlanFromLedger,applyEventToPlan,readLedgerEventsWithIntegrity,quarantineLedgerSuffix,loadLastApprovedPlan,loadLastPlanCriticApprovedSnapshot,getLedgerPath,getPlanJsonPath,archiveLegacyLedger,writePortableLedger,writeFileFsyncedThenRename,fsyncRecoveryDirectory,readLedgerDirectory,randomUUID:()=>crypto3.randomUUID()}});import{randomUUID as randomUUID8}from"node:crypto";import*as path34 from"node:path";function newIdentity(){return randomUUID8()}function isScopeBindingIdentity(value){return typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(value)}function canonicalWorkspaceIdentity(directory){return canonicalExistingFilesystemPath(directory)}function isStrictTaskId2(value){return/^\d+\.\d+(?:\.\d+)*$/.test(value)}function normalizeScopePath(value){if(typeof value!=="string")return null;if(unsafePathTextReason(value))return null;let trimmed=value.trim().replace(/\\/g,"/");if(trimmed.length===0||trimmed.includes("\x00")||trimmed.split("/").includes("..")||path34.posix.isAbsolute(trimmed)||/^[A-Za-z]:\//.test(trimmed))return null;let normalized=path34.posix.normalize(trimmed).replace(/^\.\//,"");if(normalized==="."||normalized===".."||normalized.startsWith("../"))return null;return normalized.endsWith("/")?normalized.slice(0,-1):normalized}function normalizeScopeFiles(files){if(!Array.isArray(files)||files.length===0||files.length>1e4)return null;let normalized=new Set,totalBytes=0;for(let file2 of files){let candidate=normalizeScopePath(file2);if(!candidate)return null;let bytes=Buffer.byteLength(candidate,"utf8");if(totalBytes+=bytes,bytes>MAX_SCOPE_PATH_BYTES||totalBytes>MAX_SCOPE_FILES_BYTES)return null;normalized.add(candidate)}return normalized.size>0?[...normalized].sort():null}function bindingKey(binding){return binding.generationId}function createScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),ttlMs=Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS);return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:derivePlanId(input.plan),planStructureHash:computePlanStructureHash(input.plan),taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:input.source,files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+ttlMs}}function sweepExpired(now=Date.now()){for(let[key,binding]of pendingScopeBindings)if(binding.expiresAt<=now){pendingScopeBindings.delete(key);let expired={...binding,revision:binding.revision+1,lifecycleState:"expired",updatedAt:now};scopeBindingTombstones.set(bindingKey(expired),expired)}while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function registerScopeBinding(binding){if(sweepExpired(),binding.lifecycleState!=="live"||binding.expiresAt<=Date.now())return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"Only an unexpired live binding can be admitted."};let exact=pendingScopeBindings.get(bindingKey(binding));if(exact&&exact.bindingId!==binding.bindingId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"The generation identity collides with a different binding."};if(exact&&exact.revision>binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"A newer revision of this generation is already admitted."};if(binding.activation==="declaration"&&binding.dispatchCallId===void 0){for(let[existingKey,existing]of pendingScopeBindings)if(existing.generationId!==binding.generationId&&existing.activation==="declaration"&&existing.dispatchCallId===void 0&&existing.workspaceIdentity===binding.workspaceIdentity&&existing.taskId===binding.taskId&&existing.ownerSessionId===binding.ownerSessionId)pendingScopeBindings.delete(existingKey),scopeBindingTombstones.set(existingKey,{...existing,revision:existing.revision+1,lifecycleState:"superseded",updatedAt:Date.now()})}if(!exact&&pendingScopeBindings.size>=MAX_PENDING_SCOPE_BINDINGS)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:`Scope binding capacity ${MAX_PENDING_SCOPE_BINDINGS} is exhausted; complete or expire a live task before retrying.`};let key=bindingKey(binding);return pendingScopeBindings.delete(key),pendingScopeBindings.set(key,binding),{ok:!0,binding}}function getScopeBindingForParentDispatch(input){if(sweepExpired(),!input.parentSessionId.trim()||!input.dispatchCallId.trim())return null;let active=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.parentCallId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);if(active.length>1)return null;if(active.length===1)return active[0];let pending=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.ownerMessageId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);return pending.length===1?pending[0]:null}function getActiveScopeBindingsForSession(input){sweepExpired();let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity||!input.activeSessionId.trim())return[];let now=Date.now();return[...pendingScopeBindings.values()].filter((binding)=>binding.workspaceIdentity===workspaceIdentity&&binding.ownerSessionId===input.activeSessionId&&binding.activation==="active"&&binding.lifecycleState==="live"&&binding.expiresAt>now&&isDispatchCorrelated(binding))}function isDispatchCorrelated(binding){return typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId}function createPrFeedbackScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!input.workflowSessionId.trim()||!input.workflowRevisionDigest.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),workflowIdentity=`pr-feedback:${input.workflowSessionId}`;return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:workflowIdentity,planStructureHash:input.workflowRevisionDigest,taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:"pr_feedback",files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS,workflowSessionId:input.workflowSessionId,workflowRevisionDigest:input.workflowRevisionDigest}}function getAuthorizedPrFeedbackScopeBinding(input){sweepExpired();let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity||!input.activeSessionId.trim())return null;let matches=[...pendingScopeBindings.values()].filter((binding)=>binding.workspaceIdentity===workspaceIdentity&&binding.source==="pr_feedback"&&binding.activation==="active"&&binding.ownerSessionId===input.activeSessionId&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&typeof binding.workflowSessionId==="string"&&binding.workflowSessionId===binding.parentOwnerSessionId&&typeof binding.workflowRevisionDigest==="string"&&binding.workflowRevisionDigest.length>0&&binding.planId===`pr-feedback:${binding.workflowSessionId}`&&binding.planStructureHash===binding.workflowRevisionDigest);return matches.length===1?matches[0]:null}function describeScopeWorkspaceMismatch(input){if(sweepExpired(),!input.activeSessionId.trim())return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity)return null;let first=[...pendingScopeBindings.values()].filter((binding)=>binding.ownerSessionId===input.activeSessionId&&binding.activation==="active"&&binding.source!=="pr_feedback"&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&binding.workspaceIdentity!==workspaceIdentity)[0];if(!first)return null;return`SCOPE_WORKSPACE_MISMATCH: an active scope binding for session "${sanitizeDiagnosticText(input.activeSessionId)}" (task ${first.taskId}, source ${first.source}) is rooted at "${sanitizeDiagnosticText(first.workspaceIdentity)}", but this gate resolved "${sanitizeDiagnosticText(workspaceIdentity)}". The gate is using the wrong workspace root for this session.`}function clearScopeBindings(predicate){let removed=[];if(!predicate)return removed.push(...pendingScopeBindings.values()),pendingScopeBindings.clear(),scopeBindingTombstones.clear(),removed;for(let[key,binding]of pendingScopeBindings)if(predicate(binding))removed.push(binding),pendingScopeBindings.delete(key);return removed}function clearExactScopeBinding(input){let candidate=pendingScopeBindings.get(input.generationId);if(!candidate||candidate.bindingId!==input.bindingId)return null;return pendingScopeBindings.delete(input.generationId),candidate}function installScopeBindingTombstone(binding){pendingScopeBindings.delete(binding.generationId),scopeBindingTombstones.delete(binding.generationId),scopeBindingTombstones.set(binding.generationId,binding);while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function hasScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live")}function hasDeliberateScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live"&&tombstone.lifecycleState!=="expired")}function clearSweepTombstoneForRevival(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);if(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.lifecycleState==="expired"&&tombstone.revision<=binding.revision)scopeBindingTombstones.delete(binding.generationId)}function installFailedRevocationOverlay(binding,reason){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||current.revision!==binding.revision)return!1;let now=Date.now();return installScopeBindingTombstone({...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)}),!0}function installScopeBindingRetirementIntent(binding){let source=pendingScopeBindings.get(binding.generationId)??(binding.version===2?binding:null);if(!source||source.bindingId!==binding.bindingId)return null;let now=Date.now(),tombstone={...source,revision:source.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(source.expiresAt,now)};return installScopeBindingTombstone(tombstone),tombstone}function updateExactScopeBinding(binding){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||binding.revision<=current.revision)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"The exact binding generation is stale or no longer active."};return pendingScopeBindings.set(binding.generationId,binding),{ok:!0,binding}}function createClaimedScopeBinding(previous,input){let now=Date.now();return{...previous,generationId:newIdentity(),revision:1,ownerSessionId:input.childSessionId,childSessionId:input.childSessionId,ownerMessageId:input.dispatchCallId,dispatchCallId:input.dispatchCallId,parentOwnerSessionId:input.parentSessionId,parentCallId:input.dispatchCallId,activation:"active",predecessorGenerationId:previous.generationId,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function deriveChildScopeBinding(parent,input){let workspaceIdentity=canonicalWorkspaceIdentity(input.childDirectory);if(!workspaceIdentity||!input.childSessionId.trim()||!input.parentCallId.trim())throw Error("Cannot derive child scope binding without verified identity");let now=Date.now();return{...parent,generationId:newIdentity(),revision:1,workspaceIdentity,ownerSessionId:input.childSessionId,ownerMessageId:input.parentCallId,dispatchCallId:input.parentCallId,activation:"active",parentOwnerSessionId:parent.ownerSessionId,parentCallId:input.parentCallId,predecessorGenerationId:parent.generationId,childSessionId:input.childSessionId,source:"worktree_derived",declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function scopeContains(scope,candidate){let flavor=getPathFlavor(),candidateIdentity=normalizePathIdentity(candidate,flavor).replace(/\\/g,"/");return scope.some((entry)=>{let entryIdentity=normalizePathIdentity(entry,flavor).replace(/\\/g,"/");return candidateIdentity===entryIdentity||candidateIdentity.startsWith(`${entryIdentity}/`)})}function isSubset(candidate,authority){return candidate.every((file2)=>scopeContains(authority,file2))}function resolveCoderScopeSources(input){let explicit=input.explicitFiles&&input.explicitFiles.length>0?normalizeScopeFiles(input.explicitFiles):null,plan=input.planFiles&&input.planFiles.length>0?normalizeScopeFiles(input.planFiles):null,directives=input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0?normalizeScopeFiles(input.fileDirectiveFiles):null;if(input.explicitFiles&&input.explicitFiles.length>0&&!explicit)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.planFiles&&input.planFiles.length>0&&!plan)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0&&!directives)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(explicit){let conflict=plan&&!isSubset(plan,explicit)?{source:"plan",files:plan}:directives&&!isSubset(directives,explicit)?{source:"file_directive",files:directives}:null;if(conflict)return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"declare_scope",authoritativeFiles:explicit,conflictingSource:conflict.source,conflictingFiles:conflict.files,disagreement:conflict.files.filter((file2)=>!scopeContains(explicit,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:explicit,source:"declare_scope"}}if(plan){if(directives&&!isSubset(directives,plan))return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"plan",authoritativeFiles:plan,conflictingSource:"file_directive",conflictingFiles:directives,disagreement:directives.filter((file2)=>!scopeContains(plan,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:plan,source:"plan"}}if(directives)return{ok:!0,files:directives,source:"file_directive"};return{ok:!1,code:"SCOPE_NOT_DECLARED"}}function renderSet(values,max=8){if(!values)return"(none)";return`${values.slice(0,max).map((value)=>JSON.stringify(value)).join(", ")}${values.length>max?`, … +${values.length-max}`:""}`}function formatCoderScopeConflict(decision){if(decision.code!=="SCOPE_CONFLICT")return"SCOPE_NOT_DECLARED: coder delegation has no complete, valid, non-empty scope.";return`SCOPE_CONFLICT: ${decision.authoritativeSource} authority [${renderSet(decision.authoritativeFiles)}] does not cover ${decision.conflictingSource} [${renderSet(decision.conflictingFiles)}]; outside authority: [${renderSet(decision.disagreement)}]. Architect: reconcile save_plan(files_touched), FILE directives, or declare_scope, then dispatch a new Task call.`}var MAX_PENDING_SCOPE_BINDINGS=256,DEFAULT_SCOPE_BINDING_TTL_MS=3600000,MAX_SCOPE_BINDING_TOMBSTONES=256,pendingScopeBindings,scopeBindingTombstones,MAX_SCOPE_PATH_BYTES=4096,MAX_SCOPE_FILES_BYTES=1048576;var init_scope_binding=__esm(()=>{init_ledger();init_utils3();init_filesystem_identity();init_path_identity();pendingScopeBindings=new Map,scopeBindingTombstones=new Map});var exports_scope_persistence={};__export(exports_scope_persistence,{writeScopeToDisk:()=>writeScopeToDisk,writeScopeBindingToDisk:()=>writeScopeBindingToDisk,tombstoneScopeBinding:()=>tombstoneScopeBinding,resolveScopeWithFallbacks:()=>resolveScopeWithFallbacks,resolveScopeBindingFromDisk:()=>resolveScopeBindingFromDisk,resolveAuthorizedScopeBindingForSessionDetailed:()=>resolveAuthorizedScopeBindingForSessionDetailed,resolveAuthorizedScopeBindingForSession:()=>resolveAuthorizedScopeBindingForSession,resolveAuthorizedScopeBindingDetailed:()=>resolveAuthorizedScopeBindingDetailed,resolveAuthorizedScopeBinding:()=>resolveAuthorizedScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk:()=>resolveAuthorizedPrFeedbackScopeBindingFromDisk,replaceExistingScopeDeclaration:()=>replaceExistingScopeDeclaration,refreshScopeBindingLease:()=>refreshScopeBindingLease,readScopeFromDisk:()=>readScopeFromDisk,readScopeBindingFromDisk:()=>readScopeBindingFromDisk,readPlanScope:()=>readPlanScope,pruneScopeBindingTombstones:()=>pruneScopeBindingTombstones,persistAndRegisterScopeBinding:()=>persistAndRegisterScopeBinding,flushScopeBindingMaintenance:()=>flushScopeBindingMaintenance,clearScopeForTask:()=>clearScopeForTask,clearScopeBindingFromDisk:()=>clearScopeBindingFromDisk,clearAllScopes:()=>clearAllScopes,claimScopeBindingForChildDurably:()=>claimScopeBindingForChildDurably,_scopePersistenceInternals:()=>_scopePersistenceInternals});import{createHash as createHash19}from"node:crypto";import*as fs19 from"node:fs";import*as path35 from"node:path";function getScopesDir(directory){return path35.join(directory,SCOPES_DIR)}function normalizePathForComparison(value){let normalized=path35.resolve(value);return process.platform==="win32"?normalized.toLowerCase():normalized}function isSafeTaskId(taskId){if(typeof taskId!=="string")return!1;if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(taskId))return!1;let head=taskId.replace(/\.+$/,"").split(".")[0].toUpperCase();if(WINDOWS_RESERVED.has(head))return!1;return!0}function isScopesDirSafe(directory,scopesDir){try{let resolvedWorkspace=fs19.realpathSync(directory),expectedSwarmDir=path35.join(resolvedWorkspace,".swarm"),expectedScopesDir=path35.join(expectedSwarmDir,"scopes"),swarmStat=fs19.lstatSync(expectedSwarmDir),scopesStat=fs19.lstatSync(expectedScopesDir);if(!swarmStat.isDirectory()||swarmStat.isSymbolicLink()||!scopesStat.isDirectory()||scopesStat.isSymbolicLink())return!1;let resolvedScopes=fs19.realpathSync(scopesDir);if(normalizePathForComparison(resolvedScopes)!==normalizePathForComparison(expectedScopesDir))return!1;let rel=path35.relative(resolvedWorkspace,resolvedScopes);return rel.length>0&&!rel.startsWith("..")&&!path35.isAbsolute(rel)}catch{return!1}}function resolveSafeScopeFileForUnlink(directory,targetPath){try{let resolvedWorkspace=fs19.realpathSync(directory),scopesDir=path35.join(resolvedWorkspace,SCOPES_DIR);if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let candidate=path35.resolve(targetPath),resolvedCandidate=fs19.realpathSync(candidate);if(normalizePathForComparison(path35.dirname(candidate))!==normalizePathForComparison(scopesDir)||normalizePathForComparison(resolvedCandidate)!==normalizePathForComparison(candidate))return null;let relative7=path35.relative(resolvedWorkspace,resolvedCandidate);if(relative7.length===0||relative7===".."||relative7.startsWith(`..${path35.sep}`)||path35.isAbsolute(relative7))return null;let leafStat=fs19.lstatSync(candidate);if(!leafStat.isFile()||leafStat.isSymbolicLink())return null;if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let finalResolvedCandidate=fs19.realpathSync(candidate),finalLeafStat=fs19.lstatSync(candidate);if(normalizePathForComparison(finalResolvedCandidate)!==normalizePathForComparison(candidate)||!finalLeafStat.isFile()||finalLeafStat.isSymbolicLink()||finalLeafStat.dev!==leafStat.dev||finalLeafStat.ino!==leafStat.ino)return null;return candidate}catch{return null}}function getScopeFilePath(directory,taskId){if(!isSafeTaskId(taskId))throw Error(`Invalid taskId for scope persistence: ${taskId}`);return path35.join(getScopesDir(directory),`scope-${taskId}.json`)}function getLegacyBindingFilePath(directory,taskId,ownerSessionId){if(!isSafeTaskId(taskId)||!ownerSessionId.trim())throw Error("Invalid identity for scope binding persistence");let ownerHash=createHash19("sha256").update(ownerSessionId).digest("hex").slice(0,24);return path35.join(getScopesDir(directory),`binding-${taskId}-${ownerHash}.json`)}function getBindingFilePath(directory,binding){if(!isSafeTaskId(binding.taskId)||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId))throw Error("Invalid exact identity for scope binding persistence");return path35.join(getScopesDir(directory),`binding-${binding.taskId}-${binding.bindingId}-${binding.generationId}.json`)}function getGenerationLockPath(bindingPath){return`${bindingPath}.generation-lock`}function getRetirementIntentPath(bindingPath){return`${bindingPath}.retirement-intent`}function hasDurableRetirementIntent(bindingPath,binding){let raw=readBoundedFile(getRetirementIntentPath(bindingPath));if(!raw)return!1;try{let intent=JSON.parse(raw);return intent.bindingId===binding.bindingId&&intent.generationId===binding.generationId}catch{return!1}}function ensureLockTargetSync(targetPath){try{let scopesDir=path35.dirname(targetPath),swarmDir=path35.dirname(scopesDir);if(path35.basename(scopesDir)!=="scopes"||path35.basename(swarmDir)!==".swarm")return!1;assertProjectRoot(path35.dirname(swarmDir)),fs19.mkdirSync(path35.dirname(targetPath),{recursive:!0});let nofollow=fs19.constants.O_NOFOLLOW??0,fd=fs19.openSync(targetPath,fs19.constants.O_WRONLY|fs19.constants.O_CREAT|nofollow);return fs19.closeSync(fd),!0}catch{return!1}}function readBoundedFile(filePath){let nofollow=fs19.constants.O_NOFOLLOW??0,fd;try{fd=fs19.openSync(filePath,fs19.constants.O_RDONLY|nofollow)}catch{return null}try{let stat7=fs19.fstatSync(fd);if(!stat7.isFile()||stat7.size<=0||stat7.size>MAX_SCOPE_BYTES)return null;let buffer=Buffer.alloc(stat7.size);return fs19.readSync(fd,buffer,0,stat7.size,0),buffer.toString("utf8")}catch{return null}finally{try{fs19.closeSync(fd)}catch{}}}function scopeBindingArchivePath(filePath){return`${filePath}.imported`}function collisionSafeScopeBindingArchivePath(filePath){let canonical=scopeBindingArchivePath(filePath);if(!fs19.existsSync(canonical))return canonical;for(let suffix=1;suffix<=1e4;suffix+=1){let candidate=`${canonical}.${suffix}`;if(!fs19.existsSync(candidate))return candidate}throw Error(`No collision-safe archive path available for ${path35.basename(filePath)}.`)}function scopeBindingShadowPayload(binding){return JSON.stringify(binding,null,2)}function coordinationScopeEntityKey(binding){return binding.generationId}function parseCoordinationScopeBinding(directory,row){try{let binding=validateScopeBindingPayload(directory,JSON.parse(row.payload));if(!binding||binding.generationId!==row.entityKey||binding.revision!==row.revision||binding.lifecycleState!==row.status)return null;return binding}catch{return null}}function transitionScopeBindingState(directory,binding,expectedRevision){let payload=scopeBindingShadowPayload(binding),idempotencyKey=createHash19("sha256").update(`${binding.bindingId}\x00${binding.generationId}\x00${binding.revision}\x00${binding.lifecycleState}\x00${payload}`).digest("hex");try{let result=transitionCoordinationState(directory,{namespace:SCOPE_BINDING_COORDINATION_NAMESPACE,entityKey:coordinationScopeEntityKey(binding),expectedRevision,generation:1,status:binding.lifecycleState,payload,event:{streamId:`scope-binding:${binding.bindingId}`,idempotencyKey,eventType:binding.lifecycleState,payload}});if(result.outcome!=="applied"&&result.outcome!=="duplicate")return{ok:!1,code:result.outcome==="revision_conflict"||result.outcome==="stale_generation"?"SCOPE_BINDING_STALE":"SCOPE_BINDING_PERSISTENCE_FAILED",message:`Scope binding transition failed: ${result.outcome}.`};let persisted=result.state&&parseCoordinationScopeBinding(directory,result.state);return persisted?{ok:!0,value:persisted}:persistenceFailure("Scope binding transition could not be re-read from coordination state.")}catch(error49){return persistenceFailure(`Scope binding transition failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}function transitionScopeBindingStateWithinTransaction(directory,binding,expectedRevision){let payload=scopeBindingShadowPayload(binding),idempotencyKey=createHash19("sha256").update(`${binding.bindingId}\x00${binding.generationId}\x00${binding.revision}\x00${binding.lifecycleState}\x00${payload}`).digest("hex");try{let result=transitionCoordinationStateWithinTransaction(directory,{namespace:SCOPE_BINDING_COORDINATION_NAMESPACE,entityKey:coordinationScopeEntityKey(binding),expectedRevision,generation:1,status:binding.lifecycleState,payload,event:{streamId:`scope-binding:${binding.bindingId}`,idempotencyKey,eventType:binding.lifecycleState,payload}});if(result.outcome!=="applied"&&result.outcome!=="duplicate")return{ok:!1,code:result.outcome==="revision_conflict"||result.outcome==="stale_generation"?"SCOPE_BINDING_STALE":"SCOPE_BINDING_PERSISTENCE_FAILED",message:`Scope binding transition failed: ${result.outcome}.`};let persisted=result.state&&parseCoordinationScopeBinding(directory,result.state);return persisted?{ok:!0,value:persisted}:persistenceFailure("Scope binding transition could not be re-read from coordination state.")}catch(error49){return persistenceFailure(`Scope binding transition failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}function coordinationTimestampFromMs(value,label){if(!Number.isFinite(value))throw Error(`${label} must be a finite epoch-millisecond timestamp.`);let iso=new Date(value).toISOString();if(Number.isNaN(Date.parse(iso)))throw Error(`${label} must be a valid epoch-millisecond timestamp.`);return iso}function importScopeBindingStateRows(directory,bindings){let db=getProjectDb(directory);for(let binding of bindings){if(!Number.isSafeInteger(binding.revision)||binding.revision<1)throw Error(`Legacy binding ${binding.generationId} has invalid revision ${binding.revision}.`);db.run(`INSERT INTO coordination_state
611
+ `,"utf8");try{clearSqliteLedger(directory);try{fs18.unlinkSync(getLedgerPath(directory))}catch(error49){if(error49?.code!=="ENOENT")throw error49}}finally{try{fs18.unlinkSync(marker)}catch{}}})}async function replacePlanLedgerWithRoot(directory,plan,source){assertProjectRoot(directory);let validated=PlanSchema.parse(plan);await withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","replace-plan-ledger-root",async()=>{let ledgerPath=getLedgerPath(directory);if(fs18.existsSync(ledgerPath))archiveLegacyLedger(directory,fs18.readFileSync(ledgerPath));let planHash=computePlanLedgerHash(validated),root={seq:1,timestamp:new Date().toISOString(),plan_id:derivePlanId(validated),event_type:"plan_created",source,plan_hash_before:"",plan_hash_after:planHash,schema_version:LEDGER_SCHEMA_VERSION,payload:{plan:validated,payload_hash:planHash,plan_epoch:crypto3.randomUUID()}},line=new TextEncoder().encode(serializeLedgerEvent(root)),priorMode=getPlanLedgerState(directory)?.authorityMode??"file_shadow";if(priorMode==="file_shadow"){writePortableLedger(directory,[line]);try{replaceSqliteLedger(directory,{canonicalEvents:[line],state:stateForEvents(directory,[root],priorMode),source:source==="savePlan_identity_migration"?"plan_identity_reinitialized":"checkpoint_rollback",mode:priorMode,version:package_default.version})}catch(error49){log(`[ledger] SQLite shadow re-root deferred after authoritative file commit: ${error49 instanceof Error?error49.message:String(error49)}`)}return}replaceSqliteLedger(directory,{canonicalEvents:[line],state:stateForEvents(directory,[root],priorMode),source:"checkpoint_rollback",mode:priorMode,version:package_default.version});try{writePortableLedger(directory,[line])}catch(error49){criticalWarn(`[ledger] SQLite committed rollback root, but refreshing the portable plan-ledger.jsonl export failed: ${error49 instanceof Error?error49.message:String(error49)}. SQLite remains authoritative; a later read will retry the export.`)}})}async function replayFromLedger(directory,options){let{plan}=await replayFromLedgerWithStatus(directory,options);return plan}async function peekPlanFromLedger(directory,_options){if(fs18.existsSync(path33.join(directory,".swarm","plan-ledger.resetting")))return{plan:null,truncated:!1,badSuffix:null};let file2=readFileLedgerExact(directory),events=file2.events,truncated=file2.truncated,badSuffix=file2.badSuffix,sqliteReadOnly=readSqliteLedgerEventsReadOnly(directory);if(fs18.existsSync(path33.join(directory,".swarm","plan-ledger.resetting")))return{plan:null,truncated:!1,badSuffix:null};if(sqliteReadOnly.events.length>0){let sqlite={events:sqliteReadOnly.events.map((row)=>row.event)};if(sqliteReadOnly.state?.authorityMode==="sqlite"||events.length===0)events=sqlite.events,truncated=!1,badSuffix=null}if(events.length===0)return{plan:null,truncated,badSuffix};return{plan:reconstructPlanFromEvents(directory,events),truncated,badSuffix}}async function replayFromLedgerWithStatus(directory,_options){let{events,truncated,badSuffix}=await readLedgerEventsWithIntegrity(directory);if(events.length===0)return{plan:null,truncated,badSuffix};if(truncated&&badSuffix!==null)await quarantineLedgerSuffix(directory,badSuffix);return{plan:reconstructPlanFromEvents(directory,events),truncated,badSuffix}}function reconstructPlanFromEvents(directory,events){let targetPlanId=events[0].plan_id,relevantEvents=events.filter((e)=>e.plan_id===targetPlanId);{let snapshotEvents=relevantEvents.filter((e)=>e.event_type==="snapshot");for(let i=snapshotEvents.length-1;i>=0;i--){let candidate=snapshotEvents[i],candidatePayload=candidate.payload,parseResult=candidatePayload&&candidatePayload.plan?PlanSchema.safeParse(candidatePayload.plan):null;if(!parseResult||!parseResult.success){log(`[ledger] Skipping degraded snapshot event seq=${candidate.seq} (payload failed PlanSchema validation); falling back to older snapshot history.`);continue}let plan2=parseResult.data,eventsAfterSnapshot=relevantEvents.filter((e)=>e.seq>candidate.seq);for(let event of eventsAfterSnapshot)if(plan2=applyEventToPlan(plan2,event),plan2===null)return null;return plan2}}let createdEvent=relevantEvents.find((e)=>e.event_type==="plan_created");if(createdEvent?.payload&&typeof createdEvent.payload==="object"&&"plan"in createdEvent.payload){let parseResult=PlanSchema.safeParse(createdEvent.payload.plan);if(parseResult.success){let plan2=parseResult.data,eventsAfterCreated=relevantEvents.filter((e)=>e.seq>createdEvent.seq);for(let event of eventsAfterCreated){if(plan2===null)return null;plan2=applyEventToPlan(plan2,event)}return plan2}}let planJsonPath=getPlanJsonPath(directory);if(!fs18.existsSync(planJsonPath))return null;let plan;try{let bootstrapBytes=fs18.readFileSync(planJsonPath),content=new TextDecoder("utf-8",{fatal:!0}).decode(bootstrapBytes);plan=JSON.parse(content)}catch{return null}for(let event of relevantEvents){if(plan===null)return null;plan=applyEventToPlan(plan,event)}return plan}function applyEventToPlan(plan,event){switch(event.event_type){case"plan_created":if(event.payload&&typeof event.payload==="object"&&"plan"in event.payload){let parsed=PlanSchema.safeParse(event.payload.plan);if(parsed.success)return parsed.data}return plan;case"task_status_changed":if(event.task_id&&event.to_status){let parseResult=TaskStatusSchema.safeParse(event.to_status);if(!parseResult.success)return plan;for(let phase of plan.phases){let task=phase.tasks.find((t)=>t.id===event.task_id);if(task){task.status=parseResult.data;break}}}return plan;case"phase_completed":if(event.phase_id){let phase=plan.phases.find((p)=>p.id===event.phase_id);if(phase)phase.status="complete"}return plan;case"plan_exported":return plan;case"task_added":return plan;case"task_removed":if(event.task_id)for(let phase of plan.phases){let idx=phase.tasks.findIndex((t)=>t.id===event.task_id);if(idx!==-1){phase.tasks.splice(idx,1);break}}return plan;case"task_updated":return plan;case"plan_rebuilt":return plan;case"task_reordered":return plan;case"snapshot":return plan;case"plan_reset":return null;case"execution_profile_set":{let rawProfile=event.payload?.execution_profile;if(rawProfile!==void 0){let parsed=ExecutionProfileSchema.safeParse(rawProfile);if(parsed.success)return{...plan,execution_profile:parsed.data}}return plan}case"execution_profile_locked":{if(plan.execution_profile)return{...plan,execution_profile:{...plan.execution_profile,locked:!0}};return plan}default:throw Error(`applyEventToPlan: unhandled event type "${event.event_type}" at seq ${event.seq}`)}}async function readLedgerEventsWithIntegrity(directory,options){let ledgerPath=getLedgerPath(directory);if(!fs18.existsSync(ledgerPath)&&!hasSqliteLedger(directory))return{events:[],truncated:!1,badSuffix:null};try{let result=coordinateLedger(directory);return{events:[...result.events].sort((a,b)=>a.seq-b.seq),truncated:result.truncated,badSuffix:result.badSuffix}}catch(error49){if(options?.failClosedOnReadError)throw Error(`PLAN_LEDGER_UNREADABLE: ${ledgerPath} exists but could not be read (${error49 instanceof Error?error49.message:String(error49)}); plan state cannot be resolved. This is NOT an absent ledger — preserve the file and check permissions/filesystem health before retrying.`);let code=error49?.code;if(code&&["EACCES","EIO","EISDIR","EPERM"].includes(code))return{events:[],truncated:!1,badSuffix:null};throw error49}}async function quarantineLedgerSuffix(directory,badSuffix){let salvagedCount=0;for(let line of badSuffix.split(`
612
+ `)){if(line.trim()==="")continue;try{JSON.parse(line),salvagedCount++}catch{}}try{assertProjectRoot(directory);let hash2=crypto3.createHash("sha256").update(badSuffix,"utf8").digest("hex").slice(0,12),swarmDir=path33.join(directory,".swarm");try{let existing=_internals32.readLedgerDirectory(swarmDir).sort(compareCodeUnits).filter((name)=>name.startsWith("plan-ledger.quarantine.")&&name.endsWith(`.${hash2}`));for(let name of existing){let existingPath=path33.join(swarmDir,name);if(fs18.readFileSync(existingPath,"utf8")===badSuffix)return{path:existingPath,salvagedCount}}}catch{}let quarantinePath=path33.join(swarmDir,`plan-ledger.quarantine.${Date.now()}.${hash2}`);return fs18.writeFileSync(quarantinePath,badSuffix,"utf8"),log(`[ledger] Corrupted suffix quarantined to ${path33.relative(directory,quarantinePath)} (salvageable events: ${salvagedCount})`),{path:quarantinePath,salvagedCount}}catch{return{path:null,salvagedCount}}}async function loadLastApprovedPlan(directory,expectedPlanId){let integrity=await readLedgerEventsWithIntegrity(directory);return findLastApprovedSnapshot(integrity.events,expectedPlanId)}async function loadLastPlanCriticApprovedSnapshot(directory,expectedPlanId){let integrity=await readLedgerEventsWithIntegrity(directory);return findLastApprovedSnapshot(integrity.events,expectedPlanId,(payload)=>payload.approval?.source==="plan_critic_gate")}function findLastApprovedSnapshot(events,expectedPlanId,extraFilter){if(events.length===0)return null;for(let i=events.length-1;i>=0;i--){let event=events[i];if(event.event_type!=="snapshot")continue;if(event.source!=="critic_approved")continue;if(expectedPlanId!==void 0&&event.plan_id!==expectedPlanId)continue;let payload=event.payload;if(!payload||typeof payload!=="object"||!payload.plan)continue;let parsedPlan=PlanSchema.safeParse(payload.plan);if(!parsedPlan.success){criticalWarn(`[ledger] Skipping schema-invalid critic_approved snapshot at seq ${event.seq}: ${parsedPlan.error.issues[0]?.message??"unknown schema error"}`);continue}if(expectedPlanId!==void 0){if(derivePlanId(payload.plan)!==expectedPlanId)continue}if(extraFilter&&!extraFilter(payload))continue;return{plan:parsedPlan.data,seq:event.seq,timestamp:event.timestamp,approval:payload.approval,payloadHash:payload.payload_hash}}return null}var LEDGER_SCHEMA_VERSION="1.1.0",LEDGER_FILENAME="plan-ledger.jsonl",LEDGER_LOCK_PATH,PLAN_JSON_FILENAME="plan.json",LedgerStaleWriterError,_internals32;var init_ledger=__esm(()=>{init_package();init_plan_schema();init_lock();init_telemetry();init_logger();init_project_boundary();init_ledger_sqlite();init_planning_profile();init_utils3();LEDGER_LOCK_PATH=path33.join(".swarm",LEDGER_FILENAME);LedgerStaleWriterError=class LedgerStaleWriterError extends Error{constructor(message){super(message);this.name="LedgerStaleWriterError"}};_internals32={computePlanLedgerHash,computePlanStructureHash,computeCurrentPlanHash,ledgerExists,getLatestLedgerSeq,readLedgerEvents,initLedger,appendLedgerEvent,appendLedgerEventWithRetry,takeSnapshotEvent,replayFromLedger,replayFromLedgerWithStatus,peekPlanFromLedger,applyEventToPlan,readLedgerEventsWithIntegrity,quarantineLedgerSuffix,loadLastApprovedPlan,loadLastPlanCriticApprovedSnapshot,getLedgerPath,getPlanJsonPath,archiveLegacyLedger,writePortableLedger,writeFileFsyncedThenRename,fsyncRecoveryDirectory,readLedgerDirectory,randomUUID:()=>crypto3.randomUUID()}});import{randomUUID as randomUUID8}from"node:crypto";import*as path34 from"node:path";function newIdentity(){return randomUUID8()}function isScopeBindingIdentity(value){return typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(value)}function canonicalWorkspaceIdentity(directory){return canonicalExistingFilesystemPath(directory)}function isStrictTaskId2(value){return/^\d+\.\d+(?:\.\d+)*$/.test(value)}function normalizeScopePath(value){if(typeof value!=="string")return null;if(unsafePathTextReason(value))return null;let trimmed=value.trim().replace(/\\/g,"/");if(trimmed.length===0||trimmed.includes("\x00")||trimmed.split("/").includes("..")||path34.posix.isAbsolute(trimmed)||/^[A-Za-z]:\//.test(trimmed))return null;let normalized=path34.posix.normalize(trimmed).replace(/^\.\//,"");if(normalized==="."||normalized===".."||normalized.startsWith("../"))return null;return normalized.endsWith("/")?normalized.slice(0,-1):normalized}function normalizeScopeFiles(files){if(!Array.isArray(files)||files.length===0||files.length>1e4)return null;let normalized=new Set,totalBytes=0;for(let file2 of files){let candidate=normalizeScopePath(file2);if(!candidate)return null;let bytes=Buffer.byteLength(candidate,"utf8");if(totalBytes+=bytes,bytes>MAX_SCOPE_PATH_BYTES||totalBytes>MAX_SCOPE_FILES_BYTES)return null;normalized.add(candidate)}return normalized.size>0?[...normalized].sort():null}function bindingKey(binding){return binding.generationId}function createScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),ttlMs=Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS);return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:derivePlanId(input.plan),planStructureHash:computePlanStructureHash(input.plan),taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:input.source,files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+ttlMs}}function sweepExpired(now=Date.now()){for(let[key,binding]of pendingScopeBindings)if(binding.expiresAt<=now){pendingScopeBindings.delete(key);let expired={...binding,revision:binding.revision+1,lifecycleState:"expired",updatedAt:now};scopeBindingTombstones.set(bindingKey(expired),expired)}while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function registerScopeBinding(binding){if(sweepExpired(),binding.lifecycleState!=="live"||binding.expiresAt<=Date.now())return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"Only an unexpired live binding can be admitted."};let exact=pendingScopeBindings.get(bindingKey(binding));if(exact&&exact.bindingId!==binding.bindingId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"The generation identity collides with a different binding."};if(exact&&exact.revision>binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"A newer revision of this generation is already admitted."};if(binding.activation==="declaration"&&binding.dispatchCallId===void 0){for(let[existingKey,existing]of pendingScopeBindings)if(existing.generationId!==binding.generationId&&existing.activation==="declaration"&&existing.dispatchCallId===void 0&&existing.workspaceIdentity===binding.workspaceIdentity&&existing.taskId===binding.taskId&&existing.ownerSessionId===binding.ownerSessionId)pendingScopeBindings.delete(existingKey),scopeBindingTombstones.set(existingKey,{...existing,revision:existing.revision+1,lifecycleState:"superseded",updatedAt:Date.now()})}if(!exact&&pendingScopeBindings.size>=MAX_PENDING_SCOPE_BINDINGS)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:`Scope binding capacity ${MAX_PENDING_SCOPE_BINDINGS} is exhausted; complete or expire a live task before retrying.`};let key=bindingKey(binding);return pendingScopeBindings.delete(key),pendingScopeBindings.set(key,binding),{ok:!0,binding}}function getScopeBindingForParentDispatch(input){if(sweepExpired(),!input.parentSessionId.trim()||!input.dispatchCallId.trim())return null;let active=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.parentCallId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);if(active.length>1)return null;if(active.length===1)return active[0];let pending=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.ownerMessageId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);return pending.length===1?pending[0]:null}function getActiveScopeBindingsForSession(input){sweepExpired();let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity||!input.activeSessionId.trim())return[];let now=Date.now();return[...pendingScopeBindings.values()].filter((binding)=>binding.workspaceIdentity===workspaceIdentity&&binding.ownerSessionId===input.activeSessionId&&binding.activation==="active"&&binding.lifecycleState==="live"&&binding.expiresAt>now&&isDispatchCorrelated(binding))}function isDispatchCorrelated(binding){return typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId}function createPrFeedbackScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!input.workflowSessionId.trim()||!input.workflowRevisionDigest.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),workflowIdentity=`pr-feedback:${input.workflowSessionId}`;return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:workflowIdentity,planStructureHash:input.workflowRevisionDigest,taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:"pr_feedback",files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS,workflowSessionId:input.workflowSessionId,workflowRevisionDigest:input.workflowRevisionDigest}}function getAuthorizedPrFeedbackScopeBinding(input){sweepExpired();let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity||!input.activeSessionId.trim())return null;let matches=[...pendingScopeBindings.values()].filter((binding)=>binding.workspaceIdentity===workspaceIdentity&&binding.source==="pr_feedback"&&binding.activation==="active"&&binding.ownerSessionId===input.activeSessionId&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&typeof binding.workflowSessionId==="string"&&binding.workflowSessionId===binding.parentOwnerSessionId&&typeof binding.workflowRevisionDigest==="string"&&binding.workflowRevisionDigest.length>0&&binding.planId===`pr-feedback:${binding.workflowSessionId}`&&binding.planStructureHash===binding.workflowRevisionDigest);return matches.length===1?matches[0]:null}function describeScopeWorkspaceMismatch(input){if(sweepExpired(),!input.activeSessionId.trim())return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity)return null;let first=[...pendingScopeBindings.values()].filter((binding)=>binding.ownerSessionId===input.activeSessionId&&binding.activation==="active"&&binding.source!=="pr_feedback"&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&binding.workspaceIdentity!==workspaceIdentity)[0];if(!first)return null;return`SCOPE_WORKSPACE_MISMATCH: an active scope binding for session "${sanitizeDiagnosticText(input.activeSessionId)}" (task ${first.taskId}, source ${first.source}) is rooted at "${sanitizeDiagnosticText(first.workspaceIdentity)}", but this gate resolved "${sanitizeDiagnosticText(workspaceIdentity)}". The gate is using the wrong workspace root for this session.`}function clearScopeBindings(predicate){let removed=[];if(!predicate)return removed.push(...pendingScopeBindings.values()),pendingScopeBindings.clear(),scopeBindingTombstones.clear(),removed;for(let[key,binding]of pendingScopeBindings)if(predicate(binding))removed.push(binding),pendingScopeBindings.delete(key);return removed}function clearExactScopeBinding(input){let candidate=pendingScopeBindings.get(input.generationId);if(!candidate||candidate.bindingId!==input.bindingId)return null;return pendingScopeBindings.delete(input.generationId),candidate}function installScopeBindingTombstone(binding){pendingScopeBindings.delete(binding.generationId),scopeBindingTombstones.delete(binding.generationId),scopeBindingTombstones.set(binding.generationId,binding);while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function hasScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live")}function hasDeliberateScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live"&&tombstone.lifecycleState!=="expired")}function clearSweepTombstoneForRevival(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);if(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.lifecycleState==="expired"&&tombstone.revision<=binding.revision)scopeBindingTombstones.delete(binding.generationId)}function installFailedRevocationOverlay(binding,reason){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||current.revision!==binding.revision)return!1;let now=Date.now();return installScopeBindingTombstone({...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)}),!0}function installScopeBindingRetirementIntent(binding){let source=pendingScopeBindings.get(binding.generationId)??(binding.version===2?binding:null);if(!source||source.bindingId!==binding.bindingId)return null;let now=Date.now(),tombstone={...source,revision:source.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(source.expiresAt,now)};return installScopeBindingTombstone(tombstone),tombstone}function updateExactScopeBinding(binding){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||binding.revision<=current.revision)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"The exact binding generation is stale or no longer active."};return pendingScopeBindings.set(binding.generationId,binding),{ok:!0,binding}}function createClaimedScopeBinding(previous,input){let now=Date.now();return{...previous,generationId:newIdentity(),revision:1,ownerSessionId:input.childSessionId,childSessionId:input.childSessionId,ownerMessageId:input.dispatchCallId,dispatchCallId:input.dispatchCallId,parentOwnerSessionId:input.parentSessionId,parentCallId:input.dispatchCallId,activation:"active",predecessorGenerationId:previous.generationId,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function deriveChildScopeBinding(parent,input){let workspaceIdentity=canonicalWorkspaceIdentity(input.childDirectory);if(!workspaceIdentity||!input.childSessionId.trim()||!input.parentCallId.trim())throw Error("Cannot derive child scope binding without verified identity");let now=Date.now();return{...parent,generationId:newIdentity(),revision:1,workspaceIdentity,ownerSessionId:input.childSessionId,ownerMessageId:input.parentCallId,dispatchCallId:input.parentCallId,activation:"active",parentOwnerSessionId:parent.ownerSessionId,parentCallId:input.parentCallId,predecessorGenerationId:parent.generationId,childSessionId:input.childSessionId,source:"worktree_derived",declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function scopeContains(scope,candidate){let flavor=getPathFlavor(),candidateIdentity=normalizePathIdentity(candidate,flavor).replace(/\\/g,"/");return scope.some((entry)=>{let entryIdentity=normalizePathIdentity(entry,flavor).replace(/\\/g,"/");return candidateIdentity===entryIdentity||candidateIdentity.startsWith(`${entryIdentity}/`)})}function isSubset(candidate,authority){return candidate.every((file2)=>scopeContains(authority,file2))}function resolveCoderScopeSources(input){let explicit=input.explicitFiles&&input.explicitFiles.length>0?normalizeScopeFiles(input.explicitFiles):null,plan=input.planFiles&&input.planFiles.length>0?normalizeScopeFiles(input.planFiles):null,directives=input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0?normalizeScopeFiles(input.fileDirectiveFiles):null;if(input.explicitFiles&&input.explicitFiles.length>0&&!explicit)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.planFiles&&input.planFiles.length>0&&!plan)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0&&!directives)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(explicit){let conflict=plan&&!isSubset(plan,explicit)?{source:"plan",files:plan}:directives&&!isSubset(directives,explicit)?{source:"file_directive",files:directives}:null;if(conflict)return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"declare_scope",authoritativeFiles:explicit,conflictingSource:conflict.source,conflictingFiles:conflict.files,disagreement:conflict.files.filter((file2)=>!scopeContains(explicit,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:explicit,source:"declare_scope"}}if(plan){if(directives&&!isSubset(directives,plan))return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"plan",authoritativeFiles:plan,conflictingSource:"file_directive",conflictingFiles:directives,disagreement:directives.filter((file2)=>!scopeContains(plan,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:plan,source:"plan"}}if(directives)return{ok:!0,files:directives,source:"file_directive"};return{ok:!1,code:"SCOPE_NOT_DECLARED"}}function renderSet(values,max=8){if(!values)return"(none)";return`${values.slice(0,max).map((value)=>JSON.stringify(value)).join(", ")}${values.length>max?`, … +${values.length-max}`:""}`}function formatCoderScopeConflict(decision){if(decision.code!=="SCOPE_CONFLICT")return"SCOPE_NOT_DECLARED: coder delegation has no complete, valid, non-empty scope.";return`SCOPE_CONFLICT: ${decision.authoritativeSource} authority [${renderSet(decision.authoritativeFiles)}] does not cover ${decision.conflictingSource} [${renderSet(decision.conflictingFiles)}]; outside authority: [${renderSet(decision.disagreement)}]. Architect: reconcile save_plan(files_touched), FILE directives, or declare_scope, then dispatch a new Task call.`}var MAX_PENDING_SCOPE_BINDINGS=256,DEFAULT_SCOPE_BINDING_TTL_MS=3600000,MAX_SCOPE_BINDING_TOMBSTONES=256,pendingScopeBindings,scopeBindingTombstones,MAX_SCOPE_PATH_BYTES=4096,MAX_SCOPE_FILES_BYTES=1048576;var init_scope_binding=__esm(()=>{init_ledger();init_utils3();init_filesystem_identity();init_path_identity();pendingScopeBindings=new Map,scopeBindingTombstones=new Map});var exports_scope_persistence={};__export(exports_scope_persistence,{writeScopeToDisk:()=>writeScopeToDisk,writeScopeBindingToDisk:()=>writeScopeBindingToDisk,tombstoneScopeBinding:()=>tombstoneScopeBinding,resolveScopeWithFallbacks:()=>resolveScopeWithFallbacks,resolveScopeBindingFromDisk:()=>resolveScopeBindingFromDisk,resolveAuthorizedScopeBindingForSessionDetailed:()=>resolveAuthorizedScopeBindingForSessionDetailed,resolveAuthorizedScopeBindingForSession:()=>resolveAuthorizedScopeBindingForSession,resolveAuthorizedScopeBindingDetailed:()=>resolveAuthorizedScopeBindingDetailed,resolveAuthorizedScopeBinding:()=>resolveAuthorizedScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk:()=>resolveAuthorizedPrFeedbackScopeBindingFromDisk,replaceExistingScopeDeclaration:()=>replaceExistingScopeDeclaration,refreshScopeBindingLease:()=>refreshScopeBindingLease,readScopeFromDisk:()=>readScopeFromDisk,readScopeBindingFromDisk:()=>readScopeBindingFromDisk,readPlanScope:()=>readPlanScope,pruneScopeBindingTombstones:()=>pruneScopeBindingTombstones,persistAndRegisterScopeBinding:()=>persistAndRegisterScopeBinding,flushScopeBindingMaintenance:()=>flushScopeBindingMaintenance,clearScopeForTask:()=>clearScopeForTask,clearScopeBindingFromDisk:()=>clearScopeBindingFromDisk,clearAllScopes:()=>clearAllScopes,claimScopeBindingForChildDurably:()=>claimScopeBindingForChildDurably,_scopePersistenceInternals:()=>_scopePersistenceInternals});import{createHash as createHash19}from"node:crypto";import*as fs19 from"node:fs";import*as path35 from"node:path";function getScopesDir(directory){return path35.join(directory,SCOPES_DIR)}function normalizePathForComparison(value){let normalized=path35.resolve(value);return process.platform==="win32"?normalized.toLowerCase():normalized}function isSafeTaskId(taskId){if(typeof taskId!=="string")return!1;if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(taskId))return!1;let head=taskId.replace(/\.+$/,"").split(".")[0].toUpperCase();if(WINDOWS_RESERVED.has(head))return!1;return!0}function isScopesDirSafe(directory,scopesDir){try{let resolvedWorkspace=fs19.realpathSync(directory),expectedSwarmDir=path35.join(resolvedWorkspace,".swarm"),expectedScopesDir=path35.join(expectedSwarmDir,"scopes"),swarmStat=fs19.lstatSync(expectedSwarmDir),scopesStat=fs19.lstatSync(expectedScopesDir);if(!swarmStat.isDirectory()||swarmStat.isSymbolicLink()||!scopesStat.isDirectory()||scopesStat.isSymbolicLink())return!1;let resolvedScopes=fs19.realpathSync(scopesDir);if(normalizePathForComparison(resolvedScopes)!==normalizePathForComparison(expectedScopesDir))return!1;let rel=path35.relative(resolvedWorkspace,resolvedScopes);return rel.length>0&&!rel.startsWith("..")&&!path35.isAbsolute(rel)}catch{return!1}}function resolveSafeScopeFileForUnlink(directory,targetPath){try{let resolvedWorkspace=fs19.realpathSync(directory),scopesDir=path35.join(resolvedWorkspace,SCOPES_DIR);if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let candidate=path35.resolve(targetPath),resolvedCandidate=fs19.realpathSync(candidate);if(normalizePathForComparison(path35.dirname(candidate))!==normalizePathForComparison(scopesDir)||normalizePathForComparison(resolvedCandidate)!==normalizePathForComparison(candidate))return null;let relative7=path35.relative(resolvedWorkspace,resolvedCandidate);if(relative7.length===0||relative7===".."||relative7.startsWith(`..${path35.sep}`)||path35.isAbsolute(relative7))return null;let leafStat=fs19.lstatSync(candidate);if(!leafStat.isFile()||leafStat.isSymbolicLink())return null;if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let finalResolvedCandidate=fs19.realpathSync(candidate),finalLeafStat=fs19.lstatSync(candidate);if(normalizePathForComparison(finalResolvedCandidate)!==normalizePathForComparison(candidate)||!finalLeafStat.isFile()||finalLeafStat.isSymbolicLink()||finalLeafStat.dev!==leafStat.dev||finalLeafStat.ino!==leafStat.ino)return null;return candidate}catch{return null}}function getScopeFilePath(directory,taskId){if(!isSafeTaskId(taskId))throw Error(`Invalid taskId for scope persistence: ${taskId}`);return path35.join(getScopesDir(directory),`scope-${taskId}.json`)}function getLegacyBindingFilePath(directory,taskId,ownerSessionId){if(!isSafeTaskId(taskId)||!ownerSessionId.trim())throw Error("Invalid identity for scope binding persistence");let ownerHash=createHash19("sha256").update(ownerSessionId).digest("hex").slice(0,24);return path35.join(getScopesDir(directory),`binding-${taskId}-${ownerHash}.json`)}function getBindingFilePath(directory,binding){if(!isSafeTaskId(binding.taskId)||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId))throw Error("Invalid exact identity for scope binding persistence");return path35.join(getScopesDir(directory),`binding-${binding.taskId}-${binding.bindingId}-${binding.generationId}.json`)}function getGenerationLockPath(bindingPath){return`${bindingPath}.generation-lock`}function getRetirementIntentPath(bindingPath){return`${bindingPath}.retirement-intent`}function hasDurableRetirementIntent(bindingPath,binding){let raw=readBoundedFile(getRetirementIntentPath(bindingPath));if(!raw)return!1;try{let intent=JSON.parse(raw);return intent.bindingId===binding.bindingId&&intent.generationId===binding.generationId}catch{return!1}}function ensureLockTargetSync(targetPath){try{let scopesDir=path35.dirname(targetPath),swarmDir=path35.dirname(scopesDir);if(path35.basename(scopesDir)!=="scopes"||path35.basename(swarmDir)!==".swarm")return!1;assertProjectRoot(path35.dirname(swarmDir)),fs19.mkdirSync(path35.dirname(targetPath),{recursive:!0});let nofollow=fs19.constants.O_NOFOLLOW??0,fd=fs19.openSync(targetPath,fs19.constants.O_WRONLY|fs19.constants.O_CREAT|nofollow);return fs19.closeSync(fd),!0}catch{return!1}}function readBoundedFile(filePath){let nofollow=fs19.constants.O_NOFOLLOW??0,fd;try{fd=fs19.openSync(filePath,fs19.constants.O_RDONLY|nofollow)}catch{return null}try{let stat7=fs19.fstatSync(fd);if(!stat7.isFile()||stat7.size<=0||stat7.size>MAX_SCOPE_BYTES)return null;let buffer=Buffer.alloc(stat7.size);return fs19.readSync(fd,buffer,0,stat7.size,0),buffer.toString("utf8")}catch{return null}finally{try{fs19.closeSync(fd)}catch{}}}function scopeBindingArchivePath(filePath){return`${filePath}.imported`}function collisionSafeScopeBindingArchivePath(filePath){let canonical=scopeBindingArchivePath(filePath);if(!fs19.existsSync(canonical))return canonical;for(let suffix=1;suffix<=1e4;suffix+=1){let candidate=`${canonical}.${suffix}`;if(!fs19.existsSync(candidate))return candidate}throw Error(`No collision-safe archive path available for ${path35.basename(filePath)}.`)}function scopeBindingShadowPayload(binding){return JSON.stringify(binding,null,2)}function coordinationScopeEntityKey(binding){return binding.generationId}function parseCoordinationScopeBinding(directory,row){try{let binding=validateScopeBindingPayload(directory,JSON.parse(row.payload));if(!binding||binding.generationId!==row.entityKey||binding.revision!==row.revision||binding.lifecycleState!==row.status)return null;return binding}catch{return null}}function transitionScopeBindingState(directory,binding,expectedRevision){let payload=scopeBindingShadowPayload(binding),idempotencyKey=createHash19("sha256").update(`${binding.bindingId}\x00${binding.generationId}\x00${binding.revision}\x00${binding.lifecycleState}\x00${payload}`).digest("hex");try{let result=transitionCoordinationState(directory,{namespace:SCOPE_BINDING_COORDINATION_NAMESPACE,entityKey:coordinationScopeEntityKey(binding),expectedRevision,generation:1,status:binding.lifecycleState,payload,event:{streamId:`scope-binding:${binding.bindingId}`,idempotencyKey,eventType:binding.lifecycleState,payload}});if(result.outcome!=="applied"&&result.outcome!=="duplicate")return{ok:!1,code:result.outcome==="revision_conflict"||result.outcome==="stale_generation"?"SCOPE_BINDING_STALE":"SCOPE_BINDING_PERSISTENCE_FAILED",message:`Scope binding transition failed: ${result.outcome}.`};let persisted=result.state&&parseCoordinationScopeBinding(directory,result.state);return persisted?{ok:!0,value:persisted}:persistenceFailure("Scope binding transition could not be re-read from coordination state.")}catch(error49){return persistenceFailure(`Scope binding transition failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}function transitionScopeBindingStateWithinTransaction(directory,binding,expectedRevision){let payload=scopeBindingShadowPayload(binding),idempotencyKey=createHash19("sha256").update(`${binding.bindingId}\x00${binding.generationId}\x00${binding.revision}\x00${binding.lifecycleState}\x00${payload}`).digest("hex");try{let result=transitionCoordinationStateWithinTransaction(directory,{namespace:SCOPE_BINDING_COORDINATION_NAMESPACE,entityKey:coordinationScopeEntityKey(binding),expectedRevision,generation:1,status:binding.lifecycleState,payload,event:{streamId:`scope-binding:${binding.bindingId}`,idempotencyKey,eventType:binding.lifecycleState,payload}});if(result.outcome!=="applied"&&result.outcome!=="duplicate")return{ok:!1,code:result.outcome==="revision_conflict"||result.outcome==="stale_generation"?"SCOPE_BINDING_STALE":"SCOPE_BINDING_PERSISTENCE_FAILED",message:`Scope binding transition failed: ${result.outcome}.`};let persisted=result.state&&parseCoordinationScopeBinding(directory,result.state);return persisted?{ok:!0,value:persisted}:persistenceFailure("Scope binding transition could not be re-read from coordination state.")}catch(error49){return persistenceFailure(`Scope binding transition failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}function coordinationTimestampFromMs(value,label){if(!Number.isFinite(value))throw Error(`${label} must be a finite epoch-millisecond timestamp.`);let iso=new Date(value).toISOString();if(Number.isNaN(Date.parse(iso)))throw Error(`${label} must be a valid epoch-millisecond timestamp.`);return iso}function importScopeBindingStateRows(directory,bindings){let db=getProjectDb(directory);for(let binding of bindings){if(!Number.isSafeInteger(binding.revision)||binding.revision<1)throw Error(`Legacy binding ${binding.generationId} has invalid revision ${binding.revision}.`);db.run(`INSERT INTO coordination_state
613
613
  (namespace, entity_key, revision, generation, status, payload, updated_at)
614
614
  VALUES (?, ?, ?, ?, ?, ?, ?)`,[SCOPE_BINDING_COORDINATION_NAMESPACE,coordinationScopeEntityKey(binding),binding.revision,1,binding.lifecycleState,scopeBindingShadowPayload(binding),coordinationTimestampFromMs(binding.updatedAt,"binding.updatedAt")])}}function writeScopeBindingShadow(directory,binding){try{let scopesDir=getScopesDir(directory);if(fs19.mkdirSync(scopesDir,{recursive:!0}),!isScopesDirSafe(directory,scopesDir))return;atomicWriteSync(getBindingFilePath(directory,binding),scopeBindingShadowPayload(binding))}catch{}}function archiveImportedScopeAuthorityFiles(paths){for(let filePath of paths)try{if(!fs19.existsSync(filePath))continue;let archivedPath=collisionSafeScopeBindingArchivePath(filePath);fs19.renameSync(filePath,archivedPath)}catch{}}function fingerprintCommittedScopeImportSource(directory){let scopesDir=getScopesDir(directory);try{fs19.lstatSync(scopesDir)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(!isScopesDirSafe(directory,scopesDir))return null;let names=fs19.readdirSync(scopesDir).sort();if(names.length>bindingFileScanCapacity)return null;let authorityFiles=[];for(let name of names){if(!name.startsWith("binding-")||!name.endsWith(".json"))continue;let filePath=path35.join(scopesDir,name);authorityFiles.push(filePath);let intentPath=getRetirementIntentPath(filePath);if(fs19.existsSync(intentPath))authorityFiles.push(intentPath)}for(let name of names)if(/^claim-[a-f0-9]{40}\.json$/i.test(name))authorityFiles.push(path35.join(scopesDir,name));if(authorityFiles.length===0)return null;let digest2=createHash19("sha256");for(let filePath of authorityFiles){let raw=readBoundedFile(filePath);if(raw===null)return null;digest2.update(path35.basename(filePath)),digest2.update(raw)}return{authorityFiles,sourceDigest:digest2.digest("hex")}}function collectLegacyScopeBindingsForImport(directory){let scopesDir=getScopesDir(directory);try{fs19.lstatSync(scopesDir)}catch(error49){if(error49.code==="ENOENT")return{bindings:[],authorityFiles:[],sourceDigest:"empty",rowCount:0};throw error49}if(!isScopesDirSafe(directory,scopesDir))throw Error("The durable scope store failed containment checks.");if(!migrateLegacyBindingsSync(directory))throw Error("The durable binding set could not be completely evaluated.");let names=fs19.readdirSync(scopesDir).sort();if(names.length>bindingFileScanCapacity)throw Error("The durable binding set exceeds the scan capacity.");let authorityFiles=[],bindings=[];for(let name of names){if(!name.startsWith("binding-")||!name.endsWith(".json"))continue;let filePath=path35.join(scopesDir,name);authorityFiles.push(filePath);let raw=readBoundedFile(filePath);if(!raw)throw Error(`Legacy scope binding ${name} is unreadable.`);let binding=validateScopeBindingPayload(directory,JSON.parse(raw));if(!binding||!exactFilenameMatches(directory,filePath,binding))throw Error(`Legacy scope binding ${name} is malformed.`);let intentPath=getRetirementIntentPath(filePath);if(hasDurableRetirementIntent(filePath,binding)){authorityFiles.push(intentPath);let createdAt=Date.now(),rawIntent=readBoundedFile(intentPath);if(!rawIntent)throw Error(`Legacy retirement intent ${path35.basename(intentPath)} is unreadable.`);let parsedIntent=JSON.parse(rawIntent);if(parsedIntent.bindingId!==binding.bindingId||parsedIntent.generationId!==binding.generationId)throw Error(`Legacy retirement intent ${path35.basename(intentPath)} mismatches its generation.`);if(typeof parsedIntent.createdAt==="number")createdAt=parsedIntent.createdAt;bindings.push({...binding,lifecycleState:"revoked",updatedAt:createdAt,expiresAt:Math.min(binding.expiresAt,createdAt)});continue}bindings.push(binding)}for(let name of names){if(!/^claim-[a-f0-9]{40}\.json$/i.test(name))continue;let filePath=path35.join(scopesDir,name);authorityFiles.push(filePath);let raw=readBoundedFile(filePath);if(!raw)throw Error(`Legacy claim receipt ${name} is unreadable.`);let parsed=JSON.parse(raw);if(parsed.version!==1||!isScopeBindingIdentity(parsed.predecessorGenerationId)||!isScopeBindingIdentity(parsed.winnerGenerationId)||typeof parsed.childSessionId!=="string"||!parsed.childSessionId.trim()||typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId.trim())throw Error(`Legacy claim receipt ${name} is malformed.`);let winner=bindings.find((binding)=>binding.generationId===parsed.winnerGenerationId);if(!winner)throw Error(`Legacy claim receipt ${name} has no winner generation.`);if(winner.lifecycleState==="live"&&winner.ownerSessionId!==parsed.childSessionId)throw Error(`Legacy claim receipt ${name} disagrees with the winner generation.`)}let digest2=createHash19("sha256");for(let filePath of authorityFiles){if(!fs19.existsSync(filePath))continue;digest2.update(path35.basename(filePath)),digest2.update(fs19.readFileSync(filePath))}return{bindings,authorityFiles,sourceDigest:digest2.digest("hex"),rowCount:bindings.length}}function ensureScopeBindingAuthorityImported(directory){try{let authorityExists=listCoordinationStates(directory,SCOPE_BINDING_COORDINATION_NAMESPACE,1).length>0;if(authorityExists){let importStatement=getProjectDb(directory).prepare("SELECT source_digest FROM coordination_import WHERE source = ?"),importRow;try{importRow=importStatement.get(SCOPE_BINDING_COORDINATION_IMPORT_SOURCE)}finally{importStatement.finalize()}let committedSource=fingerprintCommittedScopeImportSource(directory);if(!importRow||!committedSource||importRow.source_digest!==committedSource.sourceDigest)return{ok:!0,value:void 0}}let legacy=collectLegacyScopeBindingsForImport(directory);if(legacy.rowCount===0&&legacy.authorityFiles.length===0)return{ok:!0,value:void 0};let importedBindings=legacy.bindings.map((binding)=>({...binding}));if(authorityExists){archiveImportedScopeAuthorityFiles(legacy.authorityFiles);for(let binding of importedBindings)writeScopeBindingShadow(directory,binding);return{ok:!0,value:void 0}}let outcome=importCoordinationOnce(directory,{source:SCOPE_BINDING_COORDINATION_IMPORT_SOURCE,sourceDigest:legacy.sourceDigest,rowCount:legacy.rowCount,emptyNamespace:SCOPE_BINDING_COORDINATION_NAMESPACE},()=>{importScopeBindingStateRows(directory,importedBindings)});if(outcome==="imported"||outcome==="already_imported"){archiveImportedScopeAuthorityFiles(legacy.authorityFiles);for(let binding of importedBindings)writeScopeBindingShadow(directory,binding)}return{ok:!0,value:void 0}}catch(error49){return persistenceFailure(`Scope binding import failed closed: ${error49 instanceof Error?error49.message:"unknown import error"}`)}}function readAllAuthoritativeScopeBindings(directory,options={}){let imported=ensureScopeBindingAuthorityImported(directory);if(!imported.ok)return imported;try{let scanCapacity=options.maintenanceScan?maintenanceFileScanCapacity:bindingFileScanCapacity,rows=listCoordinationStates(directory,SCOPE_BINDING_COORDINATION_NAMESPACE,scanCapacity+1);if(rows.length>scanCapacity)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set exceeds the scan capacity."};let bindings=rows.map((row)=>parseCoordinationScopeBinding(directory,row));if(bindings.some((binding)=>binding===null))return persistenceFailure("The authoritative scope binding set contains malformed coordination rows.");let complete=bindings,liveCount=complete.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()).length;if(options.enforceLiveCapacity!==!1&&liveCount>liveBindingCapacity)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set exceeds the live binding capacity."};return{ok:!0,value:complete}}catch(error49){return persistenceFailure(`Authoritative scope binding read failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}function deterministicIdentity(value){let hex3=createHash19("sha256").update(value).digest("hex").slice(0,32);return`${hex3.slice(0,8)}-${hex3.slice(8,12)}-4${hex3.slice(13,16)}-a${hex3.slice(17,20)}-${hex3.slice(20)}`}function validateScopeBindingPayload(directory,parsed,options={}){let workspaceIdentity=canonicalWorkspaceIdentity(directory),legacyWorkspaceIdentity=legacyCanonicalExistingFilesystemPath(directory),files=Array.isArray(parsed.files)?normalizeScopeFiles(parsed.files.filter((file2)=>typeof file2==="string")):null;if(parsed.version!==2||!workspaceIdentity||parsed.workspaceIdentity!==workspaceIdentity&&parsed.workspaceIdentity!==legacyWorkspaceIdentity||!isSafeTaskId(parsed.taskId??"")||!files||typeof parsed.planId!=="string"||!parsed.planId||typeof parsed.planStructureHash!=="string"||!parsed.planStructureHash||typeof parsed.ownerSessionId!=="string"||!parsed.ownerSessionId.trim()||typeof parsed.ownerMessageId!=="string"||!parsed.ownerMessageId.trim()||!["declaration","pending_child","active"].includes(parsed.activation??"")||!["declare_scope","plan","file_directive","pr_feedback","worktree_derived"].includes(parsed.source??"")||typeof parsed.declaredAt!=="number"||!Number.isFinite(parsed.declaredAt)||typeof parsed.expiresAt!=="number"||!Number.isFinite(parsed.expiresAt))return null;let legacySeed=JSON.stringify({workspaceIdentity,planId:parsed.planId,planStructureHash:parsed.planStructureHash,taskId:parsed.taskId,ownerSessionId:parsed.ownerSessionId,ownerMessageId:parsed.ownerMessageId,dispatchCallId:parsed.dispatchCallId,activation:parsed.activation,source:parsed.source,files,declaredAt:parsed.declaredAt}),bindingId=isScopeBindingIdentity(parsed.bindingId)?parsed.bindingId:options.allowLegacy?deterministicIdentity(`binding\x00${legacySeed}`):null,generationId=isScopeBindingIdentity(parsed.generationId)?parsed.generationId:options.allowLegacy?deterministicIdentity(`generation\x00${legacySeed}`):null;if(!bindingId||!generationId)return null;let lifecycleState=parsed.lifecycleState??(options.allowLegacy?"live":void 0);if(!lifecycleState||!["live","expired","revoked","superseded"].includes(lifecycleState))return null;let revision=parsed.revision??(options.allowLegacy?1:void 0);if(!Number.isSafeInteger(revision)||(revision??0)<1)return null;let updatedAt=parsed.updatedAt??parsed.declaredAt,leaseStartedAt=parsed.leaseStartedAt??parsed.declaredAt;if(typeof updatedAt!=="number"||typeof leaseStartedAt!=="number")return null;let now=Date.now();if(parsed.declaredAt>now||updatedAt<parsed.declaredAt||leaseStartedAt<parsed.declaredAt||parsed.activation==="declaration"&&parsed.dispatchCallId!==void 0||parsed.activation==="pending_child"&&(typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId)||parsed.activation==="active"&&(typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId||typeof parsed.parentOwnerSessionId!=="string"||!parsed.parentOwnerSessionId||parsed.ownerSessionId===parsed.parentOwnerSessionId||parsed.parentCallId!==parsed.dispatchCallId))return null;return{...parsed,bindingId,generationId,revision,lifecycleState,files,workspaceIdentity,updatedAt,leaseStartedAt}}function exactFilenameMatches(directory,filePath,binding){return normalizePathForComparison(filePath)===normalizePathForComparison(getBindingFilePath(directory,binding))}function migrateLegacyBindingsSync(directory,scanCapacity=bindingFileScanCapacity){try{assertProjectRoot(directory)}catch{return!1}let scopesDir=getScopesDir(directory);if(!isScopesDirSafe(directory,scopesDir))return!1;let names;try{names=fs19.readdirSync(scopesDir).sort()}catch{return!0}if(names.length>scanCapacity)return!1;for(let name of names){let match=/^binding-(.+)-([a-f0-9]{24})\.json$/i.exec(name);if(!match||!isSafeTaskId(match[1]))continue;let legacyPath=path35.join(scopesDir,name),releaseMigration;try{releaseMigration=lockfileWithSync.lockSync(legacyPath,{stale:LOCK_STALE_MS2,realpath:!1})}catch{return!1}try{let raw=readBoundedFile(legacyPath),binding=null;try{binding=raw?validateScopeBindingPayload(directory,JSON.parse(raw),{allowLegacy:!0}):null}catch{binding=null}let ownerHash=binding?createHash19("sha256").update(binding.ownerSessionId).digest("hex").slice(0,24):"",valid=binding&&binding.taskId===match[1]&&ownerHash.toLowerCase()===match[2].toLowerCase()&&normalizePathForComparison(getLegacyBindingFilePath(directory,binding.taskId,binding.ownerSessionId))===normalizePathForComparison(legacyPath),archiveDir=path35.join(scopesDir,"archive");fs19.mkdirSync(archiveDir,{recursive:!0});let archiveStat=fs19.lstatSync(archiveDir);if(!archiveStat.isDirectory()||archiveStat.isSymbolicLink())return!1;let archiveDigest=createHash19("sha256").update(raw??name).digest("hex").slice(0,32);if(valid&&binding){let exactPath=getBindingFilePath(directory,binding);if(!fs19.existsSync(exactPath))atomicWriteSwarmFileSync(exactPath,JSON.stringify(binding,null,2));else{let existingRaw=readBoundedFile(exactPath),existing=existingRaw?validateScopeBindingPayload(directory,JSON.parse(existingRaw)):null;if(!existing||existing.bindingId!==binding.bindingId||existing.generationId!==binding.generationId)return!1}}let archivePath=path35.join(archiveDir,`${valid?"migrated":"quarantined"}-${archiveDigest}.json`);if(!fs19.existsSync(archivePath))fs19.renameSync(legacyPath,archivePath);else fs19.unlinkSync(legacyPath);fs19.writeFileSync(`${archivePath}.receipt.json`,JSON.stringify({version:1,legacyName:name,result:valid?"migrated":"quarantined",bindingId:binding?.bindingId,generationId:binding?.generationId},null,2));let archiveEntries=fs19.readdirSync(archiveDir).sort();for(let stale of archiveEntries.slice(0,Math.max(0,archiveEntries.length-2*MAX_DURABLE_TOMBSTONES))){let stalePath=path35.join(archiveDir,stale);try{let stat7=fs19.lstatSync(stalePath);if(stat7.isFile()&&!stat7.isSymbolicLink())fs19.unlinkSync(stalePath)}catch{}}}catch{return!1}finally{try{releaseMigration?.()}catch{}}}return!0}async function writeScopeToDisk(directory,taskId,files,ttlMs=DEFAULT_TTL_MS){if(!isSafeTaskId(taskId))return;if(!Array.isArray(files)||files.length===0)return;if(files.length>MAX_FILES_PER_SCOPE)return;try{assertProjectRoot(directory)}catch{return}let scopesDir=getScopesDir(directory),scopePath=getScopeFilePath(directory,taskId);try{fs19.mkdirSync(scopesDir,{recursive:!0})}catch{return}if(!isScopesDirSafe(directory,scopesDir))return;let now=Date.now(),payload={version:SCOPE_SCHEMA_VERSION,taskId,declaredAt:now,expiresAt:now+ttlMs,files:[...files]},content=JSON.stringify(payload,null,2);try{let flags=fs19.constants.O_WRONLY|fs19.constants.O_CREAT,nofollow=fs19.constants.O_NOFOLLOW??0,fd=fs19.openSync(scopePath,flags|nofollow);fs19.closeSync(fd)}catch{return}let release;try{let lockPath=getGenerationLockPath(scopePath);if(!await ensureLockTarget(lockPath))return;release=await import_proper_lockfile6.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),await atomicWrite(scopePath,content)}catch{}finally{if(release)try{await release()}catch{}}}async function writeScopeBindingToDisk(directory,binding){try{assertProjectRoot(directory)}catch(error49){return persistenceFailure(`Scope persistence project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}if(!isSafeTaskId(binding.taskId)||binding.version!==2)return persistenceFailure("Invalid binding schema or task identity.");let workspaceIdentity=canonicalWorkspaceIdentity(directory),files=normalizeScopeFiles(binding.files);if(!workspaceIdentity||workspaceIdentity!==binding.workspaceIdentity||!files||!binding.ownerSessionId||!binding.ownerMessageId||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId)||binding.revision<1||binding.lifecycleState==="live"&&binding.expiresAt<=Date.now())return persistenceFailure("Binding identity, workspace, scope, or lease is invalid.");let imported=ensureScopeBindingAuthorityImported(directory);if(!imported.ok)return imported;let all=readAllAuthoritativeScopeBindings(directory,{enforceLiveCapacity:!1});if(!all.ok)return all;let current=all.value.find((candidate)=>candidate.generationId===binding.generationId);if(current&&current.bindingId!==binding.bindingId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"The exact generation identity collides with another binding."};if(current&&current.revision===binding.revision&&current.lifecycleState===binding.lifecycleState&&JSON.stringify(current.files)===JSON.stringify(files))return writeScopeBindingShadow(directory,current),{ok:!0,value:current};let expectedRevision=current?binding.revision-1:null;if(binding.revision!==(current?.revision??0)+1)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Exact generation write requires the next CAS revision."};let persisted=transitionScopeBindingState(directory,{...binding,files},expectedRevision);if(persisted.ok)writeScopeBindingShadow(directory,persisted.value);return persisted}function persistenceFailure(message){return{ok:!1,code:"SCOPE_BINDING_PERSISTENCE_FAILED",message}}async function persistAndRegisterScopeBinding(directory,binding){let persisted=await writeScopeBindingToDisk(directory,binding);if(!persisted.ok)return persisted;let admission=registerScopeBinding(persisted.value);if(admission.ok)return scheduleScopeBindingMaintenance(directory),{ok:!0,value:persisted.value};let rollback=await tombstoneScopeBinding(directory,persisted.value,"superseded");return{ok:!1,code:rollback.ok?admission.code:"SCOPE_BINDING_PERSISTENCE_FAILED",message:rollback.ok?admission.message:`Memory admission failed and rollback failed: ${rollback.message}`}}function rollbackAdmissionFailure(directory,persisted,predecessors,admission){let now=Date.now(),revokedCandidate={...persisted,revision:persisted.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(persisted.expiresAt,now)},restoredCandidates=predecessors.map(({original,superseded})=>({...original,revision:superseded.revision+1,lifecycleState:"live",updatedAt:now})),failureMessage=null;try{withCoordinationTransaction(directory,()=>{let revoked=_scopePersistenceInternals.transitionScopeBindingStateWithinTransaction(directory,revokedCandidate,persisted.revision);if(!revoked.ok)throw failureMessage=revoked.message,Error("Scope rollback revocation transition failed.");for(let index=0;index<restoredCandidates.length;index+=1){let restored=restoredCandidates[index],superseded=predecessors[index].superseded,result=_scopePersistenceInternals.transitionScopeBindingStateWithinTransaction(directory,restored,superseded.revision);if(!result.ok)throw failureMessage=result.message,Error("Scope rollback predecessor restore failed.")}})}catch(error49){return persistenceFailure(`Memory admission failed and durable rollback failed: ${failureMessage??(error49 instanceof Error?error49.message:"unknown coordination error")}`)}installScopeBindingTombstone(revokedCandidate),writeScopeBindingShadow(directory,revokedCandidate);let admitted=[];for(let restored of restoredCandidates){writeScopeBindingShadow(directory,restored);let memory=updateExactScopeBinding(restored),admissionResult=memory.ok?memory:registerScopeBinding(restored);if(!admissionResult.ok){for(let applied of admitted)installScopeBindingTombstone({...applied,revision:applied.revision+1,lifecycleState:"revoked",updatedAt:Date.now(),expiresAt:Math.min(applied.expiresAt,Date.now())});return persistenceFailure(`Memory admission failed and predecessor re-admission failed: ${admissionResult.message}`)}admitted.push(restored)}return{ok:!1,code:admission.code,message:admission.message}}function readScopeBindingFromDisk(input){let resolved=resolveScopeBindingFromDisk({...input,includeExpired:!1});return resolved.status==="found"?resolved.binding:null}function resolveScopeBindingFromDisk(input){if(!isSafeTaskId(input.taskId))return{status:"not_declared"};let completeSet=readAllAuthoritativeScopeBindings(input.directory);if(!completeSet.ok){if(completeSet.code==="SCOPE_BINDING_STORE_OVERLOADED")scheduleScopeBindingMaintenance(input.directory);return{status:"overloaded"}}let candidates=completeSet.value.filter((parsed)=>parsed.taskId===input.taskId&&parsed.planId===derivePlanId(input.plan)&&parsed.planStructureHash===computePlanStructureHash(input.plan)&&parsed.ownerSessionId===input.ownerSessionId&&(input.requireDispatchCorrelation!==!0||isDispatchCorrelated2(parsed))&&(input.requireDeclaration!==!0||parsed.activation==="declaration"&&parsed.dispatchCallId===void 0)&&(input.parentCallId===void 0||parsed.parentCallId===input.parentCallId)),live=candidates.filter((candidate)=>candidate.lifecycleState==="live"&&candidate.expiresAt>Date.now());if(live.length>1)return{status:"ambiguous",candidates:live.slice(0,8),totalCandidates:live.length};if(live.length===1)return{status:"found",binding:live[0]};let expired=candidates.filter((candidate)=>candidate.lifecycleState!=="live"||candidate.expiresAt<=Date.now());if(candidates.length>0&&!input.includeExpired)return{status:"not_declared"};return input.includeExpired&&expired.length>0?{status:"expired",candidates:expired.slice(0,8),totalCandidates:expired.length}:(()=>{let inMemory=input.requireDeclaration===!0?[]:getActiveScopeBindingsForSession({directory:input.directory,activeSessionId:input.ownerSessionId}).filter((binding)=>binding.taskId===input.taskId&&binding.planId===derivePlanId(input.plan)&&binding.planStructureHash===computePlanStructureHash(input.plan)&&(input.requireDispatchCorrelation!==!0||isDispatchCorrelated2(binding))&&(input.parentCallId===void 0||binding.parentCallId===input.parentCallId));if(inMemory.length>1)return{status:"ambiguous",candidates:inMemory.slice(0,8),totalCandidates:inMemory.length};return inMemory.length===1?{status:"found",binding:inMemory[0]}:{status:"not_declared"}})()}function isDispatchCorrelated2(binding){return binding.activation==="active"&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId}function clearScopeBindingFromDisk(input){let localRetirement=installScopeBindingRetirementIntent(input.binding);try{assertProjectRoot(input.directory)}catch(error49){return persistenceFailure(`Scope retirement project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}let imported=ensureScopeBindingAuthorityImported(input.directory);if(!imported.ok)return imported;let all=readAllAuthoritativeScopeBindings(input.directory,{enforceLiveCapacity:!1});if(!all.ok)return all;let current=all.value.find((candidate)=>candidate.generationId===input.binding.generationId&&candidate.bindingId===input.binding.bindingId);if(!current)return localRetirement?{ok:!0,value:localRetirement}:persistenceFailure("Exact generation disappeared before serialized retirement.");if(current.lifecycleState!=="live")return installScopeBindingTombstone(current),writeScopeBindingShadow(input.directory,current),{ok:!0,value:current};let now=Date.now(),tombstone={...current,revision:current.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(current.expiresAt,now)},retired=transitionScopeBindingState(input.directory,tombstone,current.revision);if(!retired.ok)return retired;return installScopeBindingTombstone(retired.value),writeScopeBindingShadow(input.directory,retired.value),scheduleScopeBindingMaintenance(input.directory),retired}async function tombstoneScopeBinding(directory,binding,reason){let imported=ensureScopeBindingAuthorityImported(directory);if(!imported.ok)return installFailedRevocationOverlay(binding,reason),imported;let all=readAllAuthoritativeScopeBindings(directory,{enforceLiveCapacity:!1});if(!all.ok)return installFailedRevocationOverlay(binding,reason),all;let current=all.value.find((candidate)=>candidate.generationId===binding.generationId&&candidate.bindingId===binding.bindingId);if(!current)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Exact generation disappeared before tombstone.");if(current.revision!==binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Tombstone CAS revision is stale."};if(current.lifecycleState!=="live")return{ok:!0,value:current};let now=Date.now(),tombstone={...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)},persisted=transitionScopeBindingState(directory,tombstone,current.revision);if(!persisted.ok)return installFailedRevocationOverlay(binding,reason),persisted;return clearExactScopeBinding(binding),installScopeBindingTombstone(persisted.value),writeScopeBindingShadow(directory,persisted.value),scheduleScopeBindingMaintenance(directory),persisted}async function ensureLockTarget(targetPath){return ensureLockTargetSync(targetPath)}async function refreshScopeBindingLease(input){let imported=ensureScopeBindingAuthorityImported(input.directory);if(!imported.ok)return imported;let all=readAllAuthoritativeScopeBindings(input.directory,{enforceLiveCapacity:!1});if(!all.ok)return all;let current=all.value.find((candidate)=>candidate.bindingId===input.bindingId&&candidate.generationId===input.generationId&&candidate.taskId===input.taskId&&candidate.ownerSessionId===input.activeSessionId);if(!current)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Refresh identity is not the exact current session/task generation."};if(current.lifecycleState!=="live"||current.expiresAt<=Date.now()||current.revision!==input.expectedRevision)return{ok:!1,code:current.expiresAt<=Date.now()?"SCOPE_BINDING_EXPIRED":"SCOPE_BINDING_STALE",message:"Refresh cannot renew an expired, tombstoned, or stale generation."};let now=Date.now(),refreshed={...current,revision:current.revision+1,updatedAt:now,leaseStartedAt:now,expiresAt:now+Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS)},persisted=transitionScopeBindingState(input.directory,refreshed,current.revision);if(!persisted.ok)return persisted;return updateExactScopeBinding(persisted.value),writeScopeBindingShadow(input.directory,persisted.value),persisted}async function claimScopeBindingForChildDurably(input){if(!input.parentSessionId.trim()||!input.childSessionId.trim()||!input.dispatchCallId.trim()||input.parentSessionId===input.childSessionId)return persistenceFailure("Claim requires distinct non-empty parent/child identities and an exact dispatch call.");let imported=ensureScopeBindingAuthorityImported(input.directory);if(!imported.ok)return imported;let initial=readAllAuthoritativeScopeBindings(input.directory,{enforceLiveCapacity:!1});if(!initial.ok)return initial;let pending=initial.value.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()&&binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.dispatchCallId===input.dispatchCallId&&binding.ownerMessageId===input.dispatchCallId);if(pending.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Multiple pending generations match this exact Task dispatch."};let predecessor=pending[0];if(!predecessor){let successors=initial.value.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()&&binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.dispatchCallId===input.dispatchCallId&&binding.predecessorGenerationId);if(successors.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Multiple active successors match this Task dispatch."};let existing=successors[0];if(existing?.ownerSessionId===input.childSessionId){let admission=registerScopeBinding(existing);return admission.ok?{ok:!0,value:{previous:existing,claimed:existing}}:{ok:!1,code:admission.code,message:admission.message}}return existing?{ok:!1,code:"SCOPE_BINDING_ALREADY_CLAIMED",message:"This Task dispatch was already claimed by a different child session."}:initial.value.some((candidate)=>candidate.ownerSessionId===input.parentSessionId&&candidate.dispatchCallId===input.dispatchCallId)?{ok:!1,code:"SCOPE_BINDING_EXPIRED",message:"No live pending generation remains for this Task dispatch."}:{ok:!1,code:"SCOPE_NOT_DECLARED",message:"No pending generation matches this Task dispatch."}}try{let claimed=null,retired=null,alreadyClaimed=null;if(withCoordinationTransaction(input.directory,()=>{let currentSet=readAllAuthoritativeScopeBindings(input.directory,{enforceLiveCapacity:!1});if(!currentSet.ok)throw new ScopeCoordinationAbort(currentSet);let currentPredecessor=currentSet.value.find((binding)=>binding.generationId===predecessor.generationId&&binding.bindingId===predecessor.bindingId),liveSuccessors=currentSet.value.filter((binding)=>binding.predecessorGenerationId===predecessor.generationId&&binding.bindingId===predecessor.bindingId&&binding.lifecycleState==="live"&&binding.expiresAt>Date.now());if(liveSuccessors.length>1)throw new ScopeCoordinationAbort({ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Incompatible successors exist for one predecessor generation."});let existing=liveSuccessors[0];if(existing){if(existing.ownerSessionId!==input.childSessionId)throw new ScopeCoordinationAbort({ok:!1,code:"SCOPE_BINDING_ALREADY_CLAIMED",message:"This pending generation has a winner in another child session."});alreadyClaimed=existing;return}if(!currentPredecessor||currentPredecessor.lifecycleState!=="live"||currentPredecessor.expiresAt<=Date.now())throw new ScopeCoordinationAbort({ok:!1,code:"SCOPE_BINDING_EXPIRED",message:"The pending predecessor expired before claim."});predecessor=currentPredecessor;let nextClaimed=createClaimedScopeBinding(predecessor,input),claimedWrite=_scopePersistenceInternals.transitionScopeBindingStateWithinTransaction(input.directory,nextClaimed,null);if(!claimedWrite.ok)throw new ScopeCoordinationAbort(claimedWrite);let superseded={...predecessor,revision:predecessor.revision+1,lifecycleState:"superseded",updatedAt:claimedWrite.value.updatedAt,expiresAt:Math.min(predecessor.expiresAt,claimedWrite.value.updatedAt)},retiredWrite=_scopePersistenceInternals.transitionScopeBindingStateWithinTransaction(input.directory,superseded,predecessor.revision);if(!retiredWrite.ok)throw new ScopeCoordinationAbort(retiredWrite);claimed=claimedWrite.value,retired=retiredWrite.value}),alreadyClaimed){let admission2=registerScopeBinding(alreadyClaimed);return admission2.ok?{ok:!0,value:{previous:predecessor,claimed:alreadyClaimed}}:{ok:!1,code:admission2.code,message:admission2.message}}if(!predecessor||!claimed||!retired)return persistenceFailure("Claim transaction did not settle a winner.");writeScopeBindingShadow(input.directory,claimed),writeScopeBindingShadow(input.directory,retired);let admission=registerScopeBinding(claimed);if(!admission.ok)return rollbackAdmissionFailure(input.directory,claimed,[{original:predecessor,superseded:retired}],admission);return installScopeBindingTombstone(retired),{ok:!0,value:{previous:predecessor,claimed}}}catch(error49){if(error49 instanceof ScopeCoordinationAbort)return error49.failure;return persistenceFailure(`Claim transaction failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}async function replaceExistingScopeDeclaration(input){try{assertProjectRoot(input.directory)}catch(error49){return persistenceFailure(`Scope declaration project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}let{binding}=input;if(binding.activation!=="declaration"||binding.dispatchCallId!==void 0)return persistenceFailure("declare_scope may persist only a declaration generation.");let imported=ensureScopeBindingAuthorityImported(input.directory);if(!imported.ok)return imported;let all=readAllAuthoritativeScopeBindings(input.directory,{enforceLiveCapacity:!1});if(!all.ok)return all;let owned=all.value.filter((candidate)=>candidate.lifecycleState==="live"&&candidate.expiresAt>Date.now()&&candidate.workspaceIdentity===binding.workspaceIdentity&&candidate.taskId===binding.taskId&&candidate.ownerSessionId===binding.ownerSessionId&&candidate.generationId!==binding.generationId);if(owned.length>0&&!input.replaceExisting)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"A live owned generation already exists; retry declare_scope with replace_existing=true to revoke it atomically."};try{let persisted=null,retired=[];if(withCoordinationTransaction(input.directory,()=>{let create=_scopePersistenceInternals.transitionScopeBindingStateWithinTransaction(input.directory,binding,null);if(!create.ok)throw new ScopeCoordinationAbort(create);persisted=create.value;for(let prior of owned){let superseded={...prior,revision:prior.revision+1,lifecycleState:"superseded",updatedAt:create.value.updatedAt,expiresAt:Math.min(prior.expiresAt,create.value.updatedAt)},result=_scopePersistenceInternals.transitionScopeBindingStateWithinTransaction(input.directory,superseded,prior.revision);if(!result.ok)throw new ScopeCoordinationAbort(result);retired.push(result.value)}}),!persisted)return persistenceFailure("Declaration transaction did not persist a generation.");writeScopeBindingShadow(input.directory,persisted);for(let prior of retired)writeScopeBindingShadow(input.directory,prior),installScopeBindingTombstone(prior);let admission=registerScopeBinding(persisted);if(!admission.ok){if(retired.length!==owned.length)return persistenceFailure("Memory admission failed after an incomplete predecessor transition.");return rollbackAdmissionFailure(input.directory,persisted,owned.map((original,index)=>({original,superseded:retired[index]})),admission)}return{ok:!0,value:persisted}}catch(error49){if(error49 instanceof ScopeCoordinationAbort)return error49.failure;return persistenceFailure(`Declaration transaction failed: ${error49 instanceof Error?error49.message:"unknown coordination error"}`)}}function scheduleScopeBindingMaintenance(directory){let key=canonicalExistingFilesystemPath(directory);if(key===null)return;if(maintenanceJobs.has(key))return;while(maintenanceJobs.size>=MAX_MAINTENANCE_JOBS){let oldest=maintenanceJobs.keys().next().value;if(!oldest)break;maintenanceJobs.delete(oldest)}let job=Promise.resolve().then(()=>pruneScopeBindingTombstones(directory)).then(()=>{return}).catch(()=>{return}).finally(()=>maintenanceJobs.delete(key));maintenanceJobs.set(key,job)}async function flushScopeBindingMaintenance(directory){let key=directory?canonicalExistingFilesystemPath(directory):void 0;if(directory&&key===null)return;let job=key?maintenanceJobs.get(key):void 0;await Promise.all(job?[job]:[...maintenanceJobs.values()])}async function pruneScopeBindingTombstones(directory){let lockPath=path35.join(getScopesDir(directory),"maintenance.lock-target");if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare scope maintenance lock.");let release;try{release=await import_proper_lockfile6.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1});let readAll=readAllAuthoritativeScopeBindings(directory,{enforceLiveCapacity:!1,maintenanceScan:!0});if(!readAll.ok)return readAll;let all=readAll.value,tombstones=all.filter((binding)=>binding.lifecycleState!=="live").sort((left,right)=>left.updatedAt-right.updatedAt),now=Date.now(),removable=tombstones.filter((binding,index)=>now-binding.updatedAt>MAX_TOMBSTONE_AGE_MS||index<tombstones.length-MAX_DURABLE_TOMBSTONES),removed=0;for(let binding of removable){let filePath=resolveSafeScopeFileForUnlink(directory,getBindingFilePath(directory,binding));if(!filePath)continue;let exactLockPath=getGenerationLockPath(filePath);if(!await ensureLockTarget(exactLockPath))continue;let releaseExact,removedExact=!1;try{releaseExact=await import_proper_lockfile6.default.lock(exactLockPath,{stale:LOCK_STALE_MS2,retries:{retries:0},realpath:!1});let latestRaw=readBoundedFile(filePath),latest=latestRaw?validateScopeBindingPayload(directory,JSON.parse(latestRaw)):null;if(!latest||latest.generationId!==binding.generationId||latest.revision!==binding.revision||latest.lifecycleState==="live"&&!hasDurableRetirementIntent(filePath,latest))continue;deleteCoordinationState(directory,SCOPE_BINDING_COORDINATION_NAMESPACE,binding.generationId,binding.revision),fs19.unlinkSync(filePath),removedExact=!0,removed++}catch{}finally{if(releaseExact)try{await releaseExact()}catch{}}if(removedExact&&!fs19.existsSync(filePath)){try{fs19.unlinkSync(exactLockPath)}catch{}try{fs19.unlinkSync(getRetirementIntentPath(filePath))}catch{}}}let receiptNames=[];try{receiptNames=fs19.readdirSync(getScopesDir(directory)).filter((name)=>/^claim-[a-f0-9]{40}\.json$/i.test(name)).slice(0,MAX_BINDING_FILES_TO_SCAN)}catch{}for(let name of receiptNames){let receiptPath=path35.join(getScopesDir(directory),name),releaseReceipt;try{releaseReceipt=await import_proper_lockfile6.default.lock(receiptPath,{stale:LOCK_STALE_MS2,retries:{retries:0},realpath:!1});let raw=readBoundedFile(receiptPath);if(!raw)continue;let receipt=null;try{receipt=JSON.parse(raw)}catch{}let winner=receipt?all.find((binding)=>binding.generationId===receipt?.winnerGenerationId):void 0;if(Date.now()-fs19.statSync(receiptPath).mtimeMs>MAX_TOMBSTONE_AGE_MS||Boolean(winner&&(winner.lifecycleState!=="live"||winner.expiresAt<=Date.now())))fs19.unlinkSync(receiptPath),removed++}catch{}finally{if(releaseReceipt)try{await releaseReceipt()}catch{}}}return{ok:!0,value:removed}}catch(error49){return persistenceFailure(`Scope maintenance failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function readCurrentPlan(directory){try{let planPath=path35.join(directory,".swarm","plan.json"),stat7=fs19.statSync(planPath);if(!stat7.isFile()||stat7.size>MAX_PLAN_BYTES)return null;let parsed=PlanSchema.safeParse(JSON.parse(fs19.readFileSync(planPath,"utf8")));return parsed.success?parsed.data:null}catch{return null}}function appendScopeBindingRevivalEvent(workspace,revived){try{appendCoreEventSync(workspace,{type:"scope_binding_auto_recovered",timestamp:new Date().toISOString(),taskId:revived.taskId,sessionId:revived.ownerSessionId,generationId:revived.generationId,revision:revived.revision,expiresAt:new Date(revived.expiresAt).toISOString()})}catch{}}function attemptIdleScopeBindingRevival(directory,resolution){if(resolution.status!=="expired")return null;if(resolution.totalCandidates!==1||resolution.candidates.length!==1)return null;let candidate=resolution.candidates[0];if(!candidate)return null;let now=Date.now();if(candidate.lifecycleState!=="live")return null;if(candidate.expiresAt>now)return null;if(now-candidate.expiresAt>SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS)return null;if(hasDeliberateScopeBindingDenyOverlay(candidate))return null;if(!ensureScopeBindingAuthorityImported(directory).ok)return null;let all=readAllAuthoritativeScopeBindings(directory,{enforceLiveCapacity:!1});if(!all.ok)return null;let current=all.value.find((binding)=>binding.bindingId===candidate.bindingId&&binding.generationId===candidate.generationId);if(!current||current.revision!==candidate.revision||current.lifecycleState!=="live"||current.expiresAt>Date.now()||Date.now()-current.expiresAt>SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS)return null;let revivedAt=Date.now(),revived={...current,revision:current.revision+1,updatedAt:revivedAt,leaseStartedAt:revivedAt,expiresAt:revivedAt+DEFAULT_SCOPE_BINDING_TTL_MS},persisted=transitionScopeBindingState(directory,revived,current.revision);if(!persisted.ok)return null;return writeScopeBindingShadow(directory,persisted.value),clearSweepTombstoneForRevival(persisted.value),appendScopeBindingRevivalEvent(directory,persisted.value),persisted.value}function resolveAuthorizedScopeBindingForPlan(input){let resolution=resolveAuthorizedScopeBindingForPlanDetailed(input);return resolution.status==="found"?resolution.binding:null}function resolveAuthorizedScopeBindingForPlanDetailed(input){let durable=resolveScopeBindingFromDisk({directory:input.directory,taskId:input.taskId,plan:input.plan,ownerSessionId:input.activeSessionId,requireDispatchCorrelation:!0,includeExpired:!0});if(durable.status==="found"){if(hasScopeBindingDenyOverlay(durable.binding))return{status:"expired",candidates:[durable.binding],totalCandidates:1};return registerScopeBinding(durable.binding).ok?durable:{status:"overloaded"}}if(durable.status==="expired"){let revived=attemptIdleScopeBindingRevival(input.directory,durable);if(revived){if(registerScopeBinding(revived).ok)return{status:"found",binding:revived}}}if(durable.status!=="not_declared")return durable;return{status:"not_declared"}}function resolveAuthorizedScopeBinding(input){let plan=readCurrentPlan(input.directory);return plan?resolveAuthorizedScopeBindingForPlan({...input,plan}):null}function resolveAuthorizedScopeBindingDetailed(input){let plan=readCurrentPlan(input.directory);return plan?resolveAuthorizedScopeBindingForPlanDetailed({...input,plan}):{status:"not_declared"}}function resolveAuthorizedScopeBindingForSession(input){let resolution=resolveAuthorizedScopeBindingForSessionDetailed(input);return resolution.status==="found"?resolution.binding:null}function resolveAuthorizedScopeBindingForSessionDetailed(input){let plan=readCurrentPlan(input.directory);if(!plan)return{status:"not_declared"};let matches=[],expired=[],expiredTotal=0;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let resolution=resolveAuthorizedScopeBindingForPlanDetailed({directory:input.directory,plan,taskId:task.id,activeSessionId:input.activeSessionId});if(resolution.status==="overloaded")return resolution;if(resolution.status==="ambiguous")return resolution;if(resolution.status==="found")matches.push(resolution.binding);if(resolution.status==="expired")expired.push(...resolution.candidates),expiredTotal+=resolution.totalCandidates;if(matches.length>1)return{status:"ambiguous",candidates:matches.slice(0,8),totalCandidates:matches.length}}if(matches[0])return{status:"found",binding:matches[0]};return expired.length>0?{status:"expired",candidates:expired.slice(0,8),totalCandidates:expiredTotal}:{status:"not_declared"}}function resolveAuthorizedPrFeedbackScopeBindingFromDisk(input){if(!input.activeSessionId.trim())return null;let authoritative=readAllAuthoritativeScopeBindings(input.directory,{enforceLiveCapacity:!1});if(!authoritative.ok)return null;let now=Date.now(),matches=authoritative.value.filter((parsed)=>parsed.source==="pr_feedback"&&(!input.taskId||parsed.taskId===input.taskId)&&parsed.ownerSessionId===input.activeSessionId&&parsed.activation==="active"&&typeof parsed.dispatchCallId==="string"&&parsed.dispatchCallId.length>0&&parsed.ownerMessageId===parsed.dispatchCallId&&typeof parsed.parentOwnerSessionId==="string"&&parsed.parentOwnerSessionId.length>0&&parsed.ownerSessionId!==parsed.parentOwnerSessionId&&parsed.parentCallId===parsed.dispatchCallId&&parsed.workflowSessionId===parsed.parentOwnerSessionId&&typeof parsed.workflowRevisionDigest==="string"&&parsed.workflowRevisionDigest.length>0&&parsed.planId===`pr-feedback:${parsed.workflowSessionId}`&&parsed.planStructureHash===parsed.workflowRevisionDigest&&parsed.declaredAt<=now&&parsed.expiresAt>now&&parsed.lifecycleState==="live"&&!hasScopeBindingDenyOverlay(parsed));if(matches.length!==1)return null;return registerScopeBinding(matches[0]).ok?matches[0]:null}async function atomicWrite(targetPath,content){await atomicWriteSwarmFile(targetPath,content)}function atomicWriteSync(targetPath,content){atomicWriteSwarmFileSync(targetPath,content)}function readScopeFromDisk(directory,taskId){if(!isSafeTaskId(taskId))return null;let scopesDir=getScopesDir(directory);if(!isScopesDirSafe(directory,scopesDir))return null;let scopePath=getScopeFilePath(directory,taskId),nofollow=fs19.constants.O_NOFOLLOW??0,fd;try{fd=fs19.openSync(scopePath,fs19.constants.O_RDONLY|nofollow)}catch{return null}let raw;try{let stat7=fs19.fstatSync(fd);if(!stat7.isFile())return null;if(stat7.size>MAX_SCOPE_BYTES)return null;let buf=Buffer.alloc(stat7.size);fs19.readSync(fd,buf,0,stat7.size,0),raw=buf.toString("utf-8")}catch{return null}finally{try{fs19.closeSync(fd)}catch{}}if(!raw.trim())return null;let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(parsed.version!==SCOPE_SCHEMA_VERSION)return null;if(parsed.taskId!==taskId)return null;let now=Date.now();if(typeof parsed.declaredAt!=="number"||parsed.declaredAt>now)return null;if(typeof parsed.expiresAt!=="number"||now>=parsed.expiresAt)return null;if(!Array.isArray(parsed.files))return null;if(parsed.files.length>MAX_FILES_PER_SCOPE)return null;let files=parsed.files.filter((f)=>typeof f==="string");return files.length>0?files:null}function readPlanScope(directory,taskId){if(!isSafeTaskId(taskId))return null;try{let planPath=path35.join(directory,".swarm","plan.json"),stat7=fs19.statSync(planPath);if(!stat7.isFile())return null;if(stat7.size>MAX_PLAN_BYTES)return null;let raw=fs19.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);for(let phase of plan.phases??[])for(let task of phase.tasks??[]){if(task.id!==taskId)continue;let ft=task.files_touched;if(Array.isArray(ft)&&ft.length>0){if(ft.length>MAX_FILES_PER_SCOPE)return null;return ft.filter((f)=>typeof f==="string")}if(typeof ft==="string"&&ft.length>0)return[ft];return null}return null}catch{return null}}function clearScopeForTask(directory,taskId){if(!isSafeTaskId(taskId))return;try{assertProjectRoot(directory),fs19.unlinkSync(getScopeFilePath(directory,taskId))}catch{}}function clearAllScopes(directory){try{assertProjectRoot(directory),fs19.rmSync(getScopesDir(directory),{recursive:!0,force:!0})}catch{}}function resolveScopeWithFallbacks(input){let{directory,taskId,inMemoryScope,pendingMapScope}=input;if(inMemoryScope&&inMemoryScope.length>0)return inMemoryScope;if(taskId){let disk=readScopeFromDisk(directory,taskId);if(disk&&disk.length>0)return disk;let plan=readPlanScope(directory,taskId);if(plan&&plan.length>0)return plan}if(pendingMapScope&&pendingMapScope.length>0)return pendingMapScope;return null}var import_proper_lockfile6,SCOPE_SCHEMA_VERSION=1,DEFAULT_TTL_MS=86400000,LOCK_STALE_MS2=30000,SCOPES_DIR=".swarm/scopes",MAX_FILES_PER_SCOPE=1e4,MAX_PLAN_BYTES=10485760,MAX_SCOPE_BYTES=2097152,MAX_BINDING_FILES_TO_SCAN=1e4,MAX_TOMBSTONE_AGE_MS=604800000,MAX_DURABLE_TOMBSTONES=256,SCOPE_BINDING_COORDINATION_NAMESPACE="scope-binding",SCOPE_BINDING_COORDINATION_IMPORT_SOURCE="scope-binding-v2",liveBindingCapacity,bindingFileScanCapacity,maintenanceFileScanCapacity,MAX_MAINTENANCE_JOBS=64,maintenanceJobs,lockfileWithSync,ScopeCoordinationAbort,WINDOWS_RESERVED,SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS=86400000,_scopePersistenceInternals;var init_scope_persistence=__esm(()=>{init_plan_schema();init_db();init_core_events();init_ledger();init_utils3();init_atomic_write();init_filesystem_identity();init_project_boundary();init_scope_binding();import_proper_lockfile6=__toESM(require_proper_lockfile(),1),liveBindingCapacity=MAX_PENDING_SCOPE_BINDINGS,bindingFileScanCapacity=MAX_BINDING_FILES_TO_SCAN,maintenanceFileScanCapacity=MAX_BINDING_FILES_TO_SCAN*2,maintenanceJobs=new Map,lockfileWithSync=import_proper_lockfile6.default;ScopeCoordinationAbort=class ScopeCoordinationAbort extends Error{failure;constructor(failure){super(failure.message);this.failure=failure;this.name="ScopeCoordinationAbort"}};WINDOWS_RESERVED=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);_scopePersistenceInternals={transitionScopeBindingState,transitionScopeBindingStateWithinTransaction,get liveBindingCapacity(){return liveBindingCapacity},set liveBindingCapacity(value){liveBindingCapacity=Math.max(1,Math.floor(value))},get bindingFileScanCapacity(){return bindingFileScanCapacity},set bindingFileScanCapacity(value){bindingFileScanCapacity=Math.max(1,Math.floor(value))},get maintenanceFileScanCapacity(){return maintenanceFileScanCapacity},set maintenanceFileScanCapacity(value){maintenanceFileScanCapacity=Math.max(1,Math.floor(value))}}});var exports_core3={};__export(exports_core3,{writeLaneProfileToDiskReal:()=>writeLaneProfileToDiskReal,shortenWorktreePath:()=>shortenWorktreePath,resolveWorktreeBaseDir:()=>resolveWorktreeBaseDir,removeWorktree:()=>removeWorktree,removeLaneProfileFromDiskReal:()=>removeLaneProfileFromDiskReal,provisionWorktree:()=>provisionWorktree,makeWorktreeBranchName:()=>makeWorktreeBranchName,isPathUnderSwarmWorktreeBase:()=>isPathUnderSwarmWorktreeBase,isCleanWorktree:()=>isCleanWorktree,cleanUntrackedFiles:()=>cleanUntrackedFiles,checkPathBudget:()=>checkPathBudget,autoCommitDirty:()=>autoCommitDirty,assertCleanWorkingTree:()=>assertCleanWorkingTree,_internals:()=>_internals33});import*as fs20 from"node:fs";import*as fsPromises3 from"node:fs/promises";import*as os8 from"node:os";import*as path36 from"node:path";async function writeLaneProfileToDiskReal(worktreePath,laneIndex,envOverrides){let lines=[];for(let[key,value]of Object.entries(envOverrides)){if(value===null)continue;if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))continue;if(value.includes(`
615
615
  `)||value.includes("\r")){log("writeLaneProfileToDisk: skipping env var with newline in value",{key});continue}lines.push(`${key}=${value}`)}if(lines.length===0)return;let lanesDir=path36.join(worktreePath,".swarm","lanes");await fs20.promises.mkdir(lanesDir,{recursive:!0});let envPath=path36.join(lanesDir,`${laneIndex}.env`);await fs20.promises.writeFile(envPath,`${lines.join(`
@@ -849,8 +849,8 @@ Use this data to avoid repeating known failure patterns.`,summaryText=summaries.
849
849
  `):diffLines.slice(0,MAX_DIFF_LINES).join(`
850
850
  `)+`
851
851
  ... (diff truncated — `+String(diffLines.length-MAX_DIFF_LINES)+" more lines)",changedSectionsSet=new Set,currentSection="";for(let line of diffLines){let headingMatch=line.slice(1).match(/^##\s+(.+)$/);if(headingMatch)currentSection=headingMatch[1].trim();if(line.length>0&&(line[0]==="+"||line[0]==="-")){if(currentSection)changedSectionsSet.add(currentSection)}}return{diff:diffText,changedSections:Array.from(changedSectionsSet)}}function computeLcsDiff(oldLines,newLines){let m=oldLines.length,n=newLines.length,dp=Array.from({length:m+1},()=>Array(n+1).fill(0));for(let i2=1;i2<=m;i2++)for(let j2=1;j2<=n;j2++)if(oldLines[i2-1]===newLines[j2-1])dp[i2][j2]=dp[i2-1][j2-1]+1;else dp[i2][j2]=Math.max(dp[i2-1][j2],dp[i2][j2-1]);let entries=[],i=m,j=n;while(i>0||j>0)if(i>0&&j>0&&oldLines[i-1]===newLines[j-1])entries.unshift({type:"unchanged",line:oldLines[i-1]}),i--,j--;else if(j>0&&(i===0||dp[i][j-1]>=dp[i-1][j]))entries.unshift({type:"add",line:newLines[j-1]}),j--;else entries.unshift({type:"remove",line:oldLines[i-1]}),i--;return entries.map((entry)=>{if(entry.type==="unchanged")return` ${entry.line}`;if(entry.type==="add")return`+${entry.line}`;return`-${entry.line}`})}var _internals49;var init_spec_hash=__esm(()=>{init_effective_spec();_internals49={computeSpecDiff,computeSpecHash,isObligationPreserving,isSpecStale,readEffectiveSpecSync}});import{closeSync as closeSync7,fsyncSync as fsyncSync3,mkdirSync as mkdirSync22,openSync as openSync7,renameSync as renameSync13,unlinkSync as unlinkSync12,writeFileSync as writeFileSync13}from"node:fs";import*as fsPromises4 from"node:fs/promises";import*as path56 from"node:path";function derivePhaseStatusesInPlace(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((t)=>t.status==="completed"))phase.status="complete";else if(tasks.some((t)=>t.status==="in_progress"))phase.status="in_progress";else if(tasks.some((t)=>t.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function statusRank(s){switch(s){case"closed":return 5;case"completed":return 4;case"blocked":return 3;case"in_progress":return 2;case"pending":return 1;default:return 0}}function mergeStatusesTakingPrecedence(validated,replayed,ledgerStatusTaskIds){let projected=structuredClone(validated),replayedByTaskId=new Map;for(let phase of replayed.phases)for(let task of phase.tasks)if(ledgerStatusTaskIds.has(task.id))replayedByTaskId.set(task.id,task.status);for(let phase of projected.phases)for(let task of phase.tasks){let replayedStatus=replayedByTaskId.get(task.id);if(replayedStatus&&statusRank(replayedStatus)>statusRank(task.status))task.status=replayedStatus}return derivePhaseStatusesInPlace(projected),projected}function collectLedgerStatusTaskIds(events){let statusTaskIds=new Set;for(let event of events)if(event.event_type==="task_status_changed"&&typeof event.task_id==="string")statusTaskIds.add(event.task_id);return statusTaskIds}async function retryCasWithBackoff(directory,eventInput,options){let maxRetries=options.maxRetries??CAS_MAX_RETRIES,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter})}catch(error49){if(!(error49 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error49;attempt++;let base=Math.min(CAS_BACKOFF_START_MS*2**(attempt-1),CAS_BACKOFF_CAP_MS),jitter=base*CAS_BACKOFF_JITTER*(Math.random()*2-1),delayMs=Math.max(1,Math.round(base+jitter));if(emit("plan_ledger_cas_retry",{attempt,expectedHashPrefix:currentExpected.slice(0,8),delayMs}),await new Promise((resolve30)=>setTimeout(resolve30,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function loadPlanJsonOnly(directory){try{return await parsePlanJsonCached(directory)}catch(error49){warn(`Plan validation failed for .swarm/plan.json: ${error49 instanceof Error?error49.message:String(error49)}`)}return null}function compareTaskIds(a,b){let partsA=a.split(".").map((n)=>parseInt(n,10)),partsB=b.split(".").map((n)=>parseInt(n,10)),maxLen=Math.max(partsA.length,partsB.length);for(let i=0;i<maxLen;i++){let numA=partsA[i]??0,numB=partsB[i]??0;if(numA!==numB)return numA-numB}return 0}async function getLatestLedgerHash(directory){try{let events=await readLedgerEvents(directory);if(events.length===0)return"";return events[events.length-1].plan_hash_after}catch{return""}}async function surfaceLedgerStaleIfPersisted(directory,plan){let resolvedWorkspace=canonicalRootKeyFresh(directory);if(!ledgerStaleWorkspaces.has(resolvedWorkspace))return plan;try{let planHash=computePlanLedgerHash(plan),ledgerHash=await getLatestLedgerHash(directory);if(ledgerHash!==""&&planHash===ledgerHash)return ledgerStaleWorkspaces.delete(resolvedWorkspace),plan}catch{}if(plan._ledgerReplayStale=!0,typeof plan._ledgerReplayStaleReason!=="string"||plan._ledgerReplayStaleReason.length===0)plan._ledgerReplayStaleReason="plan.json still hash-mismatches the ledger after a startup ledger-replay failure (replay could not be applied and no critic-approved snapshot was available). Run /swarm reset-session if this persists.";return plan}async function parsePlanJsonCached(directory){let planJsonPath=path56.resolve(directory,".swarm","plan.json");return readCachedParsedFile(planJsonPath,PLAN_JSON_CACHE_NAMESPACE,()=>_internals50.readPlanJsonUtf8(directory),(planJsonContent)=>{if(planJsonContent.includes("\x00"))throw Error("Plan rejected: .swarm/plan.json contains null bytes");let parsed=JSON.parse(planJsonContent);return PlanSchema.parse(parsed)})}async function readPlanJsonUtf8(directory){return readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals50.readPlanFileUtf8(filePath),!1)}async function readPlanFileUtf8(filePath){return new TextDecoder("utf-8",{fatal:!0}).decode(await fsPromises4.readFile(filePath))}function computePlanContentHash(plan){let content={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(compareTaskIds),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason})).sort((a,b)=>compareTaskIds(a.id,b.id))})).sort((a,b)=>a.id-b.id)},jsonString=JSON.stringify(content);return bunHash(jsonString).toString(36)}function extractPlanHashFromMarkdown(markdown){let match=markdown.match(/<!--\s*PLAN_HASH:\s*(\S+)\s*-->/);return match?match[1]:null}async function isPlanMdInSync(directory,plan,cache2){let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent===null)return!1;let expectedHash=computePlanContentHash(plan);if(extractPlanHashFromMarkdown(planMdContent)===expectedHash)return!0;let normalizedExpected=derivePlanMarkdown(plan).trim();if(planMdContent.trim()===normalizedExpected)return!0;return!1}async function regeneratePlanMarkdown(directory,plan){assertProjectRoot(directory);let swarmDir=path56.resolve(directory,".swarm"),contentHash=computePlanContentHash(plan),markdown=derivePlanMarkdown(plan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
852
- ${markdown}`,mdPath=path56.join(swarmDir,"plan.md"),mdTempPath=path56.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync13(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}async function loadPlan(directory,cache2){let planJsonContent=null;try{planJsonContent=await _internals50.readPlanJsonUtf8(directory)}catch(error49){warn(`Plan rejected: .swarm/plan.json could not be decoded as valid UTF-8: ${error49 instanceof Error?error49.message:String(error49)}`)}if(planJsonContent!==null)if(planJsonContent.includes("\x00"))warn("Plan rejected: .swarm/plan.json contains null bytes");else try{let validated=await parsePlanJsonCached(directory);if(validated===null)warn("[loadPlan] plan.json disappeared during cached parse. Falling back to plan.md migration or ledger recovery.");else{if(!await isPlanMdInSync(directory,validated,cache2))try{await _internals50.regeneratePlanMarkdown(directory,validated)}catch(regenError){warn(`Failed to regenerate plan.md: ${regenError instanceof Error?regenError.message:String(regenError)}. Proceeding with plan.json only.`)}if(await ledgerExists(directory)){let planHash=computePlanLedgerHash(validated),ledgerHash=await getLatestLedgerHash(directory),resolvedWorkspace=canonicalRootKeyFresh(directory);if(!startupLedgerCheckedWorkspaces.has(resolvedWorkspace)){if(startupLedgerCheckedWorkspaces.add(resolvedWorkspace),ledgerHash!==""&&planHash!==ledgerHash){let currentPlanId=derivePlanId(validated),ledgerEvents=await readLedgerEvents(directory),firstEvent=ledgerEvents.length>0?ledgerEvents[0]:null;if(firstEvent&&firstEvent.plan_id!==currentPlanId)warn(`[loadPlan] Ledger identity mismatch (ledger: ${firstEvent.plan_id}, plan: ${currentPlanId}) — skipping ledger rebuild (migration detected). Use /swarm reset-session to reinitialize the ledger.`);else{warn("[loadPlan] plan.json is stale (hash mismatch with ledger) — rebuilding from ledger. If this recurs, run /swarm reset-session to clear stale session state.");try{let{plan:rebuilt,truncated}=await replayFromLedgerWithStatus(directory);if(truncated){let runtimeStale=validated;return runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason="Ledger truncated: a malformed line stopped replay before the tail, so the ledger could only be reconstructed up to the corruption. plan.json was PRESERVED (not rolled back to the prefix-only projection) and the corrupted suffix was quarantined to .swarm/plan-ledger.quarantine.*. Verify state, then run /swarm reset-session if this persists.",ledgerStaleWorkspaces.add(resolvedWorkspace),criticalWarn("[loadPlan] Ledger truncated (poison line detected) — preserving plan.json instead of rolling back to the prefix-only ledger projection. Durable post-poison events remain in plan.json. Corrupted suffix quarantined to .swarm/plan-ledger.quarantine.*. Run /swarm reset-session after verifying state if this persists."),runtimeStale}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"ledger_hash_mismatch_recovery"}),warn("[loadPlan] Rebuilt plan from ledger. Checkpoint available at .swarm/plan-export/SWARM_PLAN.md if it exists."),rebuilt}catch(replayError){try{let approved=await loadLastApprovedPlan(directory,currentPlanId);if(approved){await rebuildPlan(directory,approved.plan,{reason:"approved_snapshot_fallback"});try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;return warn(`[loadPlan] Ledger replay failed (${replayError instanceof Error?replayError.message:String(replayError)}) — recovered from critic-approved snapshot seq=${approved.seq} (approval phase=${approvedPhase??"unknown"}, timestamp=${approved.timestamp}). This may roll the plan back to an earlier phase — verify before continuing.`),approved.plan}}catch{}{let runtimeStale=validated;runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason=`Ledger replay failed during hash-mismatch rebuild and no approved snapshot was available: ${replayError instanceof Error?replayError.message:String(replayError)}`,ledgerStaleWorkspaces.add(resolvedWorkspace)}warn(`[loadPlan] Ledger replay failed during hash-mismatch rebuild: ${replayError instanceof Error?replayError.message:String(replayError)}. Returning stale plan.json. To recover: check .swarm/plan-export/SWARM_PLAN.md for a checkpoint, or run /swarm reset-session.`)}}}}else if(ledgerHash!==""&&planHash!==ledgerHash){if(process.env.DEBUG_SWARM)console.warn(`[loadPlan] Ledger hash mismatch during active session for ${resolvedWorkspace} — skipping rebuild (startup check already performed).`)}}if(validated.specHash){let staleResult=await isSpecStale(directory,validated);if(staleResult.stale){let runtimePlan=validated;if(runtimePlan._specStale=!0,runtimePlan._specStaleReason=staleResult.reason,!await isObligationPreserving(directory)){try{assertProjectRoot(directory);let diffInfo=computeSpecDiff(directory),specStalenessPath=path56.join(directory,".swarm","spec-staleness.json");await fsPromises4.writeFile(specStalenessPath,JSON.stringify({type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason,planTitle:validated.title,diff:diffInfo?.diff??null,changedSections:diffInfo?.changedSections??[]},null,2),"utf-8"),invalidateCachedArtifact(specStalenessPath)}catch{}try{assertProjectRoot(directory);let event={type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason??"unknown",planTitle:validated.title};appendCoreEventSync(directory,{...event})}catch{}}}}return await surfaceLedgerStaleIfPersisted(directory,validated)}}catch(error49){warn(`[loadPlan] plan.json validation failed: ${error49 instanceof Error?error49.message:String(error49)}. Attempting rebuild from ledger. If rebuild fails, check .swarm/plan-export/SWARM_PLAN.md for a checkpoint.`);let rawPlanId=null;try{let rawParsed=JSON.parse(planJsonContent);if(typeof rawParsed?.swarm==="string"&&typeof rawParsed?.title==="string")rawPlanId=derivePlanId(rawParsed)}catch{}if(await ledgerExists(directory)){let ledgerEventsForCatch=await readLedgerEvents(directory),catchFirstEvent=ledgerEventsForCatch.length>0?ledgerEventsForCatch[0]:null;if(!(rawPlanId===null||catchFirstEvent===null||catchFirstEvent.plan_id===rawPlanId))warn(`[loadPlan] Ledger identity mismatch in validation-failure path (ledger: ${catchFirstEvent?.plan_id}, plan: ${rawPlanId}) — skipping ledger rebuild (migration detected).`);else if(catchFirstEvent!==null&&rawPlanId!==null){let rebuilt=await replayFromLedger(directory);if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"validation_failure_recovery"}),warn("[loadPlan] Rebuilt plan from ledger after validation failure. Projection was stale."),rebuilt}}let planMdContent2=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent2!==null){let migrated=migrateLegacyPlan(planMdContent2),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json");if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return migrated}}if(await ledgerExists(directory)){let resolvedDir=canonicalRootKeyFresh(directory),existingMutex=recoveryMutexes.get(resolvedDir);if(existingMutex){await existingMutex;let postRecoveryPlan=await _internals50.loadPlanJsonOnly(directory);if(postRecoveryPlan)return postRecoveryPlan}let resolveRecovery,mutex=new Promise((r)=>{resolveRecovery=r});recoveryMutexes.set(resolvedDir,mutex);try{let rebuilt=await replayFromLedger(directory);if(rebuilt){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,rebuilt,"load_plan_rebuild_from_ledger","rebuild plan from ledger replay");if(removedCount>0)rebuilt._midLoadRemovals={count:removedCount,source:"load_plan_rebuild_from_ledger"};return rebuilt}try{let anchorEvents=await readLedgerEvents(directory);if(anchorEvents.length===0)return warn("[loadPlan] Ledger present but no events readable — refusing approved-snapshot recovery (cannot verify plan identity)."),null;let expectedPlanId=anchorEvents[0].plan_id,approved=await loadLastApprovedPlan(directory,expectedPlanId);if(approved){let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;warn(`[loadPlan] Ledger replay returned no plan — recovered from critic-approved snapshot seq=${approved.seq} timestamp=${approved.timestamp} (approval phase=${approvedPhase??"unknown"}). This may roll the plan back to an earlier phase — verify before continuing.`);let{removedCount:snapshotRemovedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot");if(snapshotRemovedCount>0)approved.plan._midLoadRemovals={count:snapshotRemovedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return approved.plan}}catch(recoveryError){warn(`[loadPlan] Approved-snapshot recovery failed: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`)}}finally{resolveRecovery(),recoveryMutexes.delete(resolvedDir)}}let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent!==null){let migrated=migrateLegacyPlan(planMdContent);return await savePlan(directory,migrated),migrated}return null}async function savePlanWithAutoAcknowledgedRemovals(directory,plan,source,reason,options){let existing=await _internals50.loadPlanJsonOnly(directory),newIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)newIds.add(task.id);let removedIds=[];if(existing){for(let phase of existing.phases)for(let task of phase.tasks)if(!newIds.has(task.id))removedIds.push(task.id)}return await savePlan(directory,plan,{...options??{},acknowledged_removals:{ids:removedIds,reason,source}}),{removedCount:removedIds.length}}async function withPlanLifecycleLock(directory,taskId,fn2){assertProjectRoot(directory);let lockResult=await tryAcquireLock(directory,"plan.json","plan-lifecycle",taskId);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan lifecycle blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{return await fn2()}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}async function savePlan(directory,plan,options){if(directory===null||directory===void 0||typeof directory!=="string"||directory.trim().length===0)throw Error("Invalid directory: directory must be a non-empty string");if(assertProjectRoot(directory),!options?.planLockAlreadyHeld){let lockResult=await tryAcquireLock(directory,"plan.json","plan-manager",`save-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{await savePlan(directory,plan,{...options,planLockAlreadyHeld:!0});return}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}let validated=PlanSchema.parse(plan),requestedForStaleProjectionReconcile=options?.staleProjectionReconcile!==void 0?PlanSchema.parse(plan):null;if(requestedForStaleProjectionReconcile)derivePhaseStatusesInPlace(requestedForStaleProjectionReconcile);if(options?.preserveCompletedStatuses!==!1)try{let currentPlan2=await _internals50.loadPlanJsonOnly(directory);if(currentPlan2){let completedTaskIds=new Set;for(let phase of currentPlan2.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.add(task.id);if(completedTaskIds.size>0){for(let phase of validated.phases)for(let task of phase.tasks)if(completedTaskIds.has(task.id)&&task.status!=="completed")task.status="completed"}}}catch{}derivePhaseStatusesInPlace(validated);let currentPlan=await _internals50.loadPlanJsonOnly(directory),planId=derivePlanId(validated),planHashForInit=computePlanLedgerHash(validated);if(!await ledgerExists(directory))try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated)}catch(initErr){let msg=initErr instanceof Error?initErr.message:String(initErr);if(!/already initialized/i.test(msg))throw initErr}else{let existingEvents=await readLedgerEvents(directory);if(existingEvents.length>0&&existingEvents[0].plan_id!==planId)options?.preCommitCheck?.(),await replacePlanLedgerWithRoot(directory,validated,"savePlan_identity_migration"),warn(`[savePlan] Ledger identity mismatch (was "${existingEvents[0].plan_id}", now "${planId}") — archived the prior exact history and committed a new root.`)}if(options?.staleProjectionReconcile){if(!currentPlan)throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: no current plan.json projection exists.");let comparableCurrent=PlanSchema.parse(currentPlan);if(derivePhaseStatusesInPlace(comparableCurrent),JSON.stringify(comparableCurrent)!==JSON.stringify(requestedForStaleProjectionReconcile))throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: manager rejected content that is not the exact unchanged plan.json projection.");let events=await readLedgerEvents(directory),tail=events[events.length-1],expected=options.staleProjectionReconcile;if(!tail||tail.seq!==expected.expectedSeq||tail.plan_hash_after!==expected.expectedLedgerHash||events[0]?.plan_id!==planId)throw new PlanConcurrentModificationError("RECONCILE_LEDGER_PROJECTION_STALE: the ledger identity or tail changed before the recovery snapshot could be appended.");try{if((await readLedgerEventsWithIntegrity(directory)).truncated)await replaceTruncatedLedgerWithRecoveryRoot(directory,validated,{seq:expected.expectedSeq,ledgerHash:expected.expectedLedgerHash});else await takeSnapshotEvent(directory,validated,{planHashAfter:computePlanLedgerHash(validated),source:"save_plan_stale_projection_reconcile",expectedSeq:expected.expectedSeq,expectedLedgerHash:expected.expectedLedgerHash})}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`RECONCILE_LEDGER_PROJECTION_STALE: ${error49.message}`);throw error49}}let currentHash=computeCurrentPlanHash(directory),hashAfter=computePlanLedgerHash(validated);if(currentPlan){let oldTaskMap=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldTaskMap.set(task.id,{phase:task.phase,status:task.status});let newTaskIds=new Set;for(let phase of validated.phases)for(let task of phase.tasks)newTaskIds.add(task.id);let missingTasks=[];for(let[id,info]of oldTaskMap.entries())if(!newTaskIds.has(id))missingTasks.push({id,phase:info.phase,status:info.status});let ack=options?.acknowledged_removals;if(missingTasks.length>0){if(!ack)throw new PlanTaskRemovalNotAcknowledgedError(missingTasks);if(typeof ack.reason!=="string"||ack.reason.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.reason must be a non-empty string.");if(typeof ack.source!=="string"||ack.source.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.source must be a non-empty string.");let ackSet=new Set(ack.ids),missingIdsSet=new Set(missingTasks.map((t)=>t.id)),unacked=missingTasks.filter((t)=>!ackSet.has(t.id));if(unacked.length>0)throw new PlanTaskRemovalNotAcknowledgedError(unacked);for(let id of ack.ids)if(!missingIdsSet.has(id))throw Error(`PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals contains "${id}" but that task is not missing from the plan.`);try{for(let missing of missingTasks){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_removed",task_id:missing.id,phase_id:missing.phase,from_status:missing.status,source:ack.source,payload:{reason:ack.reason,source:ack.source}},capturedTaskId=missing.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals50.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases)if(p.tasks.some((x)=>x.id===capturedTaskId))return!0;return!1}})}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}try{for(let phase of validated.phases)for(let task of phase.tasks){let oldTask=oldTaskMap.get(task.id);if(oldTask&&oldTask.status!==task.status){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_status_changed",task_id:task.id,phase_id:phase.id,from_status:oldTask.status,to_status:task.status,source:"savePlan"},capturedFromStatus=oldTask.status,capturedTaskId=task.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals50.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases){let t=p.tasks.find((x)=>x.id===capturedTaskId);if(t)return t.status===capturedFromStatus}return!1}})}}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}let ledgerStatusTaskIds=collectLedgerStatusTaskIds(await readLedgerEvents(directory)),replayedBeforeProjection=await replayFromLedger(directory),projectionCandidate=replayedBeforeProjection?mergeStatusesTakingPrecedence(validated,replayedBeforeProjection,ledgerStatusTaskIds):validated;if(replayedBeforeProjection&&computePlanLedgerHash(replayedBeforeProjection)!==computePlanLedgerHash(projectionCandidate))options?.preCommitCheck?.(),await takeSnapshotEvent(directory,projectionCandidate,{planHashAfter:computePlanLedgerHash(projectionCandidate),source:"savePlan_structural_projection"});let projectedPlan=projectionCandidate,SNAPSHOT_INTERVAL=50,latestSeq=await getLatestLedgerSeq(directory);if(!options?.preCommitCheck&&latestSeq>0&&latestSeq%SNAPSHOT_INTERVAL===0)await takeSnapshotWithRetry(directory,projectedPlan,{planHashAfter:computePlanLedgerHash(projectedPlan),source:"savePlan_manager"});let swarmDir=path56.resolve(directory,".swarm"),planPath=path56.join(swarmDir,"plan.json"),tempPath=path56.join(swarmDir,`plan.json.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(tempPath,JSON.stringify(projectedPlan,null,2)),options?.preCommitCheck?.(),renameSync13(tempPath,planPath)}finally{try{unlinkSync12(tempPath)}catch{}}invalidateCachedArtifact(planPath);try{let markerPath=path56.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:projectedPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let contentHash=computePlanContentHash(projectedPlan),markdown=derivePlanMarkdown(projectedPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
853
- ${markdown}`,mdPath=path56.join(swarmDir,"plan.md"),mdTempPath=path56.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync13(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}catch(mdError){let message=mdError instanceof Error?mdError.message:String(mdError);warn(`[savePlan] plan.md write failed (non-fatal, plan.json is authoritative): ${message}`);try{emit("plan_md_write_failed",{directory,error:message,timestamp:new Date().toISOString()})}catch{}}try{let markerPath=path56.join(swarmDir,".plan-write-marker"),tasksCount=projectedPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}if(currentPlan)try{let oldIdentityHash=derivePlanIdentityHash(currentPlan),newIdentityHash=derivePlanIdentityHash(projectedPlan);if(oldIdentityHash===newIdentityHash){let oldStatuses=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldStatuses.set(task.id,task.status);let newStatuses=new Map;for(let phase of projectedPlan.phases)for(let task of phase.tasks)newStatuses.set(task.id,task.status);for(let[taskId,oldStatus]of oldStatuses){let newStatus=newStatuses.get(taskId);if(oldStatus==="completed"&&newStatus!=="completed")advanceTaskCheckpointReceiptGeneration(directory,oldIdentityHash,taskId)}for(let[taskId,newStatus]of newStatuses)if(newStatus==="completed"&&oldStatuses.get(taskId)!=="completed")repairTaskCheckpointReceiptForCompletion(directory,newIdentityHash,taskId)}}catch(receiptError){warn(`[savePlan] task checkpoint receipt lifecycle sync failed (plan remains authoritative): ${receiptError instanceof Error?receiptError.message:String(receiptError)}`)}}async function rebuildPlan(directory,plan,options){assertProjectRoot(directory);let targetPlan=plan??await replayFromLedger(directory);if(!targetPlan)return null;let swarmDir=path56.join(directory,".swarm"),planPath=path56.join(swarmDir,"plan.json"),mdPath=path56.join(swarmDir,"plan.md");mkdirSync22(swarmDir,{recursive:!0});let tempPlanPath=path56.join(swarmDir,`plan.json.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);{let fd=openSync7(tempPlanPath,"w");try{writeFileSync13(fd,JSON.stringify(targetPlan,null,2),"utf8"),fsyncSync3(fd)}finally{closeSync7(fd)}}renameSync13(tempPlanPath,planPath),invalidateCachedArtifact(planPath);try{let markerPath=path56.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let contentHash=computePlanContentHash(targetPlan),markdown=derivePlanMarkdown(targetPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
852
+ ${markdown}`,mdPath=path56.join(swarmDir,"plan.md"),mdTempPath=path56.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync13(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}async function loadPlan(directory,cache2){let planJsonContent=null;try{planJsonContent=await _internals50.readPlanJsonUtf8(directory)}catch(error49){warn(`Plan rejected: .swarm/plan.json could not be decoded as valid UTF-8: ${error49 instanceof Error?error49.message:String(error49)}`)}if(planJsonContent!==null)if(planJsonContent.includes("\x00"))warn("Plan rejected: .swarm/plan.json contains null bytes");else try{let validated=await parsePlanJsonCached(directory);if(validated===null)warn("[loadPlan] plan.json disappeared during cached parse. Falling back to plan.md migration or ledger recovery.");else{if(!await isPlanMdInSync(directory,validated,cache2))try{await _internals50.regeneratePlanMarkdown(directory,validated)}catch(regenError){warn(`Failed to regenerate plan.md: ${regenError instanceof Error?regenError.message:String(regenError)}. Proceeding with plan.json only.`)}if(await ledgerExists(directory)){let planHash=computePlanLedgerHash(validated),ledgerHash=await getLatestLedgerHash(directory),resolvedWorkspace=canonicalRootKeyFresh(directory);if(!startupLedgerCheckedWorkspaces.has(resolvedWorkspace)){if(startupLedgerCheckedWorkspaces.add(resolvedWorkspace),ledgerHash!==""&&planHash!==ledgerHash){let currentPlanId=derivePlanId(validated),ledgerEvents=await readLedgerEvents(directory),firstEvent=ledgerEvents.length>0?ledgerEvents[0]:null;if(firstEvent&&firstEvent.plan_id!==currentPlanId)warn(`[loadPlan] Ledger identity mismatch (ledger: ${firstEvent.plan_id}, plan: ${currentPlanId}) — skipping ledger rebuild (migration detected). Use /swarm reset-session to reinitialize the ledger.`);else{warn("[loadPlan] plan.json is stale (hash mismatch with ledger) — rebuilding from ledger. If this recurs, run /swarm reset-session to clear stale session state.");try{let{plan:rebuilt,truncated}=await replayFromLedgerWithStatus(directory);if(truncated){let runtimeStale=validated;return runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason="Ledger truncated: a malformed line stopped replay before the tail, so the ledger could only be reconstructed up to the corruption. plan.json was PRESERVED (not rolled back to the prefix-only projection) and the corrupted suffix was quarantined to .swarm/plan-ledger.quarantine.*. Verify state, then run /swarm reset-session if this persists.",ledgerStaleWorkspaces.add(resolvedWorkspace),criticalWarn("[loadPlan] Ledger truncated (poison line detected) — preserving plan.json instead of rolling back to the prefix-only ledger projection. Durable post-poison events remain in plan.json. Corrupted suffix quarantined to .swarm/plan-ledger.quarantine.*. Run /swarm reset-session after verifying state if this persists."),runtimeStale}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"ledger_hash_mismatch_recovery"}),warn("[loadPlan] Rebuilt plan from ledger. Checkpoint available at .swarm/plan-export/SWARM_PLAN.md if it exists."),rebuilt}catch(replayError){try{let approved=await loadLastApprovedPlan(directory,currentPlanId);if(approved){await rebuildPlan(directory,approved.plan,{reason:"approved_snapshot_fallback"});try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;return warn(`[loadPlan] Ledger replay failed (${replayError instanceof Error?replayError.message:String(replayError)}) — recovered from critic-approved snapshot seq=${approved.seq} (approval phase=${approvedPhase??"unknown"}, timestamp=${approved.timestamp}). This may roll the plan back to an earlier phase — verify before continuing.`),approved.plan}}catch{}{let runtimeStale=validated;runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason=`Ledger replay failed during hash-mismatch rebuild and no approved snapshot was available: ${replayError instanceof Error?replayError.message:String(replayError)}`,ledgerStaleWorkspaces.add(resolvedWorkspace)}warn(`[loadPlan] Ledger replay failed during hash-mismatch rebuild: ${replayError instanceof Error?replayError.message:String(replayError)}. Returning stale plan.json. To recover: check .swarm/plan-export/SWARM_PLAN.md for a checkpoint, or run /swarm reset-session.`)}}}}else if(ledgerHash!==""&&planHash!==ledgerHash){if(process.env.DEBUG_SWARM)console.warn(`[loadPlan] Ledger hash mismatch during active session for ${resolvedWorkspace} — skipping rebuild (startup check already performed).`)}}if(validated.specHash){let staleResult=await isSpecStale(directory,validated);if(staleResult.stale){let runtimePlan=validated;if(runtimePlan._specStale=!0,runtimePlan._specStaleReason=staleResult.reason,!await isObligationPreserving(directory)){try{assertProjectRoot(directory);let diffInfo=computeSpecDiff(directory),specStalenessPath=path56.join(directory,".swarm","spec-staleness.json");await fsPromises4.writeFile(specStalenessPath,JSON.stringify({type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason,planTitle:validated.title,diff:diffInfo?.diff??null,changedSections:diffInfo?.changedSections??[]},null,2),"utf-8"),invalidateCachedArtifact(specStalenessPath)}catch{}try{assertProjectRoot(directory);let event={type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason??"unknown",planTitle:validated.title};appendCoreEventSync(directory,{...event})}catch{}}}}return await surfaceLedgerStaleIfPersisted(directory,validated)}}catch(error49){warn(`[loadPlan] plan.json validation failed: ${error49 instanceof Error?error49.message:String(error49)}. Attempting rebuild from ledger. If rebuild fails, check .swarm/plan-export/SWARM_PLAN.md for a checkpoint.`);let rawPlanId=null;try{let rawParsed=JSON.parse(planJsonContent);if(typeof rawParsed?.swarm==="string"&&typeof rawParsed?.title==="string")rawPlanId=derivePlanId(rawParsed)}catch{}if(await _internals50.ledgerExists(directory)){let ledgerEventsForCatch=(await _internals50.readLedgerEventsWithIntegrity(directory)).events,catchFirstEvent=ledgerEventsForCatch.length>0?ledgerEventsForCatch[0]:null;if(!(rawPlanId===null||catchFirstEvent===null||catchFirstEvent.plan_id===rawPlanId))warn(`[loadPlan] Ledger identity mismatch in validation-failure path (ledger: ${catchFirstEvent?.plan_id}, plan: ${rawPlanId}) — skipping ledger rebuild (migration detected).`);else if(catchFirstEvent!==null&&rawPlanId!==null){let rebuilt=null;try{rebuilt=await _internals50.replayFromLedger(directory)}catch(replayError){warn(`[loadPlan] Ledger replay threw in validation-failure path: ${replayError instanceof Error?replayError.message:String(replayError)}. Falling back to critic-approved snapshot before legacy migration.`)}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"validation_failure_recovery"}),warn("[loadPlan] Rebuilt plan from ledger after validation failure. Projection was stale."),rebuilt;try{let approved=await _internals50.loadLastApprovedPlan(directory,catchFirstEvent.plan_id);if(approved){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot");if(removedCount>0)approved.plan._midLoadRemovals={count:removedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return warn(`[loadPlan] Recovered from critic-approved snapshot seq=${approved.seq} after validation failure with exhausted ledger replay (approved snapshot beats lossy Markdown migration).`),approved.plan}}catch(approvedError){warn(`[loadPlan] Approved-snapshot recovery failed in validation-failure path: ${approvedError instanceof Error?approvedError.message:String(approvedError)}`)}}}let planMdContent2=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent2!==null){let migrated=migrateLegacyPlan(planMdContent2),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json");if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return await appendMigrationProvenanceEvent(directory,migrated),migrated}}if(await _internals50.ledgerExists(directory)){let resolvedDir=canonicalRootKeyFresh(directory),existingMutex=recoveryMutexes.get(resolvedDir);if(existingMutex){await existingMutex;let postRecoveryPlan=await _internals50.loadPlanJsonOnly(directory);if(postRecoveryPlan)return postRecoveryPlan}let resolveRecovery,mutex=new Promise((r)=>{resolveRecovery=r});recoveryMutexes.set(resolvedDir,mutex);try{let rebuilt=null;try{rebuilt=await _internals50.replayFromLedger(directory)}catch(replayError){warn(`[loadPlan] Ledger replay threw in missing-projection path: ${replayError instanceof Error?replayError.message:String(replayError)}. Falling back to critic-approved snapshot before legacy migration.`)}if(rebuilt){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,rebuilt,"load_plan_rebuild_from_ledger","rebuild plan from ledger replay");if(removedCount>0)rebuilt._midLoadRemovals={count:removedCount,source:"load_plan_rebuild_from_ledger"};return rebuilt}try{let anchorEvents=(await _internals50.readLedgerEventsWithIntegrity(directory)).events;if(anchorEvents.length===0)return warn("[loadPlan] Ledger present but no events readable — refusing approved-snapshot recovery (cannot verify plan identity)."),null;let expectedPlanId=anchorEvents[0].plan_id,approved=await _internals50.loadLastApprovedPlan(directory,expectedPlanId);if(approved){let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;warn(`[loadPlan] Ledger replay returned no plan — recovered from critic-approved snapshot seq=${approved.seq} timestamp=${approved.timestamp} (approval phase=${approvedPhase??"unknown"}). This may roll the plan back to an earlier phase — verify before continuing.`);let{removedCount:snapshotRemovedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot");if(snapshotRemovedCount>0)approved.plan._midLoadRemovals={count:snapshotRemovedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return approved.plan}}catch(recoveryError){warn(`[loadPlan] Approved-snapshot recovery failed: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`)}}finally{resolveRecovery(),recoveryMutexes.delete(resolvedDir)}}let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent!==null){let migrated=migrateLegacyPlan(planMdContent),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json");if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return await appendMigrationProvenanceEvent(directory,migrated),migrated}return null}async function savePlanWithAutoAcknowledgedRemovals(directory,plan,source,reason,options){let existing=await _internals50.loadPlanJsonOnly(directory),newIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)newIds.add(task.id);let removedIds=[];if(existing){for(let phase of existing.phases)for(let task of phase.tasks)if(!newIds.has(task.id))removedIds.push(task.id)}return await savePlan(directory,plan,{...options??{},acknowledged_removals:{ids:removedIds,reason,source}}),{removedCount:removedIds.length}}async function withPlanLifecycleLock(directory,taskId,fn2){assertProjectRoot(directory);let lockResult=await tryAcquireLock(directory,"plan.json","plan-lifecycle",taskId);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan lifecycle blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{return await fn2()}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}async function verifyWrittenPlanJson(directory,expected){let content;try{content=await readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals50.readPlanFileUtf8(filePath),!1)}catch(error49){throw new PlanWriteVerificationError(`PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back could not be read (${error49 instanceof Error?error49.message:String(error49)})`)}for(let attempt=0;content===null&&attempt<PLAN_WRITE_VERIFY_READ_RETRIES;attempt++){await new Promise((resolve30)=>setTimeout(resolve30,PLAN_WRITE_VERIFY_READ_BACKOFF_MS*(attempt+1)));try{content=await readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals50.readPlanFileUtf8(filePath),!1)}catch{}}if(content===null)throw new PlanWriteVerificationError("PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back returned no content after write");let parsed;try{parsed=JSON.parse(content)}catch(error49){throw new PlanWriteVerificationError(`PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back did not parse (${error49 instanceof Error?error49.message:String(error49)})`)}if(JSON.stringify(parsed)!==JSON.stringify(expected))throw new PlanWriteVerificationError("PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back content differs from the projected plan")}async function appendMigrationProvenanceEvent(directory,plan){try{await appendLedgerEvent(directory,{event_type:"plan_rebuilt",source:"load_plan_migration_from_md",plan_id:derivePlanId(plan),payload:{reason:"load_plan_migration_from_md",phases_count:plan.phases.length,tasks_count:plan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0)}})}catch(error49){warn(`[loadPlan] Markdown-migration provenance event append failed (plan remains migrated): ${error49 instanceof Error?error49.message:String(error49)}`)}}async function savePlan(directory,plan,options){if(directory===null||directory===void 0||typeof directory!=="string"||directory.trim().length===0)throw Error("Invalid directory: directory must be a non-empty string");if(assertProjectRoot(directory),!options?.planLockAlreadyHeld){let lockResult=await tryAcquireLock(directory,"plan.json","plan-manager",`save-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{return await savePlan(directory,plan,{...options,planLockAlreadyHeld:!0})}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}let validated=PlanSchema.parse(plan),requestedForStaleProjectionReconcile=options?.staleProjectionReconcile!==void 0?PlanSchema.parse(plan):null;if(requestedForStaleProjectionReconcile)derivePhaseStatusesInPlace(requestedForStaleProjectionReconcile);if(options?.preserveCompletedStatuses!==!1)try{let currentPlan2=await _internals50.loadPlanJsonOnly(directory);if(currentPlan2){let completedTaskIds=new Set;for(let phase of currentPlan2.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.add(task.id);if(completedTaskIds.size>0){for(let phase of validated.phases)for(let task of phase.tasks)if(completedTaskIds.has(task.id)&&task.status!=="completed")task.status="completed"}}}catch{}derivePhaseStatusesInPlace(validated);let currentPlan=await _internals50.loadPlanJsonOnly(directory),planId=derivePlanId(validated),planHashForInit=computePlanLedgerHash(validated);if(!await ledgerExists(directory))try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated)}catch(initErr){let msg=initErr instanceof Error?initErr.message:String(initErr);if(!/already initialized/i.test(msg))throw initErr}else{let existingEvents=await readLedgerEvents(directory);if(existingEvents.length>0&&existingEvents[0].plan_id!==planId)options?.preCommitCheck?.(),await replacePlanLedgerWithRoot(directory,validated,"savePlan_identity_migration"),warn(`[savePlan] Ledger identity mismatch (was "${existingEvents[0].plan_id}", now "${planId}") — archived the prior exact history and committed a new root.`)}if(options?.staleProjectionReconcile){if(!currentPlan)throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: no current plan.json projection exists.");let comparableCurrent=PlanSchema.parse(currentPlan);if(derivePhaseStatusesInPlace(comparableCurrent),JSON.stringify(comparableCurrent)!==JSON.stringify(requestedForStaleProjectionReconcile))throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: manager rejected content that is not the exact unchanged plan.json projection.");let events=await readLedgerEvents(directory),tail=events[events.length-1],expected=options.staleProjectionReconcile;if(!tail||tail.seq!==expected.expectedSeq||tail.plan_hash_after!==expected.expectedLedgerHash||events[0]?.plan_id!==planId)throw new PlanConcurrentModificationError("RECONCILE_LEDGER_PROJECTION_STALE: the ledger identity or tail changed before the recovery snapshot could be appended.");try{if((await _internals50.readLedgerEventsWithIntegrity(directory)).truncated)await replaceTruncatedLedgerWithRecoveryRoot(directory,validated,{seq:expected.expectedSeq,ledgerHash:expected.expectedLedgerHash});else await takeSnapshotEvent(directory,validated,{planHashAfter:computePlanLedgerHash(validated),source:"save_plan_stale_projection_reconcile",expectedSeq:expected.expectedSeq,expectedLedgerHash:expected.expectedLedgerHash})}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`RECONCILE_LEDGER_PROJECTION_STALE: ${error49.message}`);throw error49}}let currentHash=computeCurrentPlanHash(directory),hashAfter=computePlanLedgerHash(validated);if(currentPlan){let oldTaskMap=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldTaskMap.set(task.id,{phase:task.phase,status:task.status});let newTaskIds=new Set;for(let phase of validated.phases)for(let task of phase.tasks)newTaskIds.add(task.id);let missingTasks=[];for(let[id,info]of oldTaskMap.entries())if(!newTaskIds.has(id))missingTasks.push({id,phase:info.phase,status:info.status});let ack=options?.acknowledged_removals;if(missingTasks.length>0){if(!ack)throw new PlanTaskRemovalNotAcknowledgedError(missingTasks);if(typeof ack.reason!=="string"||ack.reason.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.reason must be a non-empty string.");if(typeof ack.source!=="string"||ack.source.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.source must be a non-empty string.");let ackSet=new Set(ack.ids),missingIdsSet=new Set(missingTasks.map((t)=>t.id)),unacked=missingTasks.filter((t)=>!ackSet.has(t.id));if(unacked.length>0)throw new PlanTaskRemovalNotAcknowledgedError(unacked);for(let id of ack.ids)if(!missingIdsSet.has(id))throw Error(`PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals contains "${id}" but that task is not missing from the plan.`);try{for(let missing of missingTasks){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_removed",task_id:missing.id,phase_id:missing.phase,from_status:missing.status,source:ack.source,payload:{reason:ack.reason,source:ack.source}},capturedTaskId=missing.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals50.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases)if(p.tasks.some((x)=>x.id===capturedTaskId))return!0;return!1}})}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}try{for(let phase of validated.phases)for(let task of phase.tasks){let oldTask=oldTaskMap.get(task.id);if(oldTask&&oldTask.status!==task.status){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_status_changed",task_id:task.id,phase_id:phase.id,from_status:oldTask.status,to_status:task.status,source:"savePlan"},capturedFromStatus=oldTask.status,capturedTaskId=task.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals50.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases){let t=p.tasks.find((x)=>x.id===capturedTaskId);if(t)return t.status===capturedFromStatus}return!1}})}}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}let ledgerStatusTaskIds=collectLedgerStatusTaskIds(await readLedgerEvents(directory)),replayedBeforeProjection=await _internals50.replayFromLedger(directory),projectionCandidate=replayedBeforeProjection?mergeStatusesTakingPrecedence(validated,replayedBeforeProjection,ledgerStatusTaskIds):validated;if(replayedBeforeProjection&&computePlanLedgerHash(replayedBeforeProjection)!==computePlanLedgerHash(projectionCandidate))options?.preCommitCheck?.(),await takeSnapshotEvent(directory,projectionCandidate,{planHashAfter:computePlanLedgerHash(projectionCandidate),source:"savePlan_structural_projection"});let projectedPlan=projectionCandidate,SNAPSHOT_INTERVAL=50,latestSeq=await getLatestLedgerSeq(directory);if(!options?.preCommitCheck&&latestSeq>0&&latestSeq%SNAPSHOT_INTERVAL===0)await takeSnapshotWithRetry(directory,projectedPlan,{planHashAfter:computePlanLedgerHash(projectedPlan),source:"savePlan_manager"});let swarmDir=path56.resolve(directory,".swarm"),planPath=path56.join(swarmDir,"plan.json"),tempPath=path56.join(swarmDir,`plan.json.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(tempPath,JSON.stringify(projectedPlan,null,2)),options?.preCommitCheck?.(),renameSync13(tempPath,planPath)}finally{try{unlinkSync12(tempPath)}catch{}}invalidateCachedArtifact(planPath),await _internals50.verifyWrittenPlanJson(directory,projectedPlan);try{let markerPath=path56.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:projectedPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}let mdWriteError;try{let contentHash=computePlanContentHash(projectedPlan),markdown=derivePlanMarkdown(projectedPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
853
+ ${markdown}`,mdPath=path56.join(swarmDir,"plan.md"),mdTempPath=path56.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync13(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}catch(mdError){let message=mdError instanceof Error?mdError.message:String(mdError);mdWriteError=message,warn(`[savePlan] plan.md write failed (non-fatal, plan.json is authoritative): ${message}`);try{emit("plan_md_write_failed",{directory,error:message,timestamp:new Date().toISOString()})}catch{}}try{let markerPath=path56.join(swarmDir,".plan-write-marker"),tasksCount=projectedPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}if(currentPlan)try{let oldIdentityHash=derivePlanIdentityHash(currentPlan),newIdentityHash=derivePlanIdentityHash(projectedPlan);if(oldIdentityHash===newIdentityHash){let oldStatuses=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldStatuses.set(task.id,task.status);let newStatuses=new Map;for(let phase of projectedPlan.phases)for(let task of phase.tasks)newStatuses.set(task.id,task.status);for(let[taskId,oldStatus]of oldStatuses){let newStatus=newStatuses.get(taskId);if(oldStatus==="completed"&&newStatus!=="completed")advanceTaskCheckpointReceiptGeneration(directory,oldIdentityHash,taskId)}for(let[taskId,newStatus]of newStatuses)if(newStatus==="completed"&&oldStatuses.get(taskId)!=="completed")repairTaskCheckpointReceiptForCompletion(directory,newIdentityHash,taskId)}}catch(receiptError){warn(`[savePlan] task checkpoint receipt lifecycle sync failed (plan remains authoritative): ${receiptError instanceof Error?receiptError.message:String(receiptError)}`)}if(mdWriteError!==void 0)return{durability:"incomplete",degraded_surfaces:["plan.md"],md_write_error:mdWriteError};return{durability:"complete",degraded_surfaces:[]}}async function rebuildPlan(directory,plan,options){assertProjectRoot(directory);let targetPlan=plan??await replayFromLedger(directory);if(!targetPlan)return null;let swarmDir=path56.join(directory,".swarm"),planPath=path56.join(swarmDir,"plan.json"),mdPath=path56.join(swarmDir,"plan.md");mkdirSync22(swarmDir,{recursive:!0});let tempPlanPath=path56.join(swarmDir,`plan.json.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);{let fd=openSync7(tempPlanPath,"w");try{writeFileSync13(fd,JSON.stringify(targetPlan,null,2),"utf8"),fsyncSync3(fd)}finally{closeSync7(fd)}}renameSync13(tempPlanPath,planPath),invalidateCachedArtifact(planPath);try{let markerPath=path56.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let contentHash=computePlanContentHash(targetPlan),markdown=derivePlanMarkdown(targetPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
854
854
  ${markdown}`,tempMdPath=path56.join(swarmDir,`plan.md.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(tempMdPath,markdownWithHash),renameSync13(tempMdPath,mdPath),invalidateCachedArtifact(mdPath)}finally{try{let markerPath=path56.join(swarmDir,".plan-write-marker"),tasksCount=targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}}try{let planId=derivePlanId(targetPlan),planHashAfter=computePlanLedgerHash(targetPlan);await appendLedgerEvent(directory,{event_type:"plan_rebuilt",source:"rebuildPlan",plan_id:planId,payload:{reason:options?.reason??"ledger_replay_recovery",phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0)}},{planHashAfter})}catch{}return targetPlan}async function closePlanTerminalState(directory,plan,options){assertProjectRoot(directory);let planId=derivePlanId(plan),validated=PlanSchema.parse(plan),hashAfter=computePlanLedgerHash(validated);for(let taskId of options.closedTaskIds){let taskPhaseId;for(let phase of validated.phases)if(phase.tasks.some((t)=>t.id===taskId)){taskPhaseId=phase.id;break}let fromStatus=options.originalStatuses?.get(taskId)??"in_progress";await appendLedgerEvent(directory,{plan_id:planId,event_type:"task_status_changed",task_id:taskId,phase_id:taskPhaseId,from_status:fromStatus,to_status:"closed",source:"close_terminal"},{planHashAfter:hashAfter})}for(let phaseId of options.closedPhaseIds)await appendLedgerEvent(directory,{plan_id:planId,event_type:"phase_completed",phase_id:phaseId,source:"close_terminal"},{planHashAfter:hashAfter});await takeSnapshotEvent(directory,validated,{planHashAfter:hashAfter,source:"close_terminal"});let swarmDir=path56.join(directory,".swarm"),planPath=path56.join(swarmDir,"plan.json"),tempPlanPath=path56.join(swarmDir,`plan.json.close.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(tempPlanPath,JSON.stringify(validated,null,2)),renameSync13(tempPlanPath,planPath),invalidateCachedArtifact(planPath);try{let markerPath=path56.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager_close",timestamp:new Date().toISOString(),phases_count:validated.phases.length,tasks_count:validated.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let mdPath=path56.join(swarmDir,"plan.md"),contentHash=computePlanContentHash(validated),markdown=derivePlanMarkdown(validated),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
855
855
  ${markdown}`,mdTempPath=path56.join(swarmDir,`plan.md.close.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(mdTempPath,markdownWithHash),renameSync13(mdTempPath,mdPath),invalidateCachedArtifact(mdPath)}finally{try{let markerPath=path56.join(swarmDir,".plan-write-marker"),tasksCount=validated.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager_close",timestamp:new Date().toISOString(),phases_count:validated.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}}}async function updateTaskStatus(directory,taskId,status,options){assertProjectRoot(directory);let derivePhaseStatusFromTasks=(tasks)=>{if(tasks.length>0&&tasks.every((task)=>task.status==="completed"))return"complete";if(tasks.some((task)=>task.status==="in_progress"))return"in_progress";if(tasks.some((task)=>task.status==="blocked"))return"blocked";return"pending"};{let currentPlan=await _internals50.loadPlanJsonOnly(directory);if(currentPlan){let currentTask=currentPlan.phases.flatMap((p)=>p.tasks).find((t)=>t.id===taskId),settled=currentTask&&currentTask.status!=="pending"&&currentTask.status!=="in_progress",auditedRepair=status==="in_progress"&&options?.force===!0;if(settled&&status!==currentTask.status&&!auditedRepair&&options?.terminalReconciliation!==!0)return warn(`[updateTaskStatus] refusing backward transition of settled task ${taskId} (${currentTask.status}) to ${status} without audited repair`),currentPlan}}let MAX_OUTER_RETRIES=1;for(let attempt=0;attempt<=MAX_OUTER_RETRIES;attempt++){let plan=await _internals50.loadPlan(directory);if(plan===null)throw Error(`Plan not found in directory: ${directory}`);let taskFound=!1,updatedPhases=plan.phases.map((phase)=>{let updatedTasks=phase.tasks.map((task)=>{if(task.id===taskId)return taskFound=!0,{...task,status};return task});return{...phase,status:derivePhaseStatusFromTasks(updatedTasks),tasks:updatedTasks}});if(!taskFound)throw Error(`Task not found: ${taskId}`);let updatedPlan={...plan,phases:updatedPhases};try{if(await savePlan(directory,updatedPlan,{preserveCompletedStatuses:!1,planLockAlreadyHeld:options?.planLockAlreadyHeld}),status==="completed"||status==="blocked"){let recordedTask=updatedPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);try{await _internals50.recordTaskAttempt(directory,{taskId,agent:"plan-status",outcome:status==="completed"?"pass":"fail",failureReason:status==="blocked"?recordedTask?.blocked_reason??"task marked blocked (no blocked_reason recorded)":void 0,fileTargets:recordedTask?.files_touched??[]})}catch(err){warn(`[plan/manager] run-memory record for ${taskId} failed: ${err instanceof Error?err.message:String(err)}`)}}if(status==="completed"&&_internals50.isGitRepo(directory)&&_internals50.isEpicModeActiveForProject(directory)){let mergeFailure=_internals50.getWorktreeMergeFailure(taskId);if(mergeFailure)return criticalWarn(`[plan/manager] Rule 2 auto-commit SKIPPED for ${taskId}: worktree merge-back ${mergeFailure.outcome} at stage '${mergeFailure.stage}'. The task's changes are NOT in the main tree, so no completion marker is written (Rule 3 must not treat this task as satisfied). Resolve the preserved worktree, then re-run the task. Detail: ${mergeFailure.message}`),updatedPlan;try{let taskDescription;for(let phase of updatedPlan.phases){let found=phase.tasks.find((t)=>t.id===taskId);if(found){taskDescription=found.description;break}}let canonicalScope=_internals50.readTaskScopes(directory,taskId);await _internals50.commitTaskCompletion(directory,taskId,taskDescription,canonicalScope??void 0)}catch(commitErr){criticalWarn(`[plan/manager] Rule 2 auto-commit for ${taskId} threw (non-fatal): ${commitErr instanceof Error?commitErr.message:String(commitErr)}`)}}return updatedPlan}catch(error49){if(error49 instanceof PlanConcurrentModificationError&&attempt<MAX_OUTER_RETRIES)continue;throw error49}}throw Error("updateTaskStatus: unexpected loop exit")}function derivePlanMarkdown(plan){let statusMap={pending:"PENDING",in_progress:"IN PROGRESS",complete:"COMPLETE",completed:"COMPLETE",blocked:"BLOCKED",closed:"CLOSED"},now=new Date().toISOString(),currentPhase=plan.current_phase??1,phaseStatus=statusMap[plan.phases[currentPhase-1]?.status]||"PENDING",markdown=`# ${plan.title}
856
856
  Swarm: ${plan.swarm}
@@ -874,7 +874,7 @@ ${phases.join(`
874
874
  ---
875
875
  `)}`}return`${markdown.trim()}
876
876
  `}function getCurrentTaskId(plan){if(!plan)return;let currentPhase=plan.current_phase??1,phase=plan.phases.find((p)=>p.id===currentPhase);if(!phase)return;let sortedTasks=[...phase.tasks].sort((a,b)=>compareTaskIds(a.id,b.id)),inProgress=sortedTasks.find((t)=>t.status==="in_progress");if(inProgress)return inProgress.id;return sortedTasks.find((t)=>t.status!=="completed"&&t.status!=="closed")?.id}function migrateLegacyPlan(planContent,swarmId){let lines=planContent.split(`
877
- `),title="Untitled Plan",swarm=swarmId||"default-swarm",currentPhaseNum=1,phases=[],currentPhase=null;for(let line of lines){let trimmed=line.trim();if(trimmed.startsWith("# ")&&title==="Untitled Plan"){title=trimmed.substring(2).trim();continue}if(trimmed.startsWith("Swarm:")){swarm=trimmed.substring(6).trim();continue}if(trimmed.startsWith("Phase:")){let match=trimmed.match(/Phase:\s*(\d+)/i);if(match)currentPhaseNum=parseInt(match[1],10);continue}let phaseMatch=trimmed.match(/^#{2,3}\s*Phase\s+(\d+)(?::\s*([^[]+))?\s*(?:\[([^\]]+)\])?/i);if(phaseMatch){if(currentPhase!==null)phases.push(currentPhase);let phaseId=parseInt(phaseMatch[1],10),phaseName=phaseMatch[2]?.trim()||`Phase ${phaseId}`,statusText=phaseMatch[3]?.toLowerCase()||"pending";currentPhase={id:phaseId,name:phaseName,status:{complete:"complete",completed:"complete","in progress":"in_progress",in_progress:"in_progress",inprogress:"in_progress",pending:"pending",blocked:"blocked"}[statusText]||"pending",tasks:[]};continue}let taskMatch=trimmed.match(/^-\s*\[([^\]]+)\]\s+(\d+\.\d+):\s*(.+?)(?:\s*\[(\w+)\])?(?:\s*-\s*(.+))?$/i);if(taskMatch&&currentPhase!==null){let checkbox=taskMatch[1].toLowerCase(),taskId=taskMatch[2],description=taskMatch[3].trim(),sizeText=taskMatch[4]?.toLowerCase()||"small",blockedReason,dependsMatch=description.match(/\s*\(depends:\s*([^)]+)\)$/i),depends=[];if(dependsMatch){let depsText=dependsMatch[1];depends.push(...depsText.split(",").map((d)=>d.trim())),description=description.substring(0,dependsMatch.index).trim()}let status="pending";if(checkbox==="x")status="completed";else if(checkbox==="blocked"){status="blocked";let blockedReasonMatch=taskMatch[5];if(blockedReasonMatch)blockedReason=blockedReasonMatch.trim()}let sizeMap={small:"small",medium:"medium",large:"large"},task={id:taskId,phase:currentPhase.id,status,size:sizeMap[sizeText]||"small",description,depends,acceptance:void 0,files_touched:[],evidence_path:void 0,blocked_reason:blockedReason};currentPhase.tasks.push(task)}let numberedTaskMatch=trimmed.match(/^(\d+)\.\s+(.+?)(?:\s*\[(\w+)\])?$/);if(numberedTaskMatch&&currentPhase!==null){let taskId=`${currentPhase.id}.${currentPhase.tasks.length+1}`,description=numberedTaskMatch[2].trim(),sizeText=numberedTaskMatch[3]?.toLowerCase()||"small",dependsMatch=description.match(/\s*\(depends:\s*([^)]+)\)$/i),depends=[];if(dependsMatch){let depsText=dependsMatch[1];depends.push(...depsText.split(",").map((d)=>d.trim())),description=description.substring(0,dependsMatch.index).trim()}let sizeMap={small:"small",medium:"medium",large:"large"},task={id:taskId,phase:currentPhase.id,status:"pending",size:sizeMap[sizeText]||"small",description,depends,acceptance:void 0,files_touched:[],evidence_path:void 0,blocked_reason:void 0};currentPhase.tasks.push(task)}let noPrefixTaskMatch=trimmed.match(/^-\s*\[([^\]]+)\]\s+(?!\d+\.\d+:)(.+?)(?:\s*\[(\w+)\])?(?:\s*-\s*(.+))?$/i);if(noPrefixTaskMatch&&currentPhase!==null){let checkbox=noPrefixTaskMatch[1].toLowerCase(),taskId=`${currentPhase.id}.${currentPhase.tasks.length+1}`,description=noPrefixTaskMatch[2].trim(),sizeText=noPrefixTaskMatch[3]?.toLowerCase()||"small",blockedReason,dependsMatch=description.match(/\s*\(depends:\s*([^)]+)\)$/i),depends=[];if(dependsMatch){let depsText=dependsMatch[1];depends.push(...depsText.split(",").map((d)=>d.trim())),description=description.substring(0,dependsMatch.index).trim()}let status="pending";if(checkbox==="x")status="completed";else if(checkbox==="blocked"){status="blocked";let blockedReasonMatch=noPrefixTaskMatch[4];if(blockedReasonMatch)blockedReason=blockedReasonMatch.trim()}let sizeMap={small:"small",medium:"medium",large:"large"},task={id:taskId,phase:currentPhase.id,status,size:sizeMap[sizeText]||"small",description,depends,acceptance:void 0,files_touched:[],evidence_path:void 0,blocked_reason:blockedReason};currentPhase.tasks.push(task)}}if(currentPhase!==null)phases.push(currentPhase);let migrationStatus="migrated";if(phases.length===0)criticalWarn(`migrateLegacyPlan: 0 phases parsed from ${lines.length} lines. First 3 lines: ${lines.slice(0,3).join(" | ")}`),migrationStatus="migration_failed",phases.push({id:1,name:"Migration Failed",status:"blocked",tasks:[{id:"1.1",phase:1,status:"blocked",size:"large",description:"Review and restructure plan manually",depends:[],files_touched:[],blocked_reason:"Legacy plan could not be parsed automatically"}]});return phases.sort((a,b)=>a.id-b.id),{schema_version:"1.0.0",title,swarm,current_phase:currentPhaseNum,phases,migration_status:migrationStatus}}var PlanConcurrentModificationError,PlanTaskRemovalNotAcknowledgedError,startupLedgerCheckedWorkspaces,ledgerStaleWorkspaces,recoveryMutexes,PLAN_JSON_CACHE_NAMESPACE="plan-json:validated:v1",_internals50,CAS_BACKOFF_START_MS=5,CAS_BACKOFF_CAP_MS=250,CAS_BACKOFF_JITTER=0.25,CAS_MAX_RETRIES=3;var init_manager=__esm(()=>{init_plan_schema();init_task_checkpoint_receipt();init_core_events();init_branch();init_worktree_merge_status();init_utils2();init_file_locks();init_run_memory();init_telemetry();init_state();init_task_commit();init_conflicts();init_utils();init_bun_compat();init_canonical_root();init_project_boundary();init_spec_hash();init_swarm_artifact_cache();init_ledger();init_planning_profile();init_utils3();PlanConcurrentModificationError=class PlanConcurrentModificationError extends Error{constructor(message){super(message);this.name="PlanConcurrentModificationError"}};PlanTaskRemovalNotAcknowledgedError=class PlanTaskRemovalNotAcknowledgedError extends Error{missingTasks;constructor(missingTasks){let idList=missingTasks.map((t)=>`${t.id}(${t.status})`).join(", ");super(`PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: the following tasks were present in the prior plan but missing from the new save: ${idList}. Pass acknowledged_removals.ids covering all missing task IDs with a non-empty reason to proceed.`);this.name="PlanTaskRemovalNotAcknowledgedError",this.missingTasks=missingTasks}};startupLedgerCheckedWorkspaces=new Set,ledgerStaleWorkspaces=new Set,recoveryMutexes=new Map,_internals50={loadPlan,loadPlanJsonOnly,readPlanJsonUtf8,readPlanFileUtf8,regeneratePlanMarkdown,isGitRepo,isEpicModeActiveForProject,readTaskScopes,commitTaskCompletion,getWorktreeMergeFailure,recordTaskAttempt}});function pathMatches(scopePath,cochangePath){if(scopePath===cochangePath)return!0;return scopePath.endsWith(`/${cochangePath}`)}function epicPairConflict(scopeA,scopeB,cochangePairs,threshold){let normA=scopeA.map(normalizePath),normB=scopeB.map(normalizePath),pathPairs=[];for(let a of normA)for(let b of normB)if(pathsConflict(a,b))pathPairs.push([a,b]);let pathConflict=pathPairs.length>0,activePairs=cochangePairs.filter((e)=>e.coChangeCount>=threshold.minCoChanges&&e.npmi>=threshold.npmi),cochangeMatches=[];for(let entry of activePairs){let{fileA:fa,fileB:fb}=entry,aTouchesFa=normA.some((p)=>pathMatches(p,fa)),aTouchesFb=normA.some((p)=>pathMatches(p,fb)),bTouchesFa=normB.some((p)=>pathMatches(p,fa)),bTouchesFb=normB.some((p)=>pathMatches(p,fb));if(aTouchesFa&&!aTouchesFb&&(bTouchesFb&&!bTouchesFa)||aTouchesFb&&!aTouchesFa&&(bTouchesFa&&!bTouchesFb))cochangeMatches.push({a:fa,b:fb,npmi:entry.npmi,coChangeCount:entry.coChangeCount})}let cochangeConflict=cochangeMatches.length>0,reason;if(pathConflict&&cochangeConflict)reason="both";else if(pathConflict)reason="path";else if(cochangeConflict)reason="cochange";else reason="none";return{conflict:pathConflict||cochangeConflict,reason,evidence:{pathPairs,cochangePairs:cochangeMatches}}}var init_cochange_conflict=__esm(()=>{init_conflicts()});function resolveScope(directory,taskId){let raw=readScopeFromDisk(directory,taskId);if(raw===null)return{files:[],ok:!1};if(raw.length===0)return{files:[],ok:!1};return{files:raw,ok:!0}}function computeParallelVerdict(directory,taskIds,options){if(taskIds.length>MAX_PARALLEL_VERDICT_TASKS)throw RangeError(`Parallel verdict supports at most ${MAX_PARALLEL_VERDICT_TASKS} tasks`);let useCochange=options?.useCochange===!0&&Array.isArray(options?.cochangePairs),threshold=options?.cochangeThreshold??DEFAULT_PARALLEL_COCHANGE_THRESHOLD,cochangePairs=useCochange?options.cochangePairs:[],resolved=new Map,unknownScopeTasks=[];for(let id of taskIds){let r=resolveScope(directory,id);if(resolved.set(id,r),!r.ok)unknownScopeTasks.push(id)}let pairs=[],inDegree=new Map,adj=new Map;for(let id of taskIds)inDegree.set(id,0),adj.set(id,[]);for(let i=0;i<taskIds.length;i++)for(let j=i+1;j<taskIds.length;j++){let a=taskIds[i],b=taskIds[j],ra=resolved.get(a),rb=resolved.get(b),pairVerdict,evidence;if(!ra.ok||!rb.ok)pairVerdict="unknown",evidence=[];else{let ev=epicPairConflict(ra.files,rb.files,cochangePairs,threshold);if(ev.conflict){if(pairVerdict="conflict",evidence=formatEvidence(ev),!adj.get(a).includes(b))adj.get(a).push(b),inDegree.set(b,(inDegree.get(b)??0)+1)}else pairVerdict="disjoint",evidence=[]}pairs.push({a,b,verdict:pairVerdict,evidence})}let suggestedSerialOrder=topoSort(taskIds,adj,inDegree),verdict;if(unknownScopeTasks.length>0)verdict="unknown_scopes";else if(pairs.some((p)=>p.verdict==="conflict"))verdict="conflicts_present";else verdict="all_disjoint";return{verdict,pairs,suggestedSerialOrder,unknownScopeTasks}}function formatEvidence(ev){let lines=[];for(let[pa,pb]of ev.evidence.pathPairs)lines.push(`path overlap: ${pa} ↔ ${pb}`);for(let cc of ev.evidence.cochangePairs)lines.push(`co-change: ${cc.a} ↔ ${cc.b} (npmi=${cc.npmi.toFixed(3)}, coChanges=${cc.coChangeCount})`);return lines}function topoSort(taskIds,adj,inDegree){let deg=new Map(inDegree),order=[],queue=[...taskIds.filter((id)=>(deg.get(id)??0)===0)];while(queue.length>0){let cur=queue.shift();order.push(cur);for(let next of adj.get(cur)??[])if(deg.set(next,(deg.get(next)??0)-1),(deg.get(next)??0)===0)queue.push(next);queue.sort((x,y)=>taskIds.indexOf(x)-taskIds.indexOf(y))}if(order.length<taskIds.length){for(let id of taskIds)if(!order.includes(id))order.push(id)}return order}function isProvablyDisjoint(directory,taskIds){return taskIds.length>=2&&computeParallelVerdict(directory,taskIds).verdict==="all_disjoint"}var DEFAULT_PARALLEL_COCHANGE_THRESHOLD,MAX_PARALLEL_VERDICT_TASKS=64;var init_parallel_verdict=__esm(()=>{init_scope_persistence();init_cochange_conflict();init_conflicts();DEFAULT_PARALLEL_COCHANGE_THRESHOLD={npmi:0.2,minCoChanges:3}});function generateCourseCorrection(match,trajectory){let alert=`TRAJECTORY ALERT: ${match.pattern} detected (severity: ${match.severity}) at steps ${match.stepRange[0]}-${match.stepRange[1]}`,guidance=GUIDANCE_TEMPLATES[match.pattern],action=ACTION_TEMPLATES[match.pattern](match,trajectory);return{alert,category:match.category,guidance,action,pattern:match.pattern,stepRange:match.stepRange}}function formatCourseCorrectionForInjection(correction){return`${correction.alert}
877
+ `),title="Untitled Plan",swarm=swarmId||"default-swarm",currentPhaseNum=1,phases=[],currentPhase=null;for(let line of lines){let trimmed=line.trim();if(trimmed.startsWith("# ")&&title==="Untitled Plan"){title=trimmed.substring(2).trim();continue}if(trimmed.startsWith("Swarm:")){swarm=trimmed.substring(6).trim();continue}if(trimmed.startsWith("Phase:")){let match=trimmed.match(/Phase:\s*(\d+)/i);if(match)currentPhaseNum=parseInt(match[1],10);continue}let phaseMatch=trimmed.match(/^#{2,3}\s*Phase\s+(\d+)(?::\s*([^[]+))?\s*(?:\[([^\]]+)\])?/i);if(phaseMatch){if(currentPhase!==null)phases.push(currentPhase);let phaseId=parseInt(phaseMatch[1],10),phaseName=phaseMatch[2]?.trim()||`Phase ${phaseId}`,statusText=phaseMatch[3]?.toLowerCase()||"pending";currentPhase={id:phaseId,name:phaseName,status:{complete:"complete",completed:"complete","in progress":"in_progress",in_progress:"in_progress",inprogress:"in_progress",pending:"pending",blocked:"blocked"}[statusText]||"pending",tasks:[]};continue}let taskMatch=trimmed.match(/^-\s*\[([^\]]+)\]\s+(\d+\.\d+):\s*(.+?)(?:\s*\[(\w+)\])?(?:\s*-\s*(.+))?$/i);if(taskMatch&&currentPhase!==null){let checkbox=taskMatch[1].toLowerCase(),taskId=taskMatch[2],description=taskMatch[3].trim(),sizeText=taskMatch[4]?.toLowerCase()||"small",blockedReason,dependsMatch=description.match(/\s*\(depends:\s*([^)]+)\)$/i),depends=[];if(dependsMatch){let depsText=dependsMatch[1];depends.push(...depsText.split(",").map((d)=>d.trim())),description=description.substring(0,dependsMatch.index).trim()}let status="pending";if(checkbox==="x")status="completed";else if(checkbox==="blocked"){status="blocked";let blockedReasonMatch=taskMatch[5];if(blockedReasonMatch)blockedReason=blockedReasonMatch.trim()}let sizeMap={small:"small",medium:"medium",large:"large"},task={id:taskId,phase:currentPhase.id,status,size:sizeMap[sizeText]||"small",description,depends,acceptance:void 0,files_touched:[],evidence_path:void 0,blocked_reason:blockedReason};currentPhase.tasks.push(task)}let numberedTaskMatch=trimmed.match(/^(\d+)\.\s+(.+?)(?:\s*\[(\w+)\])?$/);if(numberedTaskMatch&&currentPhase!==null){let taskId=`${currentPhase.id}.${currentPhase.tasks.length+1}`,description=numberedTaskMatch[2].trim(),sizeText=numberedTaskMatch[3]?.toLowerCase()||"small",dependsMatch=description.match(/\s*\(depends:\s*([^)]+)\)$/i),depends=[];if(dependsMatch){let depsText=dependsMatch[1];depends.push(...depsText.split(",").map((d)=>d.trim())),description=description.substring(0,dependsMatch.index).trim()}let sizeMap={small:"small",medium:"medium",large:"large"},task={id:taskId,phase:currentPhase.id,status:"pending",size:sizeMap[sizeText]||"small",description,depends,acceptance:void 0,files_touched:[],evidence_path:void 0,blocked_reason:void 0};currentPhase.tasks.push(task)}let noPrefixTaskMatch=trimmed.match(/^-\s*\[([^\]]+)\]\s+(?!\d+\.\d+:)(.+?)(?:\s*\[(\w+)\])?(?:\s*-\s*(.+))?$/i);if(noPrefixTaskMatch&&currentPhase!==null){let checkbox=noPrefixTaskMatch[1].toLowerCase(),taskId=`${currentPhase.id}.${currentPhase.tasks.length+1}`,description=noPrefixTaskMatch[2].trim(),sizeText=noPrefixTaskMatch[3]?.toLowerCase()||"small",blockedReason,dependsMatch=description.match(/\s*\(depends:\s*([^)]+)\)$/i),depends=[];if(dependsMatch){let depsText=dependsMatch[1];depends.push(...depsText.split(",").map((d)=>d.trim())),description=description.substring(0,dependsMatch.index).trim()}let status="pending";if(checkbox==="x")status="completed";else if(checkbox==="blocked"){status="blocked";let blockedReasonMatch=noPrefixTaskMatch[4];if(blockedReasonMatch)blockedReason=blockedReasonMatch.trim()}let sizeMap={small:"small",medium:"medium",large:"large"},task={id:taskId,phase:currentPhase.id,status,size:sizeMap[sizeText]||"small",description,depends,acceptance:void 0,files_touched:[],evidence_path:void 0,blocked_reason:blockedReason};currentPhase.tasks.push(task)}}if(currentPhase!==null)phases.push(currentPhase);let migrationStatus="migrated";if(phases.length===0)criticalWarn(`migrateLegacyPlan: 0 phases parsed from ${lines.length} lines. First 3 lines: ${lines.slice(0,3).join(" | ")}`),migrationStatus="migration_failed",phases.push({id:1,name:"Migration Failed",status:"blocked",tasks:[{id:"1.1",phase:1,status:"blocked",size:"large",description:"Review and restructure plan manually",depends:[],files_touched:[],blocked_reason:"Legacy plan could not be parsed automatically"}]});return phases.sort((a,b)=>a.id-b.id),{schema_version:"1.0.0",title,swarm,current_phase:currentPhaseNum,phases,migration_status:migrationStatus}}var PlanConcurrentModificationError,PlanTaskRemovalNotAcknowledgedError,startupLedgerCheckedWorkspaces,ledgerStaleWorkspaces,recoveryMutexes,PLAN_JSON_CACHE_NAMESPACE="plan-json:validated:v1",_internals50,CAS_BACKOFF_START_MS=5,CAS_BACKOFF_CAP_MS=250,CAS_BACKOFF_JITTER=0.25,CAS_MAX_RETRIES=3,PlanWriteVerificationError,PLAN_WRITE_VERIFY_READ_RETRIES=4,PLAN_WRITE_VERIFY_READ_BACKOFF_MS=200;var init_manager=__esm(()=>{init_plan_schema();init_task_checkpoint_receipt();init_core_events();init_branch();init_worktree_merge_status();init_utils2();init_file_locks();init_run_memory();init_telemetry();init_state();init_task_commit();init_conflicts();init_utils();init_bun_compat();init_canonical_root();init_project_boundary();init_spec_hash();init_swarm_artifact_cache();init_ledger();init_planning_profile();init_utils3();PlanConcurrentModificationError=class PlanConcurrentModificationError extends Error{constructor(message){super(message);this.name="PlanConcurrentModificationError"}};PlanTaskRemovalNotAcknowledgedError=class PlanTaskRemovalNotAcknowledgedError extends Error{missingTasks;constructor(missingTasks){let idList=missingTasks.map((t)=>`${t.id}(${t.status})`).join(", ");super(`PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: the following tasks were present in the prior plan but missing from the new save: ${idList}. Pass acknowledged_removals.ids covering all missing task IDs with a non-empty reason to proceed.`);this.name="PlanTaskRemovalNotAcknowledgedError",this.missingTasks=missingTasks}};startupLedgerCheckedWorkspaces=new Set,ledgerStaleWorkspaces=new Set,recoveryMutexes=new Map,_internals50={loadPlan,loadPlanJsonOnly,readPlanJsonUtf8,readPlanFileUtf8,verifyWrittenPlanJson,ledgerExists,replayFromLedger,loadLastApprovedPlan,readLedgerEventsWithIntegrity,regeneratePlanMarkdown,isGitRepo,isEpicModeActiveForProject,readTaskScopes,commitTaskCompletion,getWorktreeMergeFailure,recordTaskAttempt};PlanWriteVerificationError=class PlanWriteVerificationError extends Error{constructor(message){super(message);this.name="PlanWriteVerificationError"}}});function pathMatches(scopePath,cochangePath){if(scopePath===cochangePath)return!0;return scopePath.endsWith(`/${cochangePath}`)}function epicPairConflict(scopeA,scopeB,cochangePairs,threshold){let normA=scopeA.map(normalizePath),normB=scopeB.map(normalizePath),pathPairs=[];for(let a of normA)for(let b of normB)if(pathsConflict(a,b))pathPairs.push([a,b]);let pathConflict=pathPairs.length>0,activePairs=cochangePairs.filter((e)=>e.coChangeCount>=threshold.minCoChanges&&e.npmi>=threshold.npmi),cochangeMatches=[];for(let entry of activePairs){let{fileA:fa,fileB:fb}=entry,aTouchesFa=normA.some((p)=>pathMatches(p,fa)),aTouchesFb=normA.some((p)=>pathMatches(p,fb)),bTouchesFa=normB.some((p)=>pathMatches(p,fa)),bTouchesFb=normB.some((p)=>pathMatches(p,fb));if(aTouchesFa&&!aTouchesFb&&(bTouchesFb&&!bTouchesFa)||aTouchesFb&&!aTouchesFa&&(bTouchesFa&&!bTouchesFb))cochangeMatches.push({a:fa,b:fb,npmi:entry.npmi,coChangeCount:entry.coChangeCount})}let cochangeConflict=cochangeMatches.length>0,reason;if(pathConflict&&cochangeConflict)reason="both";else if(pathConflict)reason="path";else if(cochangeConflict)reason="cochange";else reason="none";return{conflict:pathConflict||cochangeConflict,reason,evidence:{pathPairs,cochangePairs:cochangeMatches}}}var init_cochange_conflict=__esm(()=>{init_conflicts()});function resolveScope(directory,taskId){let raw=readScopeFromDisk(directory,taskId);if(raw===null)return{files:[],ok:!1};if(raw.length===0)return{files:[],ok:!1};return{files:raw,ok:!0}}function computeParallelVerdict(directory,taskIds,options){if(taskIds.length>MAX_PARALLEL_VERDICT_TASKS)throw RangeError(`Parallel verdict supports at most ${MAX_PARALLEL_VERDICT_TASKS} tasks`);let useCochange=options?.useCochange===!0&&Array.isArray(options?.cochangePairs),threshold=options?.cochangeThreshold??DEFAULT_PARALLEL_COCHANGE_THRESHOLD,cochangePairs=useCochange?options.cochangePairs:[],resolved=new Map,unknownScopeTasks=[];for(let id of taskIds){let r=resolveScope(directory,id);if(resolved.set(id,r),!r.ok)unknownScopeTasks.push(id)}let pairs=[],inDegree=new Map,adj=new Map;for(let id of taskIds)inDegree.set(id,0),adj.set(id,[]);for(let i=0;i<taskIds.length;i++)for(let j=i+1;j<taskIds.length;j++){let a=taskIds[i],b=taskIds[j],ra=resolved.get(a),rb=resolved.get(b),pairVerdict,evidence;if(!ra.ok||!rb.ok)pairVerdict="unknown",evidence=[];else{let ev=epicPairConflict(ra.files,rb.files,cochangePairs,threshold);if(ev.conflict){if(pairVerdict="conflict",evidence=formatEvidence(ev),!adj.get(a).includes(b))adj.get(a).push(b),inDegree.set(b,(inDegree.get(b)??0)+1)}else pairVerdict="disjoint",evidence=[]}pairs.push({a,b,verdict:pairVerdict,evidence})}let suggestedSerialOrder=topoSort(taskIds,adj,inDegree),verdict;if(unknownScopeTasks.length>0)verdict="unknown_scopes";else if(pairs.some((p)=>p.verdict==="conflict"))verdict="conflicts_present";else verdict="all_disjoint";return{verdict,pairs,suggestedSerialOrder,unknownScopeTasks}}function formatEvidence(ev){let lines=[];for(let[pa,pb]of ev.evidence.pathPairs)lines.push(`path overlap: ${pa} ↔ ${pb}`);for(let cc of ev.evidence.cochangePairs)lines.push(`co-change: ${cc.a} ↔ ${cc.b} (npmi=${cc.npmi.toFixed(3)}, coChanges=${cc.coChangeCount})`);return lines}function topoSort(taskIds,adj,inDegree){let deg=new Map(inDegree),order=[],queue=[...taskIds.filter((id)=>(deg.get(id)??0)===0)];while(queue.length>0){let cur=queue.shift();order.push(cur);for(let next of adj.get(cur)??[])if(deg.set(next,(deg.get(next)??0)-1),(deg.get(next)??0)===0)queue.push(next);queue.sort((x,y)=>taskIds.indexOf(x)-taskIds.indexOf(y))}if(order.length<taskIds.length){for(let id of taskIds)if(!order.includes(id))order.push(id)}return order}function isProvablyDisjoint(directory,taskIds){return taskIds.length>=2&&computeParallelVerdict(directory,taskIds).verdict==="all_disjoint"}var DEFAULT_PARALLEL_COCHANGE_THRESHOLD,MAX_PARALLEL_VERDICT_TASKS=64;var init_parallel_verdict=__esm(()=>{init_scope_persistence();init_cochange_conflict();init_conflicts();DEFAULT_PARALLEL_COCHANGE_THRESHOLD={npmi:0.2,minCoChanges:3}});function generateCourseCorrection(match,trajectory){let alert=`TRAJECTORY ALERT: ${match.pattern} detected (severity: ${match.severity}) at steps ${match.stepRange[0]}-${match.stepRange[1]}`,guidance=GUIDANCE_TEMPLATES[match.pattern],action=ACTION_TEMPLATES[match.pattern](match,trajectory);return{alert,category:match.category,guidance,action,pattern:match.pattern,stepRange:match.stepRange}}function formatCourseCorrectionForInjection(correction){return`${correction.alert}
878
878
  CATEGORY: ${correction.category}
879
879
  GUIDANCE: ${correction.guidance}
880
880
  ACTION: ${correction.action}`}var GUIDANCE_TEMPLATES,ACTION_TEMPLATES;var init_course_correction=__esm(()=>{GUIDANCE_TEMPLATES={repetition_loop:"Agent is repeating the same action on the same target. Consider consolidating changes, stepping back to review the approach, or delegating to a different agent.",ping_pong:"Agents are delegating back and forth without making progress. Consider having the architect take direct control or redefining the task boundaries.",expansion_drift:"Scope is expanding beyond the original task. Consider creating a follow-up task, reducing the current scope, or updating the spec.",stuck_on_test:"Repeated edit-test cycles detected. Consider reviewing the test expectations, checking for environmental issues, or seeking SME consultation.",context_thrash:"Agent is requesting increasingly large file sets. Consider focusing on the specific files needed for the current task or compacting context."},ACTION_TEMPLATES={repetition_loop:(match)=>{let agents=match.affectedAgents.length>0?match.affectedAgents.join(", "):"current agent";return`Stop repetitive edits to ${match.affectedTargets.length>0?match.affectedTargets.join(", "):"current target"} by ${agents}. Take a step back and consolidate the changes made so far before proceeding.`},ping_pong:()=>{return"Interrupt the delegation cycle. Architect should take direct control of the task or explicitly redefine which agent owns which subtask."},expansion_drift:()=>{return"Freeze current scope. Document what's been attempted and create a follow-up issue for additional work. Complete current task before expanding further."},stuck_on_test:(match)=>{return`Pause edit-test cycle. ${match.affectedAgents.length>0?match.affectedAgents.join(", "):"the agent"} should review test expectations, verify environment is clean, and consult SME if root cause is unclear.`},context_thrash:(match)=>{return`Restrict file access to only ${match.affectedTargets.length>0?match.affectedTargets.slice(0,3).join(", "):"requested files"}. Use targeted file selection instead of broad context requests.`}}});function resolveLadderKey(match){return match.affectedTargets.length===1?`${match.pattern}|${match.affectedTargets[0]}`:match.pattern}function createDefaultEscalationState(){return{patternCounts:new Map,escalationLevel:0,lastPatternDetected:null,hardStopPending:!1}}function cloneEscalationState(state){return{patternCounts:new Map(state.patternCounts),escalationLevel:state.escalationLevel,lastPatternDetected:state.lastPatternDetected?{...state.lastPatternDetected,stepRange:[...state.lastPatternDetected.stepRange],affectedAgents:[...state.lastPatternDetected.affectedAgents],affectedTargets:[...state.lastPatternDetected.affectedTargets]}:null,hardStopPending:state.hardStopPending}}function generateCorrection(match,level){let levelPrefix=level===1?"GUIDANCE":level===2?"STRONG GUIDANCE":"HARD STOP",alertTemplates={repetition_loop:`${levelPrefix}: Repetitive action loop detected`,ping_pong:`${levelPrefix}: Delegation ping-pong detected`,expansion_drift:`${levelPrefix}: Scope expansion drift detected`,stuck_on_test:`${levelPrefix}: Stuck in edit-test cycle`,context_thrash:`${levelPrefix}: Excessive context requests detected`},guidanceTemplates={repetition_loop:"Stop the repetitive loop. Consolidate changes and take a different approach.",ping_pong:"Interrupt the delegation cycle. Architect should take direct control.",expansion_drift:"Freeze scope expansion. Complete current task before adding more work.",stuck_on_test:"Pause edit-test cycle. Review test expectations and verify environment.",context_thrash:"Restrict file access. Use targeted selection instead of broad context requests."},actionTemplates={repetition_loop:"Consolidate changes and change approach immediately.",ping_pong:"Architect take direct control or redefine agent task boundaries.",expansion_drift:"Document progress and create follow-up issue for additional work.",stuck_on_test:"Review test expectations, verify environment, consult SME if needed.",context_thrash:"Restrict to only the specific files needed for the current task."};return{alert:alertTemplates[match.pattern],category:match.category,guidance:guidanceTemplates[match.pattern],action:actionTemplates[match.pattern],pattern:match.pattern,stepRange:match.stepRange}}class EscalationTracker{_sessionId;_state;constructor(sessionId,initialState){this._sessionId=sessionId,this._state=initialState??createDefaultEscalationState()}recordDetection(match){let ladderKey=resolveLadderKey(match),newCount=(this._state.patternCounts.get(ladderKey)??0)+1;this._state.patternCounts.delete(ladderKey),this._state.patternCounts.set(ladderKey,newCount);while(this._state.patternCounts.size>MAX_TRACKED_LADDERS){let oldest=this._state.patternCounts.keys().next().value;if(oldest===void 0)break;this._state.patternCounts.delete(oldest)}if(this._state.lastPatternDetected=match,newCount===1){let correction=generateCorrection(match,1);return this._state.escalationLevel=1,{level:1,correction,hardStop:!1}}else if(newCount===2){let correction=generateCorrection(match,2);return this._state.escalationLevel=2,telemetry.prmEscalationTriggered(this._sessionId,match.pattern,2,newCount),{level:2,correction,hardStop:!1}}else{let correction=generateCorrection(match,3);return this._state.escalationLevel=3,this._state.hardStopPending=!0,telemetry.prmHardStop(this._sessionId,match.pattern,3,newCount),{level:3,correction,hardStop:!0}}}getState(){return cloneEscalationState(this._state)}getLadderCounts(){return new Map(this._state.patternCounts)}reset(){this._state=createDefaultEscalationState()}isHardStopPending(){return this._state.hardStopPending}}var MAX_TRACKED_LADDERS=256;var init_escalation=__esm(()=>{init_telemetry()});function sanitizeString2(input){if(!input||typeof input!=="string")return"";let result=input;result=result.replace(/[\n\r]/g,""),result=result.replace(/`/g,""),result=result.replace(/<[^>]*>/g,"");for(let pattern of INJECTION_PATTERNS2)result=result.replace(pattern,"[REDACTED]");if(result=result.trim(),result.length>200)result=`${result.slice(0,197)}...`;return result}function resolvePatternThreshold(config2,pattern){return config2.pattern_thresholds?.[pattern]??DEFAULT_THRESHOLDS[pattern]}function detectRepetitionLoop(trajectory,config2){let matches=[];if(trajectory.length<2)return matches;let windowSize=10,threshold=config2.pattern_thresholds?.repetition_loop??DEFAULT_THRESHOLDS.repetition_loop;for(let i=0;i<trajectory.length;i++){let windowStart=Math.max(0,i-windowSize+1),window2=trajectory.slice(windowStart,i+1),counts=new Map;for(let entry of window2){let key=`${entry.agent}|${entry.action}|${entry.target}`,existing=counts.get(key);if(existing)existing.count++,existing.endStep=entry.step;else counts.set(key,{count:1,startStep:entry.step,endStep:entry.step,agent:entry.agent,action:entry.action,target:entry.target})}for(let data of counts.values())if(data.count>=threshold){let{agent,action,target}=data,severity=data.count>=3?"high":"medium";matches.push({pattern:"repetition_loop",severity,category:"coordination_error",stepRange:[data.startStep,data.endStep],description:`Agent "${sanitizeString2(agent)}" performed "${sanitizeString2(action)}" on "${sanitizeString2(target)}" ${data.count} times within ${windowSize} steps`,affectedAgents:[sanitizeString2(agent)],affectedTargets:[sanitizeString2(target)],occurrenceCount:data.count})}}return matches}function detectPingPong(trajectory,config2){let matches=[],threshold=config2.pattern_thresholds?.ping_pong??DEFAULT_THRESHOLDS.ping_pong,minThreshold=3,effectiveThreshold=Math.max(threshold,3),delegateEntries=trajectory.filter((e)=>e.action==="delegate");if(delegateEntries.length<effectiveThreshold)return matches;let detectedPairs=new Set,i=0;while(i<delegateEntries.length){if(i+1>=delegateEntries.length)break;let firstAgent=delegateEntries[i].agent,secondAgent=delegateEntries[i+1].agent,target=delegateEntries[i].target;if(firstAgent===secondAgent){i++;continue}let endIndex=i+1;for(let j=i+2;j<delegateEntries.length;j++){let expectedAgent=(j-i)%2===0?firstAgent:secondAgent;if(delegateEntries[j].agent!==expectedAgent||delegateEntries[j].target!==target)break;endIndex=j}let patternLength=endIndex-i+1;if(patternLength>=effectiveThreshold){let pairKey=`${[firstAgent,secondAgent].sort().join(",")}-${target}`;if(!detectedPairs.has(pairKey)){detectedPairs.add(pairKey);let roundTrips=Math.floor(patternLength/2);matches.push({pattern:"ping_pong",severity:"high",category:"coordination_error",stepRange:[delegateEntries[i].step,delegateEntries[endIndex].step],description:`Ping-pong delegation detected: "${sanitizeString2(firstAgent)}" and "${sanitizeString2(secondAgent)}" alternating on "${sanitizeString2(target)}"`,affectedAgents:[sanitizeString2(firstAgent),sanitizeString2(secondAgent)],affectedTargets:[sanitizeString2(target)],occurrenceCount:roundTrips})}i=endIndex+1}else i++}return matches}function detectExpansionDrift(trajectory,config2){let matches=[],threshold=config2.pattern_thresholds?.expansion_drift??DEFAULT_THRESHOLDS.expansion_drift,windowSize=Math.max(threshold,5),minTrajectoryLength=windowSize*2;if(trajectory.length<minTrajectoryLength)return matches;for(let i=windowSize*2;i<=trajectory.length;i+=windowSize){let recentWindow=trajectory.slice(i-windowSize,i),previousWindow=trajectory.slice(i-windowSize*2,i-windowSize),recentTargets=new Set(recentWindow.map((e)=>e.target)),previousTargets=new Set(previousWindow.map((e)=>e.target));if(previousTargets.size>0){let expansionRatio=recentTargets.size/previousTargets.size;if(expansionRatio>1.5)matches.push({pattern:"expansion_drift",severity:"medium",category:"specification_error",stepRange:[previousWindow[0].step,recentWindow[recentWindow.length-1].step],description:`Scope expansion detected: ${previousTargets.size} unique targets → ${recentTargets.size} unique targets (${expansionRatio.toFixed(1)}x increase)`,affectedAgents:[...new Set(recentWindow.map((e)=>sanitizeString2(e.agent)))],affectedTargets:[...recentTargets].map((t)=>sanitizeString2(t)),occurrenceCount:Math.floor(expansionRatio*10)/10})}}return matches}function detectStuckOnTest(trajectory,config2){let matches=[];if(trajectory.length<3)return matches;let threshold=config2.pattern_thresholds?.stuck_on_test??DEFAULT_THRESHOLDS.stuck_on_test,fileCycles=new Map;for(let i=0;i<trajectory.length;i++){let entry=trajectory[i];if(entry.action==="edit"){let existing=fileCycles.get(entry.target);if(existing){if(existing.edits++,existing.steps.push(entry.step),!existing.agents.includes(entry.agent))existing.agents.push(entry.agent)}else fileCycles.set(entry.target,{edits:1,tests:0,steps:[entry.step],agents:[entry.agent]})}else if(entry.action==="test"){let existing=fileCycles.get(entry.target);if(existing)existing.tests++}}for(let[file2,data]of fileCycles)if(data.edits>=threshold&&data.tests>=1){let cycleCount=0,lastEditStep=-1,lastTestStep=-1,cycleStart=-1,cycleEnd=-1;for(let i=0;i<trajectory.length;i++){let entry=trajectory[i];if(entry.target===file2){if(entry.action==="edit"){if(lastTestStep>lastEditStep&&lastEditStep>0){if(cycleCount++,cycleStart===-1)cycleStart=lastEditStep;cycleEnd=entry.step}lastEditStep=entry.step}else if(entry.action==="test"&&entry.result==="failure")lastTestStep=entry.step}}if(cycleCount>=threshold)matches.push({pattern:"stuck_on_test",severity:"high",category:"reasoning_error",stepRange:[cycleStart,cycleEnd],description:`Stuck on test detected: ${cycleCount} edit-test cycles on "${sanitizeString2(file2)}"`,affectedAgents:data.agents.map((a)=>sanitizeString2(a)),affectedTargets:[sanitizeString2(file2)],occurrenceCount:cycleCount})}return matches}function detectContextThrash(trajectory,config2){let matches=[];if(trajectory.length<2)return matches;let threshold=config2.pattern_thresholds?.context_thrash??DEFAULT_THRESHOLDS.context_thrash,seenTargets=new Set,cumulativeCounts=[];for(let entry of trajectory)seenTargets.add(entry.target),cumulativeCounts.push(seenTargets.size);let runStart=0,runLength=1;for(let i=1;i<=cumulativeCounts.length;i++)if(i<cumulativeCounts.length&&cumulativeCounts[i]>cumulativeCounts[i-1])runLength++;else{if(runLength>=threshold){let runEnd=i-1,priorCount=runStart>0?cumulativeCounts[runStart-1]:0,finalCount=cumulativeCounts[runEnd];matches.push({pattern:"context_thrash",severity:"medium",category:"coordination_error",stepRange:[trajectory[runStart].step,trajectory[runEnd].step],description:`Context thrash detected: unique targets grew monotonically from ${priorCount} to ${finalCount} over ${runLength} steps`,affectedAgents:[...new Set(trajectory.slice(runStart,runEnd+1).map((e)=>sanitizeString2(e.agent)))],affectedTargets:[...new Set(trajectory.slice(runStart,runEnd+1).map((e)=>sanitizeString2(e.target)))],occurrenceCount:runLength})}runStart=i,runLength=1}return matches}function detectPatterns(trajectory,config2,lastProcessedStep=0){let startTime=Date.now();if(config2.enabled===!1)return{matches:[],detectionTimeMs:0,patternsChecked:5};let allMatches=[];allMatches.push(...detectRepetitionLoop(trajectory,config2)),allMatches.push(...detectPingPong(trajectory,config2)),allMatches.push(...detectExpansionDrift(trajectory,config2)),allMatches.push(...detectStuckOnTest(trajectory,config2)),allMatches.push(...detectContextThrash(trajectory,config2));let detectionTimeMs=Date.now()-startTime,severityRank={critical:4,high:3,medium:2,low:1},dedupedMatches=new Map;for(let match of allMatches){let key=`${match.pattern}-${match.affectedAgents.join(",")}-${match.affectedTargets.join(",")}-${match.stepRange[0]}`,existing=dedupedMatches.get(key);if(!existing){dedupedMatches.set(key,match);continue}let existingRank=severityRank[existing.severity]??0,newRank=severityRank[match.severity]??0;if(newRank>existingRank||newRank===existingRank&&match.stepRange[1]>existing.stepRange[1])dedupedMatches.set(key,match)}return{matches:Array.from(dedupedMatches.values()).filter((match)=>match.stepRange[1]>lastProcessedStep),detectionTimeMs,patternsChecked:5}}var INJECTION_PATTERNS2,DEFAULT_THRESHOLDS;var init_pattern_detector=__esm(()=>{INJECTION_PATTERNS2=[/\[SYSTEM\]/gi,/SYSTEM\s*OVERRIDE/gi,/IGNORE\s*PREVIOUS/gi,/IGNORE\s*ALL/gi,/NEW\s*INSTRUCTION/gi,/Override\s*instructions/gi,/\bJAILBREAK/gi,/\bDAN\s*MODE/gi,/\bBYPASS/gi];DEFAULT_THRESHOLDS={repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:10}});function canonicalProjectKey(directory){return canonicalRootKeyFresh(directory)}var defaultCanonicalRootRealpath,defaultCanonicalRootNativeRealpath;var init_canonical_project=__esm(()=>{init_canonical_root();defaultCanonicalRootRealpath=_internals6.realpathSync,defaultCanonicalRootNativeRealpath=_internals6.realpathSyncNative});function isClosedHandleError(err){let msg=(err instanceof Error?err.message:String(err)).toLowerCase();return msg.includes("database has closed")||msg.includes("database is closed")||msg.includes("cannot use a closed database")||msg.includes("database is not open")}class GroupCommitWriter{db;queue=[];flushing=!1;degraded=null;lastAdvisoryAt=0;closed=!1;registryKey=null;constructor(db){this.db=db}get queuedOpCount(){return this.queue.length}bindRegistryKey(key){this.registryKey=key}enqueue(op){if(this.closed)throw new DbWriteError("unknown","group-commit writer is closed");if(this.queue.length>=MAX_QUEUED_OPS)this.flushSync();if(this.queue.push(op),this.queue.length>=FLUSH_THRESHOLD_OPS)this.flushSync()}flushSync(){if(this.closed||this.flushing||this.queue.length===0)return;this.flushing=!0;let batch=this.queue;this.queue=[];try{try{this.applyBatch(batch)}catch(err){if(!isClosedHandleError(err)||this.registryKey===null)throw err;this.db=_internals51.getProjectDb(this.registryKey),this.applyBatch(batch)}}catch(err){let category=classifyDbWriteError(err);if(isClosedHandleError(err)){if(this.close(),this.registryKey!==null)_writers.delete(this.registryKey)}if(category==="busy"||category==="disk_full"||category==="read_only")this.queue=[...batch,...this.queue],this.noteDegraded(category);else this.noteDegraded(category);throw new DbWriteError(category,`swarm.db group-commit flush failed (${category}): ${err instanceof Error?err.message:String(err)}`)}finally{this.flushing=!1}}async flush(){this.flushSync()}close(){this.closed=!0,this.queue=[]}applyBatch(batch){let cls=batchDurabilityClass(batch.map((op)=>op.durability));applySynchronousForClass(this.db,cls);try{this.db.run("BEGIN IMMEDIATE")}catch(err){throw applySynchronousForClass(this.db,"normal"),err}try{for(let op of batch)op.run(this.db);this.db.run("COMMIT")}catch(err){try{this.db.run("ROLLBACK")}catch{}throw err}finally{applySynchronousForClass(this.db,"normal")}}noteDegraded(category){let now=Date.now();if(this.degraded={category,until:now+DEGRADED_COOLDOWN_MS},now-this.lastAdvisoryAt<DEGRADED_COOLDOWN_MS)return;this.lastAdvisoryAt=now,warn(`[swarm.db] durable-state writer degraded (category=${category}); queued writes retry on the next flush`)}get degradation(){if(!this.degraded)return null;if(Date.now()>this.degraded.until)return null;return this.degraded}}function getGroupCommitWriter(directory){let key=canonicalProjectKey(directory),writer=_writers.get(key);if(!writer)writer=new GroupCommitWriter(getProjectDb(directory)),writer.bindRegistryKey(key),_writers.set(key,writer);return writer}function closeGroupCommitWriter(directory){let key=canonicalProjectKey(directory),writer=_writers.get(key);if(writer){try{writer.flushSync()}catch{}writer.close(),_writers.delete(key)}}var MAX_QUEUED_OPS=1024,FLUSH_THRESHOLD_OPS=64,DEGRADED_COOLDOWN_MS=60000,_writers,_internals51;var init_group_commit_writer=__esm(()=>{init_logger();init_canonical_project();init_db_errors();init_durability();init_project_db();_writers=new Map,_internals51={getProjectDb,isClosedHandleError}});import{existsSync as existsSync31,readdirSync as readdirSync7,readFileSync as readFileSync21,renameSync as renameSync14,statSync as statSync19}from"node:fs";import{join as join42}from"node:path";function sleepSync3(ms){let shared=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(shared),0,0,ms)}function renameWithRetry4(from,to){let lastErr;for(let attempt=0;attempt<RENAME_RETRIES;attempt++)try{_internals52.renameSync(from,to);return}catch(err){lastErr=err;let code=err?.code;if(code!=="EPERM"&&code!=="EACCES"&&code!=="EBUSY")throw err;sleepSync3(RENAME_RETRY_DELAY_MS2)}throw lastErr}function warnStaleLegacyOnce(key,fileName){let guard=`${key}::${fileName}`;if(warnedStaleLegacy.has(guard))return;warnedStaleLegacy.add(guard),warn(`[swarm.db] legacy artifact ${fileName} is present but the target table is non-empty; leaving the file untouched (it is inert — readers use swarm.db)`)}function importLegacyJsonl(directory,opts){let root=canonicalProjectKey(directory),filePath=join42(root,".swarm",opts.fileName);if(!existsSync31(filePath))return{imported:0,skipped:0,archived:!1};let db=getProjectDb(directory),content;try{if(statSync19(filePath).size>_internals52.maxLegacyImportBytes())return warn(`[swarm.db] legacy artifact ${opts.fileName} exceeds the import size cap; leaving it inert (not imported, not renamed)`),{imported:0,skipped:0,archived:!1};content=readFileSync21(filePath,"utf-8")}catch{return{imported:0,skipped:0,archived:!1}}let payloads=[],skipped=0;for(let line of content.split(`
@@ -7442,7 +7442,7 @@ Regenerated on: save_plan and phase_complete.
7442
7442
  `)}function aggregateEvidence(cluster,phaseNumber){let refs=new Set;for(let p of cluster)for(let ref of p.evidenceRefs)refs.add(ref);let list=Array.from(refs).slice(0,19);return list.push(`consolidation:phase-${phaseNumber}`),list}async function runConsolidationPass(input,deps){let{phaseNumber,runId,config:config3}=input,consolidation=config3.consolidation,base={skipped:!0,phaseNumber,clusterCount:0,clustersDeferred:0,decisionsEmitted:0,added:0,superseded:0,contradictionsDetected:0,deduped:0,proposed:0,memoriesDecayed:0,errored:0};if(!config3.enabled||!consolidation.enabled||!deps.gateway.isEnabled())return{...base,skipReason:"disabled"};let priorLog=await deps.readLog();if(priorLog.some((r)=>r.phaseNumber===phaseNumber))return{...base,skipReason:"already_consolidated"};let processedBefore=new Set(priorLog.flatMap((r)=>r.processedProposalIds)),startedAt=deps.now().toISOString(),logKey=runId??"unknown";await deps.logEvent({event:"consolidation_started",runId:logKey,phaseNumber,timestamp:startedAt});let pendingProposals=(await deps.gateway.listProposals({status:"pending"})).filter((p)=>p.proposedBy?.agentRole!==CONSOLIDATION_AGENT_ROLE&&!processedBefore.has(p.id)).sort((a,b)=>a.id.localeCompare(b.id)),deadAnchorMemoryIds=deps.readDeadAnchorMemoryIds?.()??new Set,existingMemories=(await deps.gateway.listMemories({})).filter((memory)=>!deadAnchorMemoryIds.has(memory.id)),clusters=clusterByJaccard(pendingProposals,(p)=>p.proposedRecord?.text??p.rationale,consolidation.jaccardThreshold),processable=clusters.slice(0,consolidation.maxClustersPerPass),clustersDeferred=Math.max(0,clusters.length-processable.length);await deps.logEvent({event:"cluster_count",runId:logKey,phaseNumber,clusterCount:clusters.length});let result={...base,skipped:!1,clusterCount:clusters.length,clustersDeferred},processedProposalIds=new Set;if(!deps.llmDelegate){if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),{...result,skipReason:"no_llm_delegate_decay_only"}}let seenFactTexts=new Set;for(let cluster of processable){if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};for(let p of cluster)processedProposalIds.add(p.id);let raw;try{let prompt=buildDistillationPrompt(cluster,existingMemories);raw=await deps.llmDelegate("",prompt,deps.signal)}catch{result.errored++;continue}let facts=parseDistillationOutput(raw),evidenceRefs=aggregateEvidence(cluster,phaseNumber);for(let fact of facts){let normalized=fact.text.replace(/\s+/g," ").trim().toLowerCase();if(seenFactTexts.has(normalized))continue;seenFactTexts.add(normalized);let plan=deriveDecision(fact,existingMemories,{autoApplyMinConfidence:consolidation.autoApplyMinConfidence,jaccardThreshold:consolidation.jaccardThreshold});try{await executePlan(plan,evidenceRefs,input,deps,result)}catch{result.errored++}}}if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),result}async function executePlan(plan,evidenceRefs,input,deps,result){let{phaseNumber}=input;if(plan.type==="skip")return;if(plan.type==="dedup"){result.deduped++;return}let newRecord={kind:plan.fact.kind,text:plan.fact.text,confidence:plan.fact.confidence,stability:"durable",source:sourceForDistilled(evidenceRefs,phaseNumber),metadata:{consolidatedFromPhase:phaseNumber}},rationale=`consolidation phase ${phaseNumber}`;if(((plan.type==="add"||plan.type==="supersede")&&EVIDENCE_REQUIRED_KINDS.has(plan.fact.kind)&&!hasRealEvidence(evidenceRefs)?"proposal":plan.type)==="proposal"){await deps.gateway.propose({operation:plan.type==="supersede"?"supersede":"add",kind:plan.fact.kind,text:plan.fact.text,rationale:plan.type==="proposal"?`${rationale}: ${plan.reason}`:`${rationale}: evidence-required kind lacks real evidence source`,evidenceRefs,...plan.type==="supersede"?{targetMemoryId:plan.oldMemoryId}:{}}),result.proposed++;return}if(plan.type==="supersede"){let proposal2=await deps.gateway.propose({operation:"supersede",kind:plan.fact.kind,text:plan.fact.text,targetMemoryId:plan.oldMemoryId,rationale,evidenceRefs});if(proposal2.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"supersede",proposalId:proposal2.id,oldMemoryId:plan.oldMemoryId,replacement:newRecord,reason:`contradiction superseded during phase ${phaseNumber} consolidation`}),result.superseded++,result.contradictionsDetected++,result.decisionsEmitted++;return}let proposal=await deps.gateway.propose({operation:"add",kind:plan.fact.kind,text:plan.fact.text,rationale,evidenceRefs});if(proposal.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"add",proposalId:proposal.id,memory:newRecord}),result.added++,result.decisionsEmitted++}async function applyDecay(memories,input,deps){let decayed=0,halfLives=input.config.consolidation.decayHalfLifeDays,now2=deps.now();for(let memory of memories){if(deps.signal?.aborted)break;if(memory.metadata.deleted===!0||memory.supersededBy)continue;if(isPastDecayHorizon(memory,halfLives,now2))continue;let nextExpiry=computeDecayExpiry(memory,halfLives,now2);if(!nextExpiry)continue;try{await deps.gateway.upsertCurated({...memory,expiresAt:nextExpiry}),decayed++}catch{}}return decayed}async function finalize2(input,deps,result,startedAt,processedProposalIds){let{phaseNumber,runId}=input,logKey=runId??"unknown",completedAt=deps.now().toISOString();await deps.logEvent({event:"decisions_emitted",runId:logKey,phaseNumber,decisionsEmitted:result.decisionsEmitted}),await deps.logEvent({event:"contradictions_detected",runId:logKey,phaseNumber,contradictionsDetected:result.contradictionsDetected}),await deps.logEvent({event:"memories_decayed",runId:logKey,phaseNumber,memoriesDecayed:result.memoriesDecayed}),await deps.logEvent({event:"consolidation_completed",runId:logKey,phaseNumber,clusterCount:result.clusterCount,decisionsEmitted:result.decisionsEmitted,contradictionsDetected:result.contradictionsDetected,memoriesDecayed:result.memoriesDecayed,timestamp:completedAt}),await deps.appendLog({phaseNumber,runId,startedAt,completedAt,clusterCount:result.clusterCount,clustersDeferred:result.clustersDeferred,decisionsEmitted:result.decisionsEmitted,added:result.added,superseded:result.superseded,contradictionsDetected:result.contradictionsDetected,deduped:result.deduped,proposed:result.proposed,memoriesDecayed:result.memoriesDecayed,errored:result.errored,processedProposalIds:Array.from(processedProposalIds)})}init_consolidation_log();init_gateway();init_reflection_service();init_run_log();init_storage_root();init_canonical_root();var CONSOLIDATION_TIMEOUT_MS=300000,runningByDirectory2=new Map;async function runMemoryConsolidation(req){let key2=canonicalRootKeyFresh(req.directory),existing=runningByDirectory2.get(key2);if(existing)return existing;let run=(async()=>{if(!req.config.enabled||!req.config.consolidation.enabled)return{started:!1,reason:"disabled"};let gateway=createMemoryGateway({directory:req.directory,sessionID:req.sessionId,runId:req.sessionId,agentRole:"curator_consolidation"},{config:req.config}),controller=new AbortController,timer=setTimeout(()=>controller.abort(),CONSOLIDATION_TIMEOUT_MS);timer.unref?.();try{if(!gateway.isEnabled())return{started:!1,reason:"disabled"};let llmDelegate=createCuratorLLMDelegate(req.directory,"consolidation",req.sessionId),result=await runConsolidationPass({directory:req.directory,phaseNumber:req.phase,runId:req.sessionId,config:req.config},{gateway,llmDelegate,now:()=>new Date,logEvent:(event)=>appendMemoryRunLog(req.directory,req.sessionId,event),readLog:()=>readConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config)),appendLog:(record3)=>appendConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config),record3),readDeadAnchorMemoryIds:()=>readDeadAnchorMemoryIds(req.directory),signal:controller.signal});return{started:!result.skipped,reason:result.skipReason,result}}finally{clearTimeout(timer),await gateway.dispose()}})();runningByDirectory2.set(key2,run);try{return await run}finally{if(runningByDirectory2.get(key2)===run)runningByDirectory2.delete(key2)}}function runMemoryConsolidationFireAndForget(req,onComplete,onError){queueMicrotask(()=>{runMemoryConsolidation(req).then(onComplete).catch(onError)})}init_skill_consolidation();init_snapshot_writer();init_state2();init_telemetry();init_state();init_file_locks();import*as fs189 from"node:fs";import*as path316 from"node:path";init_state4();var DEFAULT_CONFIG4={phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!1};function defaultReadPlanJson(dir){try{let planPath=path316.join(dir,".swarm","plan.json");if(!fs189.existsSync(planPath))return null;let raw=fs189.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(typeof plan!=="object"||plan===null||!Array.isArray(plan.phases))return null;return plan}catch{return null}}function readReviewerEvidenceFromFile(directory,phase){try{let evidencePath=path316.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json");if(!fs189.existsSync(evidencePath))return null;let raw=fs189.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED")return null;return parsed}catch{return null}}function readCriticEvidenceFromFile(directory,phase){try{let evidencePath=path316.join(directory,".swarm","evidence",String(phase),"lean-turbo-critic.json");if(!fs189.existsSync(evidencePath))return null;let raw=fs189.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED"&&verdict!=="ESCALATE_TO_HUMAN")return null;return parsed}catch{return null}}function listLaneEvidenceSync(directory,phase){let evidenceDir=path316.join(directory,".swarm","evidence",String(phase),"lean-turbo"),entries2;try{entries2=fs189.readdirSync(evidenceDir)}catch{return[]}entries2.sort();let laneIds=[];for(let entry of entries2){if(!entry.endsWith(".json")||entry==="lean-turbo-phase.json")continue;laneIds.push(entry.slice(0,-5))}return laneIds}var _internals267={listActiveLocks,readPersisted:readPersisted3,readPlanJson:defaultReadPlanJson,readReviewerEvidence:readReviewerEvidenceFromFile,readCriticEvidence:readCriticEvidenceFromFile,listLaneEvidence,listLaneEvidenceSync,verifyLeanTurboPhaseReady};function validatePersistedShape3(persisted){if(typeof persisted!=="object"||persisted===null)return!1;if(Array.isArray(persisted))return!1;if(typeof persisted.sessions!=="object")return!1;if(persisted.sessions===null)return!1;if(Array.isArray(persisted.sessions))return!1;return!0}function validateLanesArray(lanes){if(!Array.isArray(lanes))return!1;for(let lane of lanes){if(typeof lane!=="object"||lane===null)return!1;if(typeof lane.laneId!=="string")return!1;if(typeof lane.status!=="string")return!1}return!0}function validateDegradedTasksArray(degradedTasks){if(!Array.isArray(degradedTasks))return!1;for(let dt of degradedTasks){if(typeof dt!=="object"||dt===null)return!1;if(typeof dt.taskId!=="string")return!1}return!0}function verifyLeanTurboPhaseReady(directory,phase,sessionIDOrConfig,config3){let sessionID=typeof sessionIDOrConfig==="string"?sessionIDOrConfig:void 0,mergedConfig={...DEFAULT_CONFIG4,...typeof sessionIDOrConfig==="object"&&sessionIDOrConfig!==null?sessionIDOrConfig:config3??DEFAULT_CONFIG4},statePath2=path316.join(directory,".swarm","turbo-state.json");if(!fs189.existsSync(statePath2))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let persisted=_internals267.readPersisted(directory);if(!persisted)return{ok:!1,reason:"Lean Turbo state unreadable or missing"};if(!validatePersistedShape3(persisted))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let runState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){runState=sessionState;break}if(!runState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){runState=sessionState;break}}if(!runState)return{ok:!1,reason:sessionID?`No active Lean Turbo session for phase ${phase} and session ${sessionID}`:`No active Lean Turbo session for phase ${phase}`};if(!validateLanesArray(runState.lanes))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(!validateDegradedTasksArray(runState.degradedTasks))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(runState.lanes.length===0&&(!Array.isArray(runState.serializedTasks)||runState.serializedTasks.length===0)&&(!Array.isArray(runState.degradedTasks)||runState.degradedTasks.length===0))return{ok:!1,reason:`No lane plan or fallback tasks found for phase ${phase}`};let laneIds=runState.lanes.map((l)=>l.laneId);if(runState.lanes.length>0){for(let lane of runState.lanes)if(lane.status!=="completed"&&lane.status!=="failed")return{ok:!1,reason:`Lane ${lane.laneId} is not completed (status: ${lane.status})`}}if(runState.lanes.length>0){let evidenceLaneIds=new Set(_internals267.listLaneEvidenceSync(directory,phase));for(let lane of runState.lanes)if((lane.status==="completed"||lane.status==="failed")&&!evidenceLaneIds.has(lane.laneId))return{ok:!1,reason:`Lane ${lane.laneId} is ${lane.status} but lane evidence file is missing`}}let activeLocks=_internals267.listActiveLocks(directory),phaseLaneIds=new Set(laneIds);for(let lock of activeLocks)if(lock.laneId&&phaseLaneIds.has(lock.laneId))return{ok:!1,reason:`Active locks remain for lane ${lock.laneId}`};let laneTaskIds=new Set;for(let lane of runState.lanes)if(Array.isArray(lane.taskIds))for(let taskId of lane.taskIds)laneTaskIds.add(taskId);let serialDegradedTasks=runState.degradedTasks.filter((dt)=>!laneTaskIds.has(dt.taskId));if(serialDegradedTasks.length>0){let plan=_internals267.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify degraded task status: plan.json unreadable or malformed"};for(let dt of serialDegradedTasks){if(!Array.isArray(plan.phases))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phases is not an array)`};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phase ${phase} tasks is not an array)`};let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===dt.taskId);if(!task2)return{ok:!1,reason:`Degraded task ${dt.taskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Degraded task ${dt.taskId} not yet completed via standard flow`}}}let serializedTasks=runState.serializedTasks;if(Array.isArray(serializedTasks)&&serializedTasks.length>0){let plan=_internals267.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify serialized task status: plan.json unreadable or malformed"};if(!Array.isArray(plan.phases))return{ok:!1,reason:"Cannot verify serialized tasks: plan.json malformed (phases is not an array)"};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify serialized tasks: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify serialized tasks: plan.json malformed (phase ${phase} tasks is not an array)`};for(let serTaskId of serializedTasks){let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===serTaskId);if(!task2)return{ok:!1,reason:`Serialized task ${serTaskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Serialized task ${serTaskId} not yet completed (status: ${task2.status})`}}}if(mergedConfig.integrated_diff_required){let evidencePath=path316.join(directory,".swarm","evidence",String(phase),"lean-turbo","lean-turbo-phase.json"),hasDiff=!1;try{let content=fs189.readFileSync(evidencePath,"utf-8");hasDiff=!!JSON.parse(content).integratedDiffSummary}catch{}if(!hasDiff)return{ok:!1,reason:`Integrated diff summary is required but missing for phase ${phase}`}}let reviewerVerdict=runState.lastReviewerVerdict;if(!reviewerVerdict)reviewerVerdict=_internals267.readReviewerEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_reviewer){if(reviewerVerdict!=="APPROVED")return{ok:!1,reason:"Integrated reviewer approval missing or rejected"}}let criticVerdict=runState.lastCriticVerdict;if(!criticVerdict)criticVerdict=_internals267.readCriticEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_critic){if(criticVerdict!=="APPROVED")return{ok:!1,reason:"Integrated critic approval missing or rejected"}}return{ok:!0,reason:`Phase ${phase} is ready to advance`,evidence:{lanes:laneIds,degradedTasks:runState.degradedTasks.map((dt)=>dt.taskId),reviewerVerdict:reviewerVerdict??runState.lastReviewerVerdict,criticVerdict:criticVerdict??runState.lastCriticVerdict}}}init_logger();init_create_tool();function resolveCouncilFreshnessMaxAgeMs(config3){let hours=config3?.freshnessMaxAgeHours??24;if(!Number.isFinite(hours)||hours<1)return 86400000;return Math.min(hours,720)*60*60*1000}function evaluateCouncilFreshness(input){if(input.timestampMs===null||!Number.isFinite(input.timestampMs))return{ok:!1,reason:"invalid_timestamp",message:"evidence has a missing or invalid timestamp",recovery:"Re-run the council to generate fresh, timestamped evidence."};if(input.timestampMs>input.nowMs)return{ok:!1,reason:"future_timestamp",message:"evidence timestamp is in the future",recovery:"Re-run the council after the host clock is correct, then resubmit."};if(input.nowMs-input.timestampMs>input.maxAgeMs)return{ok:!1,reason:"stale_evidence",message:`evidence is older than the configured freshness window (${Math.round(input.maxAgeMs/3600000)} hours)`,recovery:"Re-run the council for fresh review."};if(input.mustPostdateMs!==void 0&&input.mustPostdateMs!==null&&Number.isFinite(input.mustPostdateMs)){if(input.mustPostdateMs>input.nowMs)return{ok:!1,reason:"invalid_required_input",message:"a later required input (e.g. the phase retrospective) is timestamped in the future — host clock skew suspected",recovery:"Correct the host clock / fix the skewed timestamp, then re-run the council."};if(input.timestampMs<input.mustPostdateMs)return{ok:!1,reason:"predates_required_input",message:"evidence predates a later required input (e.g. the phase retrospective)",recovery:"Re-run the council after the latest required evidence is available."}}return{ok:!0,message:"evidence is fresh",recovery:""}}function parseTimestampMs(value){if(typeof value!=="string")return null;let parsed=new Date(value).getTime();return Number.isNaN(parsed)?null:parsed}function latestRetroTimestampMsFromBundle(bundle,phase){if(!bundle||typeof bundle!=="object")return null;let raw=bundle,entries2=Array.isArray(raw.entries)?raw.entries:[],timestamps=[parseTimestampMs(raw.created_at),parseTimestampMs(raw.updated_at),...entries2.filter((entry)=>typeof entry==="object"&&entry!==null).filter((entry)=>entry.type==="retrospective"&&entry.phase_number===phase).map((entry)=>parseTimestampMs(entry.timestamp))].filter((timestamp)=>timestamp!==null);return timestamps.length>0?Math.max(...timestamps):null}init_store5();async function runArchitectureSupervisorGate(ctx){let{phase,dir,pluginConfig,agentsDispatched,safeWarn}=ctx,asConfig=pluginConfig.architectural_supervision,summarizeFindings=(findings)=>{if(!Array.isArray(findings)||findings.length===0)return"";let details=findings.map((f)=>f&&typeof f==="object"&&typeof f.description==="string"?f.description:void 0).filter((d)=>Boolean(d));return details.length>0?`
7443
7443
  Findings: ${details.join("; ")}`:""},asBlocked=(reason,message)=>({blocked:!0,reason,message,agentsDispatched,agentsMissing:[],warnings:[]}),asEntry=null;try{asEntry=readSupervisorReportRaw(dir,phase)}catch(asError2){return asBlocked("ARCH_SUPERVISOR_ERROR",`Phase ${phase} cannot be completed: architecture supervisor gate encountered an error. Error: ${String(asError2)}`)}if(!asEntry)return asBlocked("ARCH_SUPERVISOR_REQUIRED",`Phase ${phase} cannot be completed: architectural_supervision gate mode is enabled and no architecture supervisor evidence was found at .swarm/evidence/${phase}/architecture-supervisor.json. Dispatch critic_architecture_supervisor with the phase + agent summaries, then call write_architecture_supervisor_evidence.`);let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:asEntry.timestamp?new Date(asEntry.timestamp).getTime():null,maxAgeMs:resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council)});if(!freshness.ok)return asBlocked({invalid_timestamp:"ARCH_SUPERVISOR_INVALID_TIMESTAMP",future_timestamp:"ARCH_SUPERVISOR_FUTURE_TIMESTAMP",stale_evidence:"ARCH_SUPERVISOR_STALE_EVIDENCE",predates_required_input:"ARCH_SUPERVISOR_STALE_EVIDENCE",invalid_required_input:"ARCH_SUPERVISOR_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"ARCH_SUPERVISOR_STALE_EVIDENCE",`Phase ${phase} cannot be completed: architecture supervisor ${freshness.message}. ${freshness.recovery}`);if(typeof asEntry.phase_number!=="number"||asEntry.phase_number!==phase)return asBlocked("ARCH_SUPERVISOR_PHASE_MISMATCH",`Phase ${phase} cannot be completed: architecture supervisor evidence is for phase ${String(asEntry.phase_number)}, not phase ${phase}.`);let gateWarnings=[];if(asConfig?.provenance_verify===!0){let provenance=asEntry.provenance;if(!provenance||!provenance.agent_name&&!provenance.session_id)return asBlocked("ARCH_SUPERVISOR_MISSING_PROVENANCE",`Phase ${phase} cannot be completed: architecture supervisor evidence lacks provenance (agent_name or session_id). Evidence provenance verification is enabled.`)}else if(!asEntry.provenance||!asEntry.provenance.agent_name&&!asEntry.provenance.session_id){let msg=`Architecture supervisor evidence lacks provenance for phase ${phase}. Enable 'provenance_verify' in architectural_supervision config to enforce provenance verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}let asVerdict=asEntry.verdict;if(asVerdict==="REJECT")return asBlocked("ARCH_SUPERVISOR_REJECTED",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'REJECT'. Address the system-level findings before completing the phase.${summarizeFindings(asEntry.findings)}`);if(asVerdict==="CONCERNS"){if(asConfig?.allow_concerns_to_complete===!1)return asBlocked("ARCH_SUPERVISOR_CONCERNS",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'CONCERNS' and allow_concerns_to_complete is disabled.${summarizeFindings(asEntry.findings)}`);safeWarn(`[phase_complete] Architecture supervisor returned CONCERNS for phase ${phase} — proceeding (allow_concerns_to_complete is enabled)`,void 0)}else if(asVerdict!=="APPROVE")return asBlocked("ARCH_SUPERVISOR_INVALID",`Phase ${phase} cannot be completed: architecture supervisor evidence contains unrecognized verdict '${String(asVerdict)}'. Expected one of: APPROVE, CONCERNS, REJECT.`);return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}async function runCompletionVerifyGate(ctx){let{phase,dir,agentsDispatched}=ctx;try{let completionResultRaw=await executeCompletionVerify({phase,writeEvidence:!1},dir),completionResult=JSON.parse(completionResultRaw);if(completionResult.status==="blocked")return{blocked:!0,reason:"COMPLETION_INCOMPLETE",message:`Phase ${phase} cannot be completed: ${completionResult.reason}`,agentsDispatched,agentsMissing:[],warnings:completionResult.blockedTasks?[`Blocked tasks: ${completionResult.blockedTasks.map((t)=>t.task_id).join(", ")}`]:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}catch(completionError){return{blocked:!0,reason:"COMPLETION_VERIFY_ERROR",message:`Phase ${phase} cannot be completed: completion verify gate encountered an error. Error: ${String(completionError)}`,agentsDispatched,agentsMissing:[],warnings:[`COMPLETION_VERIFY_ERROR: ${String(completionError)}`]}}}init_effective_spec();import*as fs190 from"node:fs";import*as path317 from"node:path";init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_state2();async function resolveGatePreamble(dir,sessionID){let plan=await loadPlan(dir);if(!plan)return{resolved:!1};let planId=derivePlanId(plan),planHash=computePlanLedgerHash(plan),lookup=getProfileLookupForIdentity(dir,plan),overrides2=(sessionID?swarmState.agentSessions.get(sessionID):void 0)?.qaGateSessionOverrides??{};if(lookup.kind==="missing"){let hasOverrides=Object.keys(overrides2).length>0;return{resolved:hasOverrides,plan,planId,planHash,effectiveGates:hasOverrides?{...DEFAULT_QA_GATES,...overrides2}:void 0,identityBound:!0}}let profile=lookup.profile,effective=getEffectiveGates(profile,overrides2);return{resolved:!0,plan,planId,planHash,effectiveGates:effective,identityBound:lookup.kind==="bound"}}async function runDriftGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,gateWarnings=[],driftCheckEnabled=!0,driftHasEffectiveSpec=!1;try{driftHasEffectiveSpec=readEffectiveSpecSync(dir)!==null;let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved){if(preamble.identityBound===!1&&preamble.effectiveGates?.drift_check===!0)return{blocked:!0,reason:"DRIFT_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: drift_check is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};driftCheckEnabled=preamble.effectiveGates?.drift_check===!0}}catch(gateLoadError){safeWarn("[phase_complete] QA gate profile load error, drift_check defaults to enabled:",gateLoadError)}if(!driftCheckEnabled)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`drift_check gate is disabled. Drift verification was skipped for phase ${phase}.`]};let phaseType;try{let planPath=path317.join(dir,".swarm","plan.json");if(fs190.existsSync(planPath)){let planRaw=fs190.readFileSync(planPath,"utf-8");phaseType=JSON.parse(planRaw).phases?.find((p)=>p.id===phase)?.type}}catch{}if(phaseType==="non-code")return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`Phase ${phase} is annotated as 'non-code'. Drift verification was skipped per phase type annotation.`]};try{let driftEvidencePath=path317.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs190.readFileSync(driftEvidencePath,"utf-8"),entries2=JSON.parse(driftEvidenceContent).entries??[];for(let entry of entries2)if(typeof entry.type==="string"&&entry.type.includes("drift")&&typeof entry.verdict==="string"){if(driftVerdictFound=!0,!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Drift verification evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="approved")driftVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier returned verdict '${entry.verdict}'. Address the drift issues before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readError){if(readError.code!=="ENOENT")safeWarn("[phase_complete] Drift verifier evidence unreadable:",readError);driftVerdictFound=!1}if(!driftVerdictFound)if(!driftHasEffectiveSpec){let incompleteTaskCount=0,planParseable=!1;try{let planPath=path317.join(dir,".swarm","plan.json");if(fs190.existsSync(planPath)){let planRaw=fs190.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);planParseable=!0;let planPhase=plan.phases?.find((p)=>p.id===phase);if(planPhase?.tasks)incompleteTaskCount=planPhase.tasks.filter((t)=>t.status!=="completed"&&t.status!=="closed").length}}catch{}if(!planParseable)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:["No effective spec found and drift verification evidence missing — consider running critic_drift_verifier before phase completion."]};else if(incompleteTaskCount>0)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found and drift verification evidence missing. Phase ${phase} has ${incompleteTaskCount} incomplete task(s) in plan.json — consider running critic_drift_verifier before phase completion.`]};else return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found. Phase ${phase} tasks are all completed in plan.json. Drift verification was skipped.`]}}else return{blocked:!0,reason:"DRIFT_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: drift_check is enabled and drift verifier evidence not found at .swarm/evidence/${phase}/drift-verifier.json. Run drift verification before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!driftVerdictApproved&&driftVerdictFound)return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}catch(driftError){return{blocked:!0,reason:"DRIFT_VERIFICATION_ERROR",message:`Phase ${phase} cannot be completed: drift verification encountered an error: ${driftError instanceof Error?driftError.message:String(driftError)}. This is a hard block — resolve the error before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}import*as fs191 from"node:fs";import*as path318 from"node:path";init_council_review_identity();init_types();init_qa_gate_profile();init_utils3();init_state2();function readLatestRetroTimestampMs(dir,phase){let baseDir=path318.normalize(path318.resolve(dir,".swarm")),retroPath=path318.normalize(path318.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path318.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path318.sep)||retroPath===baseDir))return null;try{let content=fs191.readFileSync(retroPath,"utf-8");return latestRetroTimestampMsFromBundle(JSON.parse(content),phase)}catch{return null}}function sessionHasEnabledFinalCouncil(sessionID){if(!sessionID)return!1;return swarmState.agentSessions.get(sessionID)?.qaGateSessionOverrides?.final_council===!0}async function runFinalCouncilGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,finalCouncilEnabled=!1,gateWarnings=[];try{let preamble=await resolveGatePreamble(dir,sessionID);if(!preamble.resolved||!preamble.plan){if(hasAnyProfileWithEnabledGate(dir,"final_council")||sessionHasEnabledFinalCouncil(sessionID))return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_REQUIRED",message:`Phase ${phase} cannot be completed: final_council is enabled but plan.json is missing or invalid, so the final council gate cannot verify the current plan identity. Restore a valid .swarm/plan.json and re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};let warning="Final council gate: plan.json is missing and no enabled final_council profile was found. If final_council is required, the gate cannot be verified.";return gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[warning]}}if(preamble.resolved&&preamble.plan){let lastPhaseId=preamble.plan.phases[preamble.plan.phases.length-1]?.id;if(lastPhaseId!==void 0&&phase===lastPhaseId){if(preamble.effectiveGates?.final_council===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"FINAL_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the project")}`,agentsDispatched,agentsMissing:[],warnings:[]};finalCouncilEnabled=!0;let fcPath=path318.join(dir,".swarm","evidence","final-council.json"),fcVerdictFound=!1,_fcVerdict,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan:preamble.plan,config:ctx.pluginConfig.council}),completionPolicy=resolveFinalCompletionPolicy(ctx.pluginConfig.council),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council);try{let fcContent=fs191.readFileSync(fcPath,"utf-8"),fcBundle=JSON.parse(fcContent);for(let entry of fcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="final-council"&&typeof entry.verdict==="string"){fcVerdictFound=!0,_fcVerdict=entry.verdict;let fcTimeMs=parseTimestampMs(entry.timestamp),latestRetroTimestampMs=latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs(dir,phase),freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:fcTimeMs,maxAgeMs,mustPostdateMs:latestRetroTimestampMs});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"FINAL_COUNCIL_TIMESTAMP_REQUIRED",future_timestamp:"FINAL_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"FINAL_COUNCIL_STALE_EVIDENCE",predates_required_input:"FINAL_COUNCIL_STALE_EVIDENCE",invalid_required_input:"FINAL_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(preamble.plan){let currentPlanId=preamble.planId;if(entry.plan_id&&entry.plan_id!==currentPlanId)return{blocked:!0,reason:"final_council_plan_mismatch",message:`Final council evidence belongs to a different plan (evidence: ${entry.plan_id}, current: ${currentPlanId}). Re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.plan_id)return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_ID_REQUIRED",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing plan_id binding. Re-run the final council to generate evidence with plan identity.`,agentsDispatched,agentsMissing:[],warnings:[]};let currentIdentityHash=derivePlanIdentityHash(preamble.plan);if(entry.plan_identity_hash!==currentIdentityHash)return{blocked:!0,reason:entry.plan_identity_hash?"FINAL_COUNCIL_PLAN_IDENTITY_MISMATCH":"FINAL_COUNCIL_PLAN_IDENTITY_REQUIRED",message:entry.plan_identity_hash?`Phase ${phase} cannot be completed: final council evidence belongs to a different raw plan identity. Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_identity_hash binding. Re-run the final council to generate collision-resistant plan identity evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"FINAL_COUNCIL_IDENTITY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:entry.identity_version?`Phase ${phase} cannot be completed: final council evidence was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION}). Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence predates the council review identity cutover and carries no identity proof. Re-run the final council to generate identity-bound evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:entry.review_hash?"FINAL_COUNCIL_STALE_REVIEW_IDENTITY":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence does not match the current council review identity (review-relevant plan content or council policy changed since the review). Re-run the final council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"FINAL_COUNCIL_POLICY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence was produced under a different council policy. Re-run the final council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]}}let requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:COUNCIL_MEMBER_ROLES.length,rawMembersVoted=Array.isArray(entry.membersVoted)?entry.membersVoted.filter((member)=>typeof member==="string"):[],distinctCanonicalVoted=new Set(rawMembersVoted.map((member)=>resolveCouncilMemberRole(member)).filter((role)=>Boolean(role))),membersAbsent=COUNCIL_MEMBER_ROLES.filter((role)=>!distinctCanonicalVoted.has(role)),strictAllMembersPresent=distinctCanonicalVoted.size===COUNCIL_MEMBER_ROLES.length,quorumSatisfied=completionPolicy.mode==="quorum"?distinctCanonicalVoted.size>=requiredMembers:strictAllMembersPresent&&membersAbsent.length===0;if(typeof entry.quorumSize!=="number"||!Number.isFinite(entry.quorumSize)||entry.quorumSize<requiredMembers||!quorumSatisfied)return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence does not prove the required quorum (policy ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}; recorded quorumSize: ${typeof entry.quorumSize==="number"?entry.quorumSize:"missing"}; distinct canonical members: ${distinctCanonicalVoted.size} of ${requiredMembers} required; absent: [${membersAbsent.join(", ")}]). Re-run the project-scoped final council and call write_final_council_evidence to generate quorumed evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="rejected"||entry.verdict==="REJECTED")return{blocked:!0,reason:"FINAL_COUNCIL_REJECTED",message:`Phase ${phase} (last phase) cannot be completed: final council returned verdict 'REJECTED'. Address the required fixes before completing the project.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="concerns"||entry.verdict==="CONCERNS"){let advisoryNotes=Array.isArray(entry.advisoryNotes)?entry.advisoryNotes.filter((note)=>typeof note==="string"):[],warning=advisoryNotes.length>0?`Final council returned CONCERNS (non-blocking): ${advisoryNotes.join("; ")}`:"Final council returned CONCERNS (non-blocking).";gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0)}if(entry.verdict!=="approved"&&entry.verdict!=="APPROVED"&&entry.verdict!=="concerns"&&entry.verdict!=="CONCERNS")return{blocked:!0,reason:"FINAL_COUNCIL_INVALID_VERDICT",message:`Phase ${phase} (last phase) cannot be completed: final council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: approved, concerns, rejected.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Final council evidence unreadable:",readErr);fcVerdictFound=!1}if(!fcVerdictFound)return{blocked:!0,reason:"FINAL_COUNCIL_REQUIRED",final_council_required:!0,message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled and final council evidence not found at .swarm/evidence/final-council.json. Dispatch critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collect their CouncilMemberVerdict JSON, and call write_final_council_evidence before completing the project. Do not use convene_general_council for this gate.`,agentsDispatched,agentsMissing:[],warnings:["Final council required - dispatch the project-scoped council members, then call write_final_council_evidence to persist quorumed evidence."]}}}}}catch(fcError){if(finalCouncilEnabled)return{blocked:!0,reason:"FINAL_COUNCIL_ERROR",message:`Phase ${phase} (last phase) cannot be completed: final council gate encountered an error. Error: ${String(fcError)}`,agentsDispatched,agentsMissing:[],warnings:[`FINAL_COUNCIL_ERROR: ${String(fcError)}`]};else safeWarn("[phase_complete] Final council gate error (non-blocking):",fcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_schema();init_manager();init_diff_source();init_evidence2();function pass(ctx,warnings=[]){return{blocked:!1,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings}}function block(ctx,reason,message,recovery={kind:"tool",action:"run_phase_review",args:{phase:ctx.phase,sessionID:ctx.sessionID}}){return{blocked:!0,reason,message,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings:[],recovery}}function evidenceStatusMatchesScope(evidenceStatus,scopeStatus){return scopeStatus==="clean"?evidenceStatus==="clean":evidenceStatus==="completed"}async function runFinalReviewGate(ctx){let config3;try{config3=resolveAutoReviewConfig(ctx.pluginConfig.auto_review??{})}catch(error93){return block(ctx,"FINAL_REVIEW_CONFIG_INVALID",`Phase ${ctx.phase} cannot be completed: ${error93 instanceof Error?error93.message:String(error93)}`,{kind:"tool",action:"swarm_command",args:{command:"doctor",args:["config"]}})}let finalPlanPhase=(await loadPlanJsonOnly(ctx.dir).catch(()=>null))?.phases.at(-1)?.id===ctx.phase,allowedTriggers=new Set;if(config3.final_review.on_phase_complete)allowedTriggers.add("phase_completion");if(finalPlanPhase&&config3.final_review.on_plan_complete)allowedTriggers.add("plan_completion");if(!config3.enabled||config3.final_review.mode!=="gate"||config3.trigger==="task_completion"||allowedTriggers.size===0)return pass(ctx);let evidence2=readAutoReviewEvidenceForPhase(ctx.dir,ctx.phase);if(!evidence2)return block(ctx,"FINAL_REVIEW_EVIDENCE_MISSING",`Phase ${ctx.phase} cannot be completed: .swarm/evidence/${ctx.phase}/auto-review.json is missing or malformed.`);if(evidence2.schema_version!==2||!evidence2.scope.manifest)return block(ctx,"FINAL_REVIEW_LEGACY_RERUN",`Phase ${ctx.phase} cannot be completed: final review evidence uses the legacy schema and must be rerun with run_phase_review before completion.`);if(evidence2.phase!==ctx.phase||!allowedTriggers.has(evidence2.trigger))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence does not match the current review scope.`);let currentScope=await _internals268.collectReviewDiff({directory:ctx.dir,maxBytes:config3.final_review.max_diff_bytes});if(currentScope.status==="error")return block(ctx,"FINAL_REVIEW_SCOPE_COLLECTION_FAILED",`Phase ${ctx.phase} cannot be completed: terminal final-review scope collection failed (${currentScope.reason}).`);let currentManifest=await materializeAutoReviewManifest(ctx.dir,currentScope.manifest,config3);if(currentManifest.hash!==evidence2.scope.manifest.hash||JSON.stringify(currentScope.selector)!==JSON.stringify(evidence2.scope.selector)||JSON.stringify(currentScope.completeness)!==JSON.stringify(evidence2.scope.completeness)||!evidenceStatusMatchesScope(evidence2.review.status,currentScope.status))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: repository scope, plan requirements, or review policy changed after final review evidence was produced.`);if(evidence2.policy.mode!==config3.final_review.mode||evidence2.policy.min_confidence!==config3.min_confidence||evidence2.policy.structured_findings!==config3.structured_findings||evidence2.policy.validate_findings!==config3.validate_findings||evidence2.policy.digest!==currentManifest.review_policy_digest)return block(ctx,"FINAL_REVIEW_POLICY_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence was produced under a different policy.`);let integrity=validateAutoReviewEvidenceIntegrity(ctx.dir,evidence2,{scopeHash:evidence2.scope.hash,phase:ctx.phase,trigger:evidence2.trigger,policy:{mode:evidence2.policy.mode,min_confidence:evidence2.policy.min_confidence,structured_findings:evidence2.policy.structured_findings,validate_findings:evidence2.policy.validate_findings},scopeContent:currentScope.canonicalText});if(!integrity.ok)return block(ctx,integrity.code==="receipt_missing"?"FINAL_REVIEW_RECEIPT_MISSING":"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: final review evidence integrity check failed (${integrity.reason}).`);if(evidence2.review.status==="error")return block(ctx,"FINAL_REVIEW_FAILED",`Phase ${ctx.phase} cannot be completed: final review dispatch or parsing failed.`);if(!evidence2.scope.completeness.complete)return block(ctx,"FINAL_REVIEW_SCOPE_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: final review scope was truncated or incomplete.`);if(evidence2.review.status==="completed"&&evidence2.review.output_mode!=="structured")return block(ctx,"FINAL_REVIEW_STRUCTURED_EVIDENCE_REQUIRED",`Phase ${ctx.phase} cannot be completed: gate mode requires structured review evidence.`);if(!evidence2.validation_complete)return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: independent finding validation evidence is incomplete.`);let gateCandidates=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical"));if(gateCandidates.some((finding)=>!finding.validation||finding.validation.finding_id!==finding.finding_id))return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: gate-eligible findings lack exact-ID validation evidence.`);let confirmedIds=gateCandidates.filter((finding)=>finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(confirmedIds.length!==recordedBlockingIds.length||confirmedIds.some((id,index)=>id!==recordedBlockingIds[index]))return block(ctx,"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: blocking finding IDs do not match independently confirmed findings.`);if(evidence2.blocking_finding_ids.length>0)return block(ctx,"FINAL_REVIEW_CONFIRMED_FINDINGS",`Phase ${ctx.phase} cannot be completed: ${evidence2.blocking_finding_ids.length} anchored HIGH/CRITICAL finding(s) were independently CONFIRMED.`);return pass(ctx)}var _internals268={collectReviewDiff};import*as fs192 from"node:fs";import*as path319 from"node:path";async function runHallucinationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,hallucinationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.hallucination_guard===!0){if(hallucinationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let hgPath=path319.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs192.readFileSync(hgPath,"utf-8"),hgBundle=JSON.parse(hgContent);for(let entry of hgBundle.entries??[])if(typeof entry.type==="string"&&entry.type.includes("hallucination")&&typeof entry.verdict==="string"){if(hgVerdictFound=!0,entry.verdict==="approved")hgVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier returned verdict '${entry.verdict}'. Remove fabricated APIs/signatures and fix broken citations before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Hallucination guard evidence unreadable:",readErr);hgVerdictFound=!1}if(!hgVerdictFound)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled and evidence not found at .swarm/evidence/${phase}/hallucination-guard.json. Delegate to critic_hallucination_verifier and call write_hallucination_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!hgVerdictApproved)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(hgError){if(hallucinationGateEnabled)return{blocked:!0,reason:"HALLUCINATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: hallucination guard gate encountered an error when hallucination_guard was enabled. Error: ${String(hgError)}`,agentsDispatched,agentsMissing:[],warnings:[`HALLUCINATION_GATE_ERROR: ${String(hgError)}`]};else safeWarn("[phase_complete] Hallucination guard error (non-blocking):",hgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs193 from"node:fs";import*as path320 from"node:path";async function runMutationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,mutationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.mutation_test===!0){if(mutationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"MUTATION_GATE_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: mutation_test is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let mgPath=path320.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs193.readFileSync(mgPath,"utf-8"),mgBundle=JSON.parse(mgContent);for(let entry of mgBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="mutation-gate"&&typeof entry.verdict==="string"){if(mgVerdictFound=!0,mgVerdict=entry.verdict,entry.verdict==="fail")return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate returned verdict 'fail'. Resolve surviving mutants or lower the kill-rate threshold before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};else if(!["pass","warn","skip"].includes(entry.verdict))return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: pass, warn, fail, skip.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Mutation gate evidence unreadable:",readErr);mgVerdictFound=!1}if(!mgVerdictFound)return{blocked:!0,reason:"MUTATION_GATE_MISSING",message:`Phase ${phase} cannot be completed: mutation_test is enabled and evidence not found at .swarm/evidence/${phase}/mutation-gate.json. Run mutation_test, then call write_mutation_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(mgVerdict==="warn")safeWarn(`[phase_complete] Mutation gate verdict is 'warn' for phase ${phase} — proceeding with warning`,void 0)}}catch(mgError){if(mutationGateEnabled)return{blocked:!0,reason:"MUTATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: mutation gate encountered an error when mutation_test was enabled. Error: ${String(mgError)}`,agentsDispatched,agentsMissing:[],warnings:[`MUTATION_GATE_ERROR: ${String(mgError)}`]};else safeWarn("[phase_complete] Mutation gate error (non-blocking):",mgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs194 from"node:fs";import*as path321 from"node:path";init_council_review_identity();function readLatestRetroTimestampMs2(dir,phase){let baseDir=path321.normalize(path321.resolve(dir,".swarm")),retroPath=path321.normalize(path321.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path321.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path321.sep)||retroPath===baseDir))return null;try{return latestRetroTimestampMsFromBundle(JSON.parse(fs194.readFileSync(retroPath,"utf-8")),phase)}catch{return null}}async function runPhaseCouncilGate(ctx){let{phase,dir,sessionID,pluginConfig,agentsDispatched,safeWarn}=ctx,gateWarnings=[],councilModeEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.phase_council===!0&&pluginConfig.council?.enabled===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"PHASE_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: phase_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};councilModeEnabled=!0;let identity=computeCouncilReviewIdentity({level:"phase",scope:{kind:"phase",phaseNumber:phase},plan:preamble.plan??null,config:pluginConfig.council}),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(pluginConfig.council),pcPath=path321.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcPhaseNumber;try{let pcContent=fs194.readFileSync(pcPath,"utf-8"),pcBundle=JSON.parse(pcContent);for(let entry of pcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="phase-council"&&typeof entry.verdict==="string"){if(pcVerdictFound=!0,_pcVerdict=entry.verdict,pcQuorumSize=typeof entry.quorumSize==="number"?entry.quorumSize:void 0,pcPhaseNumber=typeof entry.phase_number==="number"?entry.phase_number:typeof entry.phase==="number"?entry.phase:void 0,pcPhaseNumber===void 0||typeof pcPhaseNumber!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_PHASE",message:`Phase ${phase} cannot be completed: phase council evidence is missing phase_number field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber!==phase)return{blocked:!0,reason:"PHASE_COUNCIL_PHASE_MISMATCH",message:`Phase ${phase} cannot be completed: phase council evidence is for phase ${pcPhaseNumber}, not phase ${phase}. Run council for the correct phase.`,agentsDispatched,agentsMissing:[],warnings:[]};let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:parseTimestampMs(entry.timestamp),maxAgeMs,mustPostdateMs:latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs2(dir,phase)});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"PHASE_COUNCIL_INVALID_TIMESTAMP",future_timestamp:"PHASE_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"PHASE_COUNCIL_STALE_EVIDENCE",predates_required_input:"PHASE_COUNCIL_STALE_EVIDENCE",invalid_required_input:"PHASE_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"PHASE_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: phase council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"PHASE_COUNCIL_IDENTITY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence ${entry.identity_version?`was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION})`:"predates the council review identity cutover and carries no identity proof"}. Re-convene the phase council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:"PHASE_COUNCIL_STALE_REVIEW_IDENTITY",message:`Phase ${phase} cannot be completed: phase council evidence does not match the current council review identity (review-relevant plan content changed since the review). Re-convene the phase council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"PHASE_COUNCIL_POLICY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence was produced under a different council policy. Re-convene the phase council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Phase council evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="REJECT"||entry.verdict==="reject"){let requiredFixes=entry.requiredFixes??entry.required_fixes??[],fixesDetail=Array.isArray(requiredFixes)&&requiredFixes.length>0?`
7444
7444
  Required fixes: ${requiredFixes.map((f)=>f.detail??JSON.stringify(f)).join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_REJECTED",message:`Phase ${phase} cannot be completed: phase council returned verdict 'REJECT'. Address the required fixes before completing the phase.${fixesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}if(entry.verdict==="CONCERNS"||entry.verdict==="concerns"){if(!(pluginConfig.council?.phaseConcernsAllowComplete??!0)){let advisoryNotes=entry.advisoryNotes??entry.advisory_notes??[],notesDetail=Array.isArray(advisoryNotes)&&advisoryNotes.length>0?`
7445
- Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};let effectiveMinimum=pluginConfig.council.requireAllMembers?5:pluginConfig.council.minimumMembers??3;if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<effectiveMinimum)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (${effectiveMinimum}). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}import{createHash as createHash98}from"node:crypto";var MAX_DETAIL_CHARS=1024,MAX_WARNINGS=32,MAX_ACTORS=64,DEFAULT_GATE_TIMEOUT_MS=1e4,MAX_GATE_TIMEOUT_MS=30000;async function runBoundedGate(check3){let timeoutMs=Math.min(MAX_GATE_TIMEOUT_MS,Math.max(1,check3.timeoutMs??DEFAULT_GATE_TIMEOUT_MS)),timer;try{return await Promise.race([check3.run(),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error(`${check3.id.toUpperCase()}_TIMEOUT: gate read exceeded ${timeoutMs}ms`)),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}function bounded(value,fallback=""){let text=typeof value==="string"?value:fallback;return text.length<=MAX_DETAIL_CHARS?text:`${text.slice(0,MAX_DETAIL_CHARS-1)}…`}function boundedStrings(value,limit=MAX_ACTORS){if(!Array.isArray(value))return[];return value.filter((item)=>typeof item==="string").slice(0,limit).map((item)=>bounded(item))}function recoveryFrom(result){let raw=result.recovery;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(!["tool","command","retry","user_action"].includes(String(candidate2.kind))||typeof candidate2.action!=="string"||candidate2.action.length===0)return;return{kind:candidate2.kind,action:bounded(candidate2.action),...candidate2.args&&typeof candidate2.args==="object"&&!Array.isArray(candidate2.args)?{args:candidate2.args}:{}}}function defaultBlockedRecovery(check3,result){let action={critical_directives:"knowledge_receipt",retrospective:"write_retro",completion_verify:"completion_verify",drift:"write_drift_evidence",hallucination:"write_hallucination_evidence",mutation:"write_mutation_evidence",final_review:"run_phase_review",lean_turbo_readiness:"lean_turbo_review"}[check3.id];if(action){if(check3.id==="lean_turbo_readiness"){let blockedOnCritic=/critic/i.test(`${result.message??""} ${result.reason??""}`);return{kind:"tool",action,...blockedOnCritic?{args:{follow_up_tool:"lean_turbo_critic"}}:{}}}return{kind:"tool",action}}if(check3.id==="phase_council"||check3.id==="final_council")return{kind:"user_action",action:"Task",args:{agents:["critic","reviewer","sme","test_engineer","explorer"],follow_up_tool:check3.id==="phase_council"?"submit_phase_council_verdicts":"write_final_council_evidence"}};if(check3.id==="architecture_supervisor")return{kind:"user_action",action:"Task",args:{agents:["critic_architecture_supervisor"],follow_up_tool:"write_architecture_supervisor_evidence"}};if(check3.id==="full_auto_approval")return{kind:"user_action",action:"Task",args:{agents:["critic_oversight"]}};if(check3.id==="required_agents")return{kind:"user_action",action:"Task",args:{agents:boundedStrings(result.agentsMissing)}};return{kind:"retry",action:"phase_complete"}}function retrospectiveGateFrom(result){let raw=result.retrospective_gate;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(typeof candidate2.schema_valid!=="boolean"||typeof candidate2.gate_pass!=="boolean")return;return{schema_valid:candidate2.schema_valid,gate_pass:candidate2.gate_pass,...candidate2.verdict==="pass"||candidate2.verdict==="fail"?{verdict:candidate2.verdict}:{}}}function stableReportHash(phase,entries2){return createHash98("sha256").update(JSON.stringify({schemaVersion:1,phase,entries:entries2})).digest("hex")}async function collectPhaseGateReport(input){let entries2=[];for(let check3 of input.checks){if(check3.applicable===!1){entries2.push({id:check3.id,code:"NOT_APPLICABLE",outcome:"not_applicable",detail:bounded(check3.notApplicableDetail,"gate not applicable"),evidenceRefs:[],responsibleActor:check3.responsibleActor,agentsDispatched:[],agentsMissing:[],warnings:[]});continue}try{let result=await runBoundedGate(check3),recovery=recoveryFrom(result)??(result.blocked?defaultBlockedRecovery(check3,result):void 0),retrospectiveGate=retrospectiveGateFrom(result);entries2.push({id:check3.id,code:typeof result.reason==="string"?bounded(result.reason):result.blocked?`${check3.id.toUpperCase()}_BLOCKED`:"PASS",outcome:result.blocked?"block":"pass",...typeof result.message==="string"?{detail:bounded(result.message)}:{},evidenceRefs:boundedStrings(result.evidenceRefs),responsibleActor:check3.responsibleActor,...recovery?{recovery,requiredRecoveryKind:recovery.kind}:{},...retrospectiveGate?{retrospective_gate:retrospectiveGate}:{},agentsDispatched:boundedStrings(result.agentsDispatched),agentsMissing:boundedStrings(result.agentsMissing),warnings:boundedStrings(result.warnings,MAX_WARNINGS),...typeof result.recovery_guidance==="string"?{recoveryGuidance:bounded(result.recovery_guidance)}:{},...result.phase_council_required===!0?{phase_council_required:!0}:{},...result.final_council_required===!0?{final_council_required:!0}:{}})}catch(error93){entries2.push({id:check3.id,code:error93 instanceof Error&&error93.message.startsWith(`${check3.id.toUpperCase()}_TIMEOUT:`)?`${check3.id.toUpperCase()}_TIMEOUT`:`${check3.id.toUpperCase()}_ERROR`,outcome:"error",detail:bounded(error93 instanceof Error?error93.message:String(error93),"unknown gate error"),evidenceRefs:[],responsibleActor:check3.responsibleActor,recovery:{kind:"retry",action:"phase_complete"},requiredRecoveryKind:"retry",agentsDispatched:[],agentsMissing:[],warnings:[]})}}let outcome=entries2.some((entry)=>entry.outcome==="block"||entry.outcome==="error")?"block":"pass";return{schemaVersion:1,phase:input.phase,outcome,reportHash:stableReportHash(input.phase,entries2),entries:entries2}}function formatPhaseGateCompatibility(report){let firstFailure=report.entries.find((entry)=>entry.outcome==="block"||entry.outcome==="error"),retrospectiveEntry=report.entries.find((entry)=>entry.id==="retrospective"&&entry.retrospective_gate),recoveryGuidance=report.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,requiredAgentsEntry=report.entries.find((entry)=>entry.id==="required_agents"),dispatched=new Set,missing=new Set,warnings=[];for(let entry of report.entries){for(let actor of entry.agentsDispatched)dispatched.add(actor);for(let actor of entry.agentsMissing)missing.add(actor);for(let warning of entry.warnings)if(warnings.length<MAX_WARNINGS&&!warnings.includes(warning))warnings.push(warning)}if(requiredAgentsEntry){dispatched.clear();for(let actor of requiredAgentsEntry.agentsDispatched)dispatched.add(actor)}return{success:report.outcome==="pass",phase:report.phase,status:report.outcome==="pass"?"success":firstFailure?.code==="REQUIRED_AGENTS_MISSING"?"incomplete":"blocked",...firstFailure?{reason:firstFailure.code,message:firstFailure.detail}:{},agentsDispatched:[...dispatched].sort(),agentsMissing:[...missing].sort(),warnings,gate_report:report,...recoveryGuidance?{recovery_guidance:recoveryGuidance}:{},...report.entries.some((entry)=>entry.phase_council_required)?{phase_council_required:!0}:{},...report.entries.some((entry)=>entry.final_council_required)?{final_council_required:!0}:{},...retrospectiveEntry?.retrospective_gate?{retrospective_gate:retrospectiveEntry.retrospective_gate}:{}}}import{createHash as createHash99}from"node:crypto";import*as fs195 from"node:fs";import*as path322 from"node:path";var MAX_SNAPSHOT_FILES=512,MAX_SNAPSHOT_ENTRIES=2048,MAX_SNAPSHOT_BYTES=16777216,INPUTS=[".swarm/evidence",".swarm/spec.md",".swarm/knowledge-receipts-v2.jsonl","specs","openspec/specs","openspec/changes"];function compareUtf8(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function isContained3(root,candidate2){let relative81=path322.relative(root,candidate2);return relative81===""||relative81!==".."&&!relative81.startsWith(`..${path322.sep}`)&&!path322.isAbsolute(relative81)}function computePhaseEvidenceSnapshot(directory){let root=fs195.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat24;try{stat24=fs195.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat24.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path322.relative(root,absolute)}`);if(stat24.isDirectory()){let names=[],handle=fs195.opendirSync(absolute);try{for(;;){let entry=handle.readSync();if(!entry)break;if(visitedEntries+=1,visitedEntries>MAX_SNAPSHOT_ENTRIES)throw Error("PHASE_SNAPSHOT_ENTRY_LIMIT");names.push(entry.name)}}finally{handle.closeSync()}for(let name of names.sort(compareUtf8))visit(path322.join(absolute,name));return}if(!stat24.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path322.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat24.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs195.openSync(absolute,fs195.constants.O_RDONLY|(fs195.constants.O_NOFOLLOW??0));try{let opened=fs195.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat24.dev||opened.ino!==stat24.ino||opened.size!==stat24.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs195.readFileSync(descriptor),after=fs195.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path322.relative(root,absolute).replaceAll("\\","/"),sha256:createHash99("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs195.closeSync(descriptor)}};for(let relative81 of INPUTS)visit(path322.join(root,...relative81.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash99("sha256").update(JSON.stringify({schemaVersion:1,entries:entries2})).digest("hex")}init_resolve_working_directory();var phaseCompleteReceiptInternals={recordPhaseCloseIntent,commitPhaseClosed},phaseCompleteCommitInternals={savePlan:(...args2)=>savePlan(...args2)},phaseCompletePreflightInternals={runCompletionVerifyGate,runDriftGate,runHallucinationGate,runMutationGate,runPhaseCouncilGate,runArchitectureSupervisorGate,runFinalReviewGate,runFinalCouncilGate};function buildMissingAgentRecoveryGuidance(input){if(input.missing.length===0)return;let steps=[`Dispatch the missing required role${input.missing.length===1?"":"s"} (${input.missing.join(", ")}) and retry phase_complete after each Task returns a successful, non-empty result.`];if(input.docsAddedByConfig&&input.missing.includes("docs"))steps.push("If this phase genuinely has no documentation obligation, set phase_complete.require_docs to false in opencode-swarm configuration; that setting is independent of the QA gate profile.");if(!input.docsPlanReadable&&input.missing.includes("docs"))steps.push("A readable plan is required to bind durable docs participation. Restore or rebuild .swarm/plan.json/.swarm/plan.md (or recover from .swarm/plan-export/) before re-dispatching docs, then retry phase_complete.");if(input.docsEvidenceStatus==="corrupt")steps.push("The readable docs-participation projection is corrupt; a genuine docs re-dispatch will quarantine the original bytes and rebuild it safely.");else if(input.docsEvidenceStatus==="unreadable"||input.docsEvidenceStatus==="oversized")steps.push("The docs-participation projection needs operator repair or archival before a re-dispatch can persist new proof.");if(input.missing.includes("docs")&&input.docsEvidenceStatus==="missing")steps.push("No prior durable docs-participation receipt was found (this can happen after a plugin upgrade or a cleared evidence store). A fresh docs Task dispatch writes a new durable completion receipt and is the canonical recovery path.");if(input.policy==="warn")steps.push("The configured warn policy allows closure with a warning, but it does not create participation proof.");else steps.push('Last resort: if the missing role obligation genuinely cannot be satisfied in this environment, set phase_complete.policy to "warn" in opencode-swarm configuration. This weakens enforcement for every missing role and does NOT create durable participation proof, so only use it when the obligation cannot be met.');return steps.join(" ")}function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES7=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task2 of tasks){if(task2.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task2.id))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&(entry.verdict==="pass"||entry.verdict==="fail")}async function executePhaseComplete(args2,workingDirectory,directory,_runtime={}){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[];if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);let crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1){let disabledReport=await collectPhaseGateReport({phase,checks:["critical_directives","retrospective","completion_verify","drift","hallucination","mutation","phase_council","architecture_supervisor","final_review","final_council","full_auto_approval","lean_turbo_readiness","required_agents","snapshot_identity"].map((id)=>({id,responsibleActor:"architect",applicable:!1,notApplicableDetail:"phase completion enforcement is disabled",run:async()=>({blocked:!1,agentsDispatched:[],agentsMissing:[],warnings:[]})}))});return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[],gate_report:disabledReport},null,2)}let receiptPlan=await loadPlan(dir).catch(()=>null),receiptPhaseLabel=receiptPlan?extractCurrentPhaseFromPlan(receiptPlan)??`Phase ${receiptPlan.current_phase??phase}`:`Phase ${phase}`,knowledgeEnabled=config3.knowledge?.enabled!==!1,retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,retrospectiveGate={schema_valid:!1,gate_pass:!1},primaryRetroTaskId=`retro-${phase}`,preflightNowMs=Date.now(),gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId,preflightNowMs},passGate=(extra={})=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[],...extra}),preflightChecks=[];preflightChecks.push({id:"critical_directives",responsibleActor:"architect",applicable:knowledgeEnabled,notApplicableDetail:"knowledge directives are disabled",run:async()=>{let requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((value)=>typeof value==="string"&&value.length>0):[];if(requestedAccept.length>0){let callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect";if(stripKnownSwarmPrefix(callerAgent).toLowerCase()!=="architect")return{...passGate(),blocked:!0,reason:"OVERRIDE_DENIED_NON_ARCHITECT",message:"accept_violations is architect-only and cannot be committed by this caller."};let justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"";return{...passGate(),blocked:!0,reason:justification.length>=10?"DIRECTIVE_OVERRIDE_SEPARATE_ACTION_REQUIRED":"OVERRIDE_REQUIRES_JUSTIFICATION",message:justification.length>=10?"Directive overrides are separate audited evidence writes. Record the override, then retry phase_complete without accept_violations.":"accept_violations requires at least 10 characters of substantive justification.",recovery:{kind:"tool",action:"record_directive_override",args:{directive_ids:requestedAccept,justification,phase}}}}let directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,sessionId:sessionID,phaseLabel:receiptPhaseLabel});if(!directiveGate.blocked)return passGate();return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals267.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=await readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let planRaw=fs197.readFileSync(validateSwarmPath(dir,"plan.json"),"utf8"),target=JSON.parse(planRaw).phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash100("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs197.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash100("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path324.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs197.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs197.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs197.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs197.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries2=taskEvidenceResult.bundle.entries??[];for(let entry of entries2)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_external_tool_runner();init_create_tool();import*as fs198 from"node:fs";import*as path325 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000;function resolveAuditCommandDefault(name){if(process.platform!=="win32")return[name];let resolved=resolveExecutableFromPath([name]);if(!resolved)return[name];let lowered=resolved.toLowerCase();if(lowered.endsWith(".cmd")||lowered.endsWith(".bat")){if(/["&|<>^!%]/.test(resolved))return[name];return["cmd.exe","/d","/s","/c",`call "${resolved}"`]}return[resolved]}var _internals270={bunSpawn,resolveAuditCommand:resolveAuditCommandDefault};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs198.existsSync(path325.join(cwd,"package.json")))ecosystems.push("npm");if(fs198.existsSync(path325.join(cwd,"pyproject.toml"))||fs198.existsSync(path325.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs198.existsSync(path325.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs198.existsSync(path325.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs198.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs198.existsSync(path325.join(cwd,"Gemfile"))||fs198.existsSync(path325.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs198.existsSync(path325.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs198.existsSync(path325.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=[..._internals270.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals270.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity){switch(severity.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=[..._internals270.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals270.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
7445
+ Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};let effectiveMinimum=pluginConfig.council.requireAllMembers?5:pluginConfig.council.minimumMembers??3;if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<effectiveMinimum)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (${effectiveMinimum}). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}import{createHash as createHash98}from"node:crypto";var MAX_DETAIL_CHARS=1024,MAX_WARNINGS=32,MAX_ACTORS=64,DEFAULT_GATE_TIMEOUT_MS=1e4,MAX_GATE_TIMEOUT_MS=30000;async function runBoundedGate(check3){let timeoutMs=Math.min(MAX_GATE_TIMEOUT_MS,Math.max(1,check3.timeoutMs??DEFAULT_GATE_TIMEOUT_MS)),timer;try{return await Promise.race([check3.run(),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error(`${check3.id.toUpperCase()}_TIMEOUT: gate read exceeded ${timeoutMs}ms`)),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}function bounded(value,fallback=""){let text=typeof value==="string"?value:fallback;return text.length<=MAX_DETAIL_CHARS?text:`${text.slice(0,MAX_DETAIL_CHARS-1)}…`}function boundedStrings(value,limit=MAX_ACTORS){if(!Array.isArray(value))return[];return value.filter((item)=>typeof item==="string").slice(0,limit).map((item)=>bounded(item))}function recoveryFrom(result){let raw=result.recovery;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(!["tool","command","retry","user_action"].includes(String(candidate2.kind))||typeof candidate2.action!=="string"||candidate2.action.length===0)return;return{kind:candidate2.kind,action:bounded(candidate2.action),...candidate2.args&&typeof candidate2.args==="object"&&!Array.isArray(candidate2.args)?{args:candidate2.args}:{}}}function defaultBlockedRecovery(check3,result){let action={critical_directives:"knowledge_receipt",retrospective:"write_retro",completion_verify:"completion_verify",drift:"write_drift_evidence",hallucination:"write_hallucination_evidence",mutation:"write_mutation_evidence",final_review:"run_phase_review",lean_turbo_readiness:"lean_turbo_review"}[check3.id];if(action){if(check3.id==="lean_turbo_readiness"){let blockedOnCritic=/critic/i.test(`${result.message??""} ${result.reason??""}`);return{kind:"tool",action,...blockedOnCritic?{args:{follow_up_tool:"lean_turbo_critic"}}:{}}}return{kind:"tool",action}}if(check3.id==="phase_council"||check3.id==="final_council")return{kind:"user_action",action:"Task",args:{agents:["critic","reviewer","sme","test_engineer","explorer"],follow_up_tool:check3.id==="phase_council"?"submit_phase_council_verdicts":"write_final_council_evidence"}};if(check3.id==="architecture_supervisor")return{kind:"user_action",action:"Task",args:{agents:["critic_architecture_supervisor"],follow_up_tool:"write_architecture_supervisor_evidence"}};if(check3.id==="full_auto_approval")return{kind:"user_action",action:"Task",args:{agents:["critic_oversight"]}};if(check3.id==="required_agents")return{kind:"user_action",action:"Task",args:{agents:boundedStrings(result.agentsMissing)}};return{kind:"retry",action:"phase_complete"}}function retrospectiveGateFrom(result){let raw=result.retrospective_gate;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(typeof candidate2.schema_valid!=="boolean"||typeof candidate2.gate_pass!=="boolean")return;return{schema_valid:candidate2.schema_valid,gate_pass:candidate2.gate_pass,...candidate2.verdict==="pass"||candidate2.verdict==="fail"?{verdict:candidate2.verdict}:{}}}function stableReportHash(phase,entries2){return createHash98("sha256").update(JSON.stringify({schemaVersion:1,phase,entries:entries2})).digest("hex")}async function collectPhaseGateReport(input){let entries2=[];for(let check3 of input.checks){if(check3.applicable===!1){entries2.push({id:check3.id,code:"NOT_APPLICABLE",outcome:"not_applicable",detail:bounded(check3.notApplicableDetail,"gate not applicable"),evidenceRefs:[],responsibleActor:check3.responsibleActor,agentsDispatched:[],agentsMissing:[],warnings:[]});continue}try{let result=await runBoundedGate(check3),recovery=recoveryFrom(result)??(result.blocked?defaultBlockedRecovery(check3,result):void 0),retrospectiveGate=retrospectiveGateFrom(result);entries2.push({id:check3.id,code:typeof result.reason==="string"?bounded(result.reason):result.blocked?`${check3.id.toUpperCase()}_BLOCKED`:"PASS",outcome:result.blocked?"block":"pass",...typeof result.message==="string"?{detail:bounded(result.message)}:{},evidenceRefs:boundedStrings(result.evidenceRefs),responsibleActor:check3.responsibleActor,...recovery?{recovery,requiredRecoveryKind:recovery.kind}:{},...retrospectiveGate?{retrospective_gate:retrospectiveGate}:{},agentsDispatched:boundedStrings(result.agentsDispatched),agentsMissing:boundedStrings(result.agentsMissing),warnings:boundedStrings(result.warnings,MAX_WARNINGS),...typeof result.recovery_guidance==="string"?{recoveryGuidance:bounded(result.recovery_guidance)}:{},...result.phase_council_required===!0?{phase_council_required:!0}:{},...result.final_council_required===!0?{final_council_required:!0}:{}})}catch(error93){entries2.push({id:check3.id,code:error93 instanceof Error&&error93.message.startsWith(`${check3.id.toUpperCase()}_TIMEOUT:`)?`${check3.id.toUpperCase()}_TIMEOUT`:`${check3.id.toUpperCase()}_ERROR`,outcome:"error",detail:bounded(error93 instanceof Error?error93.message:String(error93),"unknown gate error"),evidenceRefs:[],responsibleActor:check3.responsibleActor,recovery:{kind:"retry",action:"phase_complete"},requiredRecoveryKind:"retry",agentsDispatched:[],agentsMissing:[],warnings:[]})}}let outcome=entries2.some((entry)=>entry.outcome==="block"||entry.outcome==="error")?"block":"pass";return{schemaVersion:1,phase:input.phase,outcome,reportHash:stableReportHash(input.phase,entries2),entries:entries2}}function formatPhaseGateCompatibility(report){let firstFailure=report.entries.find((entry)=>entry.outcome==="block"||entry.outcome==="error"),retrospectiveEntry=report.entries.find((entry)=>entry.id==="retrospective"&&entry.retrospective_gate),recoveryGuidance=report.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,requiredAgentsEntry=report.entries.find((entry)=>entry.id==="required_agents"),dispatched=new Set,missing=new Set,warnings=[];for(let entry of report.entries){for(let actor of entry.agentsDispatched)dispatched.add(actor);for(let actor of entry.agentsMissing)missing.add(actor);for(let warning of entry.warnings)if(warnings.length<MAX_WARNINGS&&!warnings.includes(warning))warnings.push(warning)}if(requiredAgentsEntry){dispatched.clear();for(let actor of requiredAgentsEntry.agentsDispatched)dispatched.add(actor)}return{success:report.outcome==="pass",phase:report.phase,status:report.outcome==="pass"?"success":firstFailure?.code==="REQUIRED_AGENTS_MISSING"?"incomplete":"blocked",...firstFailure?{reason:firstFailure.code,message:firstFailure.detail}:{},agentsDispatched:[...dispatched].sort(),agentsMissing:[...missing].sort(),warnings,gate_report:report,...recoveryGuidance?{recovery_guidance:recoveryGuidance}:{},...report.entries.some((entry)=>entry.phase_council_required)?{phase_council_required:!0}:{},...report.entries.some((entry)=>entry.final_council_required)?{final_council_required:!0}:{},...retrospectiveEntry?.retrospective_gate?{retrospective_gate:retrospectiveEntry.retrospective_gate}:{}}}import{createHash as createHash99}from"node:crypto";import*as fs195 from"node:fs";import*as path322 from"node:path";var MAX_SNAPSHOT_FILES=512,MAX_SNAPSHOT_ENTRIES=2048,MAX_SNAPSHOT_BYTES=16777216,INPUTS=[".swarm/evidence",".swarm/spec.md",".swarm/knowledge-receipts-v2.jsonl","specs","openspec/specs","openspec/changes"];function compareUtf8(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function isContained3(root,candidate2){let relative81=path322.relative(root,candidate2);return relative81===""||relative81!==".."&&!relative81.startsWith(`..${path322.sep}`)&&!path322.isAbsolute(relative81)}function computePhaseEvidenceSnapshot(directory){let root=fs195.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat24;try{stat24=fs195.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat24.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path322.relative(root,absolute)}`);if(stat24.isDirectory()){let names=[],handle=fs195.opendirSync(absolute);try{for(;;){let entry=handle.readSync();if(!entry)break;if(visitedEntries+=1,visitedEntries>MAX_SNAPSHOT_ENTRIES)throw Error("PHASE_SNAPSHOT_ENTRY_LIMIT");names.push(entry.name)}}finally{handle.closeSync()}for(let name of names.sort(compareUtf8))visit(path322.join(absolute,name));return}if(!stat24.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path322.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat24.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs195.openSync(absolute,fs195.constants.O_RDONLY|(fs195.constants.O_NOFOLLOW??0));try{let opened=fs195.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat24.dev||opened.ino!==stat24.ino||opened.size!==stat24.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs195.readFileSync(descriptor),after=fs195.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path322.relative(root,absolute).replaceAll("\\","/"),sha256:createHash99("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs195.closeSync(descriptor)}};for(let relative81 of INPUTS)visit(path322.join(root,...relative81.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash99("sha256").update(JSON.stringify({schemaVersion:1,entries:entries2})).digest("hex")}init_resolve_working_directory();var phaseCompleteReceiptInternals={recordPhaseCloseIntent,commitPhaseClosed},phaseCompleteCommitInternals={savePlan:(...args2)=>savePlan(...args2)},phaseCompletePreflightInternals={runCompletionVerifyGate,runDriftGate,runHallucinationGate,runMutationGate,runPhaseCouncilGate,runArchitectureSupervisorGate,runFinalReviewGate,runFinalCouncilGate};function buildMissingAgentRecoveryGuidance(input){if(input.missing.length===0)return;let steps=[`Dispatch the missing required role${input.missing.length===1?"":"s"} (${input.missing.join(", ")}) and retry phase_complete after each Task returns a successful, non-empty result.`];if(input.docsAddedByConfig&&input.missing.includes("docs"))steps.push("If this phase genuinely has no documentation obligation, set phase_complete.require_docs to false in opencode-swarm configuration; that setting is independent of the QA gate profile.");if(!input.docsPlanReadable&&input.missing.includes("docs"))steps.push("A readable plan is required to bind durable docs participation. Restore or rebuild .swarm/plan.json/.swarm/plan.md (or recover from .swarm/plan-export/) before re-dispatching docs, then retry phase_complete.");if(input.docsEvidenceStatus==="corrupt")steps.push("The readable docs-participation projection is corrupt; a genuine docs re-dispatch will quarantine the original bytes and rebuild it safely.");else if(input.docsEvidenceStatus==="unreadable"||input.docsEvidenceStatus==="oversized")steps.push("The docs-participation projection needs operator repair or archival before a re-dispatch can persist new proof.");if(input.missing.includes("docs")&&input.docsEvidenceStatus==="missing")steps.push("No prior durable docs-participation receipt was found (this can happen after a plugin upgrade or a cleared evidence store). A fresh docs Task dispatch writes a new durable completion receipt and is the canonical recovery path.");if(input.policy==="warn")steps.push("The configured warn policy allows closure with a warning, but it does not create participation proof.");else steps.push('Last resort: if the missing role obligation genuinely cannot be satisfied in this environment, set phase_complete.policy to "warn" in opencode-swarm configuration. This weakens enforcement for every missing role and does NOT create durable participation proof, so only use it when the obligation cannot be met.');return steps.join(" ")}function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES7=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task2 of tasks){if(task2.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task2.id))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&(entry.verdict==="pass"||entry.verdict==="fail")}async function executePhaseComplete(args2,workingDirectory,directory,_runtime={}){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[];if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);let crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1){let disabledReport=await collectPhaseGateReport({phase,checks:["critical_directives","retrospective","completion_verify","drift","hallucination","mutation","phase_council","architecture_supervisor","final_review","final_council","full_auto_approval","lean_turbo_readiness","required_agents","snapshot_identity"].map((id)=>({id,responsibleActor:"architect",applicable:!1,notApplicableDetail:"phase completion enforcement is disabled",run:async()=>({blocked:!1,agentsDispatched:[],agentsMissing:[],warnings:[]})}))});return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[],gate_report:disabledReport},null,2)}let receiptPlan=await loadPlan(dir).catch(()=>null),receiptPhaseLabel=receiptPlan?extractCurrentPhaseFromPlan(receiptPlan)??`Phase ${receiptPlan.current_phase??phase}`:`Phase ${phase}`,knowledgeEnabled=config3.knowledge?.enabled!==!1,retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,retrospectiveGate={schema_valid:!1,gate_pass:!1},primaryRetroTaskId=`retro-${phase}`,preflightNowMs=Date.now(),gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId,preflightNowMs},passGate=(extra={})=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[],...extra}),preflightChecks=[];preflightChecks.push({id:"critical_directives",responsibleActor:"architect",applicable:knowledgeEnabled,notApplicableDetail:"knowledge directives are disabled",run:async()=>{let requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((value)=>typeof value==="string"&&value.length>0):[];if(requestedAccept.length>0){let callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect";if(stripKnownSwarmPrefix(callerAgent).toLowerCase()!=="architect")return{...passGate(),blocked:!0,reason:"OVERRIDE_DENIED_NON_ARCHITECT",message:"accept_violations is architect-only and cannot be committed by this caller."};let justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"";return{...passGate(),blocked:!0,reason:justification.length>=10?"DIRECTIVE_OVERRIDE_SEPARATE_ACTION_REQUIRED":"OVERRIDE_REQUIRES_JUSTIFICATION",message:justification.length>=10?"Directive overrides are separate audited evidence writes. Record the override, then retry phase_complete without accept_violations.":"accept_violations requires at least 10 characters of substantive justification.",recovery:{kind:"tool",action:"record_directive_override",args:{directive_ids:requestedAccept,justification,phase}}}}let directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,sessionId:sessionID,phaseLabel:receiptPhaseLabel});if(!directiveGate.blocked)return passGate();return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals267.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=await readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let planRaw=fs197.readFileSync(validateSwarmPath(dir,"plan.json"),"utf8"),target=JSON.parse(planRaw).phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash100("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs197.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{let saveDurability=await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash100("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}});if(saveDurability.durability==="incomplete")warnings.push(`Plan saved with incomplete durability; degraded surfaces: ${saveDurability.degraded_surfaces.join(", ")}`+(saveDurability.md_write_error?` (${saveDurability.md_write_error})`:""))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path324.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs197.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs197.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs197.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs197.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries2=taskEvidenceResult.bundle.entries??[];for(let entry of entries2)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_external_tool_runner();init_create_tool();import*as fs198 from"node:fs";import*as path325 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000;function resolveAuditCommandDefault(name){if(process.platform!=="win32")return[name];let resolved=resolveExecutableFromPath([name]);if(!resolved)return[name];let lowered=resolved.toLowerCase();if(lowered.endsWith(".cmd")||lowered.endsWith(".bat")){if(/["&|<>^!%]/.test(resolved))return[name];return["cmd.exe","/d","/s","/c",`call "${resolved}"`]}return[resolved]}var _internals270={bunSpawn,resolveAuditCommand:resolveAuditCommandDefault};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs198.existsSync(path325.join(cwd,"package.json")))ecosystems.push("npm");if(fs198.existsSync(path325.join(cwd,"pyproject.toml"))||fs198.existsSync(path325.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs198.existsSync(path325.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs198.existsSync(path325.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs198.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs198.existsSync(path325.join(cwd,"Gemfile"))||fs198.existsSync(path325.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs198.existsSync(path325.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs198.existsSync(path325.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=[..._internals270.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals270.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity){switch(severity.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=[..._internals270.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals270.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
7446
7446
  `).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.vulnerabilities?.list)for(let item of obj.vulnerabilities.list){let cvss=item.advisory.cvss||0,severity=mapCargoSeverity(cvss);findings.push({package:item.advisory.package,installedVersion:item.package.version,patchedVersion:item.versions.patched&&item.versions.patched.length>0?item.versions.patched[0]:null,severity,title:item.advisory.title,cve:item.advisory.aliases&&item.advisory.aliases.length>0?item.advisory.aliases[0]:item.advisory.id?item.advisory.id:null,url:item.advisory.url||null})}}catch{}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"cargo",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return cargoAuditFailure(command,error93)}}function mapCargoSeverity(cvss){if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runGoAudit(directory){let command=["govulncheck","-json","./..."];if(!isCommandAvailable("govulncheck"))return warn("[pkg-audit] govulncheck not found, skipping Go audit"),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"govulncheck not installed. Install with: go install golang.org/x/vuln/cmd/govulncheck@latest"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==3)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck exited with code ${exitCode}`};if(exitCode===0)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let osvMap=new Map,goFindings=[],lines=stdout.split(`
7447
7447
  `).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.osv)osvMap.set(obj.osv.id,obj.osv);if(obj.finding)goFindings.push(obj.finding)}catch{}let findings=[];for(let finding of goFindings){let osv=osvMap.get(finding.osv),severity=osv?.aliases?.some((a)=>a.startsWith("CVE-"))??!1?"high":"moderate",cve=osv?.aliases?.find((a)=>a.startsWith("CVE-"))??null,url3=osv?.references?.find((r)=>r.type==="WEB")?.url??`https://pkg.go.dev/vuln/${finding.osv}`,trace0=finding.trace[0],pkgName=trace0?.module??finding.osv,installedVersion=trace0?.version??"unknown";findings.push({package:pkgName,installedVersion,patchedVersion:finding.fixed_by??null,severity,title:osv?.summary??finding.osv,cve,url:url3})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"go",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running govulncheck: ${errorMessage3}`}}}async function runDotnetAudit(directory){let command=["dotnet","list","package","--vulnerable","--include-transitive"];if(!isCommandAvailable("dotnet"))return warn("[pkg-audit] dotnet not found, skipping .NET audit"),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dotnet CLI not installed. Install from: https://dotnet.microsoft.com/download"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dotnet list package timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&!stdout.includes("has the following vulnerable packages"))return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dotnet list package exited with code ${exitCode}`};let vulnLinePattern=/^\s*>\s+(\S+)\s+\S+\s+(\S+)\s+(Critical|High|Moderate|Low)\s+(\S+)/i,findings=[],lines=stdout.split(`
7448
7448
  `);for(let line of lines){let match=line.match(vulnLinePattern);if(match){let[,pkgName,resolvedVersion,severityStr,url3]=match,severity=mapDotnetSeverity(severityStr);findings.push({package:pkgName,installedVersion:resolvedVersion,patchedVersion:null,severity,title:`Vulnerable package: ${pkgName}`,cve:null,url:url3})}}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"dotnet",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running dotnet list package: ${errorMessage3}`}}}function mapDotnetSeverity(severity){switch(severity.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runBundleAudit(directory){let useBundleExec=!isCommandAvailable("bundle-audit")&&isCommandAvailable("bundle");if(!isCommandAvailable("bundle-audit")&&!isCommandAvailable("bundle"))return warn("[pkg-audit] bundle-audit not found, skipping Ruby audit"),{ecosystem:"ruby",command:["bundle-audit","check","--format","json"],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"bundle-audit not installed. Install with: gem install bundler-audit"};let command=useBundleExec?["bundle","exec","bundle-audit","check","--format","json"]:["bundle-audit","check","--format","json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`bundle-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==1)return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`bundle-audit failed with exit code ${exitCode}`};if(exitCode===0)return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let response;try{response=JSON.parse(stdout)}catch{return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"bundle-audit JSON output could not be parsed"}}let findings=[];for(let item of response.results??[]){let adv=item.advisory,severity=mapBundleSeverity(adv);findings.push({package:item.gem.name,installedVersion:item.gem.version,patchedVersion:adv.patched_versions?.[0]??null,severity,title:adv.title,cve:adv.cve??null,url:adv.url})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"ruby",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error",isNotInstalled=errorMessage3.includes("not recognized")||errorMessage3.includes("not found")||errorMessage3.includes("No such file")||errorMessage3.includes("ENOENT");return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:isNotInstalled?"bundle-audit not installed. Install with: gem install bundler-audit":`Error running bundle-audit: ${errorMessage3}`}}}function mapBundleSeverity(adv){if(adv.criticality)switch(adv.criticality.toLowerCase()){case"critical":return"critical";case"high":return"high";case"medium":return"moderate";case"low":return"low"}let cvss=adv.cvss_v3??adv.cvss_v2??0;if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runDartAudit(directory){let dartBin=isCommandAvailable("dart")?"dart":isCommandAvailable("flutter")?"flutter":null;if(!dartBin)return warn("[pkg-audit] dart/flutter not found, skipping Dart audit"),{ecosystem:"dart",command:["dart","pub","outdated","--json"],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dart or flutter not installed. Install from: https://dart.dev/get-dart"};let command=[dartBin,"pub","outdated","--json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dart pub outdated timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0)return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dart pub outdated exited with code ${exitCode}`};let response;try{response=JSON.parse(stdout)}catch{return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dart pub outdated JSON output could not be parsed"}}let findings=[];for(let pkg of response.packages??[]){let current=pkg.current?.version,latest=pkg.latest?.version;if(!current||!latest||current===latest)continue;if(!pkg.upgradable)continue;findings.push({package:pkg.package,installedVersion:current,patchedVersion:pkg.upgradable.version,severity:"info",title:`Outdated package: ${pkg.package} (${current} → ${latest})`,cve:null,url:`https://pub.dev/packages/${pkg.package}`})}return{ecosystem:"dart",command,findings,criticalCount:0,highCount:0,totalCount:findings.length,clean:findings.length===0,note:"dart pub outdated reports outdated packages, not security vulnerabilities"}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running dart pub outdated: ${errorMessage3}`}}}async function runComposerAudit(directory){let command=["composer","audit","--locked","--format=json"];if(!isCommandAvailable("composer"))return warn("[pkg-audit] composer not found, skipping Composer audit"),{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"composer not installed or not on PATH"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve130)=>setTimeout(()=>resolve130("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`composer audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited,hasVulnerabilities=(exitCode&1)!==0,hasAbandoned=(exitCode&2)!==0;if(exitCode===0)return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};if(hasVulnerabilities&&!stdout.trim())return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!1,incomplete:!0,note:`composer audit returned exit code ${exitCode} indicating vulnerabilities but produced no output`};let parsed;try{parsed=JSON.parse(stdout||"{}")}catch{return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!hasVulnerabilities,incomplete:!0,note:`composer audit returned exit code ${exitCode} but output was not valid JSON`}}if(!hasVulnerabilities&&hasAbandoned){let abandonedList=Object.keys(parsed.abandoned??{});return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:abandonedList.length>0?`Abandoned packages detected: ${abandonedList.join(", ")}`:"composer audit exit 2 (abandoned packages)"}}let findings=[];for(let advisories of Object.values(parsed.advisories??{}))for(let advisory of advisories){let hasCve=Boolean(advisory.cve?.trim());findings.push({package:advisory.packageName,installedVersion:"see composer.lock",patchedVersion:null,severity:hasCve?"high":"moderate",title:advisory.title,cve:advisory.cve||null,url:advisory.link||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length,abandonedNote=hasAbandoned&&Object.keys(parsed.abandoned??{}).length>0?` Also abandoned: ${Object.keys(parsed.abandoned).join(", ")}`:"";return{ecosystem:"composer",command,findings,criticalCount,highCount,totalCount:findings.length,clean:!1,...abandonedNote?{note:abandonedNote.trim()}:{}}}catch(error93){return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`composer audit error: ${error93 instanceof Error?error93.message:String(error93)}`}}}async function runAutoAudit(directory){let ecosystems=detectEcosystems(directory);if(ecosystems.length===0)return{ecosystems:[],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let results=[];for(let eco of ecosystems)switch(eco){case"npm":results.push(await runNpmAudit(directory));break;case"pip":results.push(await runPipAudit(directory));break;case"cargo":results.push(await runCargoAudit(directory));break;case"go":results.push(await runGoAudit(directory));break;case"dotnet":results.push(await runDotnetAudit(directory));break;case"ruby":results.push(await runBundleAudit(directory));break;case"dart":results.push(await runDartAudit(directory));break;case"composer":results.push(await runComposerAudit(directory));break}let allFindings=[],totalCritical=0,totalHigh=0,notes=[],ecosystemsIncomplete=[],anyIncomplete=!1;for(let result of results){if(allFindings.push(...result.findings),totalCritical+=result.criticalCount,totalHigh+=result.highCount,result.note)notes.push(result.note);if(result.incomplete)anyIncomplete=!0,ecosystemsIncomplete.push(result.ecosystem)}return{ecosystems,findings:allFindings,criticalCount:totalCritical,highCount:totalHigh,totalCount:allFindings.length,clean:allFindings.length===0&&!anyIncomplete,notes,ecosystemsIncomplete}}var pkg_audit=createSwarmTool({description:'Run package manager security audit (npm, pip, cargo, go, dotnet, ruby, dart) and return structured CVE data. Use ecosystem to specify which package manager, or "auto" to detect from project files.',args:{ecosystem:exports_external.enum(["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"]).default("auto").describe('Package ecosystem to audit: "auto" (detect from project files), "npm", "pip", "cargo", "go" (govulncheck), "dotnet" (dotnet list package), "ruby" (bundle-audit), "dart" (dart pub outdated), or "composer" (Composer/PHP)')},async execute(args2,directory){if(!validateArgs3(args2))return JSON.stringify({error:'Invalid arguments: ecosystem must be "auto", "npm", "pip", "cargo", "go", "dotnet", "ruby", "dart", or "composer"'},null,2);if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided"},null,2);let ecosystem=args2.ecosystem||"auto",result;switch(ecosystem){case"auto":result=await runAutoAudit(directory);break;case"npm":result=await runNpmAudit(directory);break;case"pip":result=await runPipAudit(directory);break;case"cargo":result=await runCargoAudit(directory);break;case"go":result=await runGoAudit(directory);break;case"dotnet":result=await runDotnetAudit(directory);break;case"ruby":result=await runBundleAudit(directory);break;case"dart":result=await runDartAudit(directory);break;case"composer":result=await runComposerAudit(directory);break}return JSON.stringify(result,null,2)}});init_zod();init_config();init_manager2();init_registry();init_utils();init_path_security();init_create_tool();import*as fs199 from"node:fs";import*as path326 from"node:path";var MAX_FILE_SIZE=1048576,DEFAULT_SENTINEL_ALLOWLIST=["SC-PLACEHOLDER"],DEFAULT_COMMENT_PATTERNS=[{pattern:/\bTODO\b/i,rule_id:"placeholder/comment-todo"},{pattern:/\bFIXME\b/i,rule_id:"placeholder/comment-fixme"},{pattern:/\bTBD\b/i,rule_id:"placeholder/comment-other"},{pattern:/\bXXX\b/,rule_id:"placeholder/comment-other"},{pattern:/\bHACK\b/i,rule_id:"placeholder/comment-other"}],DEFAULT_STRING_PATTERNS=[{pattern:/"[^"]*\bplaceholder\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bstub\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bwip\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bnot implemented\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bplaceholder\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bstub\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bwip\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/`[^`]*\bplaceholder\b[^`]*`/i,rule_id:"placeholder/text-placeholder"},{pattern:/`[^`]*\bstub\b[^`]*`/i,rule_id:"placeholder/text-placeholder"}],FILE_ALLOWLIST=["src/tools/declare-scope.ts","src/tools/placeholder-scan.ts"],DEFAULT_CODE_PATTERNS=[{pattern:/throw\s+new\s+Error\s*\(\s*["'][^"']*\bTODO\b[^"']*["']\s*\)/i,rule_id:"placeholder/code-throw-todo"},{pattern:/throw\s+new\s+Error\s*\(\s*["'][^"']*\bFIXME\b[^"']*["']\s*\)/i,rule_id:"placeholder/code-throw-todo"},{pattern:/return\s+null\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+undefined\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+None\s*$/m,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+0\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+false\s*;/i,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+true\s*;/i,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+""\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+\[\]\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+\{\}\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+nil\s*;/,rule_id:"placeholder/code-stub-return"}],PLAN_PLACEHOLDER_PATTERNS=[{pattern:/\[task\]/gi,rule_id:"placeholder/plan-bracket-task"},{pattern:/\[Project\]/g,rule_id:"placeholder/plan-bracket-project"},{pattern:/\[date\]/g,rule_id:"placeholder/plan-bracket-date"},{pattern:/\[reason\]/g,rule_id:"placeholder/plan-bracket-reason"},{pattern:/\[description\]/gi,rule_id:"placeholder/plan-bracket-description"}],TEST_PATH_PATTERNS=[/\.test\./,/\.spec\./,/\btests?\//,/\b__tests?__\//,/\bmocks?\//,/\b__mocks?__\//,/\bspecs?\//,/\b__specs?__\//],SCAFFOLD_PATH_PATTERNS=[/\bgenerated\//,/\bscaffold\//,/\btemplates?\//,/\b__generated__\//,/\b__scaffold__\//],SCAFFOLD_FILENAME_PATTERNS=[/^gen-/,/^scaffold-/,/^template-/,/\.gen\./,/\.scaffold\./,/\.template\./],SUPPORTED_PARSER_EXTENSIONS=new Set([".js",".jsx",".ts",".tsx",".py",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".blade.php",".rb"]);function isTestFile2(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");return TEST_PATH_PATTERNS.some((pattern)=>pattern.test(normalizedPath))}function isScaffoldFile(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");if(SCAFFOLD_PATH_PATTERNS.some((pattern)=>pattern.test(normalizedPath)))return!0;let filename=path326.basename(filePath);if(SCAFFOLD_FILENAME_PATTERNS.some((pattern)=>pattern.test(filename)))return!0;return!1}function isAllowedByGlobs(filePath,allowGlobs){if(!allowGlobs||allowGlobs.length===0)return!1;let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");for(let glob of allowGlobs)try{let regexPattern=glob.replace(/\*\*/g,"<<<DBL>>>").replace(/\*/g,"([^/]+)").replace(/<<<DBL>>>/g,"(.*)");if(new RegExp(`^${regexPattern}`,"i").test(normalizedPath))return!0;let filename=path326.basename(filePath);if(new RegExp(`^${regexPattern}$`,"i").test(filename))return!0}catch{}return!1}function isParserSupported(filePath){let ext=path326.extname(filePath).toLowerCase();return SUPPORTED_PARSER_EXTENSIONS.has(ext)}var BODY_SHAPE_SUPPORTED_EXTENSIONS=new Set([".js",".jsx",".ts",".tsx",".py"]);function isBodyShapeSupported(filePath){return BODY_SHAPE_SUPPORTED_EXTENSIONS.has(path326.extname(filePath).toLowerCase())}function isPlanFile(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");return normalizedPath.endsWith(".swarm/plan.md")||normalizedPath.includes("/.swarm/plan.md")}function scanPlanFileForPlaceholders(content,filePath,addedLines){let findings=[],lines=content.split(`
@@ -7486,7 +7486,7 @@ ${paginatedContent}`;if(endLine<totalLines){let remaining=totalLines-endLine;res
7486
7486
  ${result.stderr}`;return/(?:\b(?:ran|running|collected)\s+0\s+(?:tests?|items?)\b|\btests? run:\s*0\b|\b0\s+(?:tests?\s+(?:ran|passed)|pass(?:ed)?|passing|examples?)\b|\bno tests? (?:ran|to run|found|were found|executed|is available)\b|\bno test is available\b|\btests? (?:are|were) skipped\b|\btest\b[^\n]*\bskipped\b|\bNO-SOURCE\b|\[no test files\])/i.test(output)}function reproductionSelectorValues(command){let runnerVerbs=new Set(["run","run-script","test","tests","spec","check"]),selectorFlags=new Set(["--test-name-pattern","--testNamePattern","--tests","--filter","--grep","-k","-m","-run"]),selectors=new Set;for(let index=1;index<command.length;index+=1){let arg=command[index];if(selectorFlags.has(arg)){let value=command[index+1];if(value&&!value.startsWith("-"))selectors.add(value);index+=1;continue}let assignment=arg.match(/^(?:--(?:test-name-pattern|testNamePattern|tests|filter|grep)|-run|-Dtest)=(.+)$/);if(assignment?.[1]){selectors.add(assignment[1]);continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;if(runnerVerbs.has(arg.toLowerCase()))continue;selectors.add(arg)}return selectors}function isPlausibleTypecheckCommand(executable,args2,_directCommandName){if(executable==="go")return args2[0]==="vet"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));if(executable==="flow")return["check","status","focus-check"].includes(args2[0]?.toLowerCase());if(executable==="phpstan")return["analyse","analyze"].includes(args2[0]?.toLowerCase())&&!args2.some((arg)=>/^--generate-baseline(?:=.*)?$/i.test(arg));return/^(?:tsc|pyright|mypy|sorbet|psalm)$/.test(executable)||executable==="cargo"&&args2[0]==="check"||executable==="dotnet"&&args2[0]==="build"}function isPlausibleReproductionCommand(executable,args2,_directCommandName,_commandPath){if(executable==="python"||executable==="python3")return args2[0]==="-m"&&args2[1]?.toLowerCase()==="pytest";if(executable==="bundle")return args2[0]==="exec"&&args2[1]?.toLowerCase()==="rspec";if(executable==="cargo")return args2[0]==="test"||args2[0]==="nextest"&&args2[1]?.toLowerCase()==="run";if(executable==="go")return args2[0]==="test"&&!args2.some((arg)=>/^(?:-c|-list(?:=.*)?)$/i.test(arg));if(executable==="node")return args2[0]==="--test";if(executable==="deno")return args2[0]==="test";if(executable==="zig")return args2[0]==="test";if(executable==="meson")return args2[0]==="test";if(executable==="make"||executable==="ninja")return args2.some((arg)=>/^(?:test|check|verify|regression)$/i.test(arg));if(executable==="playwright")return args2[0]==="test";if(executable==="dart"||executable==="flutter")return args2[0]==="test";if(executable==="xcodebuild")return args2.some((arg)=>["test","test-without-building"].includes(arg.toLowerCase()))&&!args2.some((arg)=>/^-(?:list|enumerate-tests|showBuildSettings|showdestinations|showTestPlans|showsdks|version|help)$/i.test(arg));if(executable==="cypress")return args2[0]==="run";if(/^(?:pytest|ctest|rspec|phpunit|vitest|jest|mocha|ava|go-test-sum)$/.test(executable))return!0;if(executable==="dotnet")return args2[0]?.toLowerCase()==="test";if(["mvn","mvnw"].includes(executable))return args2.some((arg)=>/^(?:test|verify|integration-test|failsafe:integration-test)$/i.test(arg));if(["gradle","gradlew"].includes(executable)){let invokesExecutableTestTask=args2.some((arg)=>{if(arg.startsWith("-"))return!1;let task2=arg.split(":").filter(Boolean).at(-1)??"";if(/^(?:compile|process|generate|assemble|classes|jar|source|kapt|prepare)/i.test(task2))return!1;return task2.toLowerCase()==="test"||/^test[A-Z0-9_-]/.test(task2)&&/Test$/.test(task2)||/^[a-z][A-Za-z0-9_-]*Test$/.test(task2)});return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&invokesExecutableTestTask}return!1}function isPlausibleStageACommand(category,command){if(category==="diff-check")return isExactDiffCheck(command);let executable=path337.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");if(BLOCKED_EXECUTABLES.has(executable))return!1;if(command.slice(1).some((arg)=>/^(?:-h|--help|--version|version|help|list|-N|--fixtures(?:-per-test)?|--markers|--trace-config|--cache-show|--list(?:-?(?:tests?|suites|groups))?(?:-xml)?(?:=.*)?|--show-only(?:=.*)?|--print-labels|--listFilesOnly|--noCheck|--no-check|--no-run(?:=.*)?|--test-dry-run(?:=.*)?|--createStub|--createstub|--print-config|--env-info|--show-settings|--show-files|--list-msgs|--generate-rcfile|--show-?config(?:=.*)?|--init|--dry-run(?:=.*)?|--collect-only|--setup-(?:only|plan)|--co|--if-present(?:=.*)?)$/i.test(arg)))return!1;if(command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))||["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))return!1;if(category==="lint"&&command.some((arg)=>/^(?:--fix(?:-only)?|--write|--apply|--auto-?correct)(?:=.*)?$|^-[aAw]$/.test(arg)))return!1;if(category==="reproduction"&&(command.some((arg)=>/^(?:--passWithNoTests|--allow-no-tests|--collect-only|--list|--dry-run|--only|--todo|--update-snapshot|--bless|--accept|-w|-x(?:.+)?|--exclude-task(?:=.+)?)$/i.test(arg))||command.some((arg)=>/^-D(?:skipTests|skipITs|maven\.test\.(?:skip|skip\.exec))(?:=true)?$/i.test(arg))))return!1;if(["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&["build","run","test"].includes(command[1]))return isPlausiblePackageManagerCommand(category,executable,command.slice(1));if(executable==="npx")return isPlausiblePackageManagerCommand(category,executable,command.slice(1));let directCommandName=executable.replace(/\.(?:sh|ps1|py|js|mjs|cjs|rb|pl)$/,"");switch(category){case"build":return isPlausibleBuildCommand(executable,command.slice(1));case"typecheck":return isPlausibleTypecheckCommand(executable,command.slice(1),directCommandName);case"lint":return isPlausibleLintCommand(executable,command.slice(1),directCommandName);case"reproduction":return isPlausibleReproductionCommand(executable,command.slice(1),directCommandName,command[0])}}function readBoundedText(filePath){try{let stat24=fs207.statSync(filePath);if(!stat24.isFile()||stat24.size>524288)return;return fs207.readFileSync(filePath,"utf8")}catch{return}}function readPresentRepositoryText(directory,filePath,label){let stat24;try{stat24=fs207.statSync(filePath)}catch(error93){if(error93.code==="ENOENT")return;throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}if(!stat24.isFile()||stat24.size>524288)throw Error(`BLOCKED: Stage A cannot inspect present ${label}`);try{let canonicalRoot=fs207.realpathSync(path337.resolve(directory)),canonicalFile=fs207.realpathSync(filePath),relative87=path337.relative(canonicalRoot,canonicalFile);if(relative87===".."||relative87.startsWith(`..${path337.sep}`)||path337.isAbsolute(relative87))throw Error("escaping manifest");return fs207.readFileSync(canonicalFile,"utf8")}catch{throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}}function resolveContainedDirectory(directory,workingDirectory="."){let root=path337.resolve(directory),canonicalRoot=(()=>{try{return fs207.realpathSync(root)}catch{return root}})(),candidate2=path337.resolve(root,workingDirectory);try{if(!fs207.statSync(candidate2).isDirectory())return;let absolute=fs207.realpathSync(candidate2),relativePath2=path337.relative(canonicalRoot,absolute);if(relativePath2===".."||relativePath2.startsWith(`..${path337.sep}`)||path337.isAbsolute(relativePath2))return;return{absolute,relative:relativePath2.replaceAll("\\","/")||"."}}catch{return}}function readRepositoryValidationContract(directory,contractPath){let root=path337.resolve(directory),canonicalRoot=(()=>{try{return fs207.realpathSync(root)}catch{return root}})(),resolved=path337.resolve(root,contractPath),canonicalContract;try{canonicalContract=fs207.realpathSync(resolved)}catch{return}let relative87=path337.relative(canonicalRoot,canonicalContract);if(!relative87||relative87===".."||relative87.startsWith(`..${path337.sep}`)||path337.isAbsolute(relative87)||path337.basename(canonicalContract)!==".pr-validation.json")return;let text=readBoundedText(canonicalContract);if(!text)return;try{return RepositoryValidationContractSchema.parse(JSON.parse(text))}catch{return}}async function resolveContractBaseProvenance(directory,prHeadSha,baseRef,baseSha){if(!baseRef&&!baseSha)return;if(!baseRef||!baseSha)throw Error("BLOCKED: Stage A contract authorization requires both base_ref and base_sha");let resolvedBase=await _internals277.resolveExactMergeBaseAsync(directory,baseRef,prHeadSha);if(!resolvedBase||resolvedBase.toLowerCase()!==baseSha.toLowerCase()||resolvedBase.toLowerCase()===prHeadSha.toLowerCase())throw Error("Stage A contract authorization requires base_sha to be the immutable merge base of base_ref and pr_head_sha");return{baseRef,baseSha:resolvedBase.toLowerCase()}}function readTrustedRepositoryValidationContract(directory,contractPath,provenance){if(!provenance)return;let current=readRepositoryValidationContract(directory,contractPath),currentText=readBoundedText(path337.resolve(directory,contractPath)),baseText=_internals277.readGitTextAtRevision(directory,provenance.baseSha,contractPath.replaceAll("\\","/").replace(/^\.\//,""));if(!current||!currentText||baseText===null||currentText!==baseText)return;return current}function isExactRepositoryContractValidator(directory,check3,provenance){if(!check3.validator_contract)return!1;let validator=readTrustedRepositoryValidationContract(directory,check3.validator_contract.path,provenance)?.validators.find((candidate2)=>candidate2.id===check3.validator_contract?.id);if(!validator||validator.category!==check3.category)return!1;let requestedDirectory=resolveContainedDirectory(directory,check3.working_directory??"."),declaredDirectory=resolveContainedDirectory(directory,validator.working_directory);return Boolean(requestedDirectory&&declaredDirectory)&&requestedDirectory?.absolute===declaredDirectory?.absolute&&validator.command.length===check3.command.length&&validator.command.every((part,index)=>part===check3.command[index])}function isExactObligationContractAuthorization(directory,obligation,check3,provenance){let identity=obligation.validatorContract;if(!identity||check3.validator_contract?.path!==identity.path||check3.validator_contract.id!==identity.id)return!1;let validator=readTrustedRepositoryValidationContract(directory,identity.path,provenance)?.validators.find(({id})=>id===identity.id),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),validatorWorkspace=validator?resolveContainedDirectory(directory,validator.working_directory):void 0;if(!validator||validator.category!==obligation.category||validatorWorkspace?.absolute!==workspace?.absolute)return!1;if(!obligation.source.startsWith("package.json#")||!workspace)return!1;let scriptName=obligation.source.slice(13),packageText=readBoundedText(path337.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&declared.length===validator.command.length&&declared.every((part,index)=>part===validator.command[index])&&(packageManagerSelectsExactScript(check3.command,scriptName)||declared.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])))}catch{return!1}}function isSafeContractCommand(command){let executable=path337.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");return!BLOCKED_EXECUTABLES.has(executable)&&!command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))&&!command.some((arg)=>/^(?:-h|--help|--version|help|version|--dry-run|--if-present)$/i.test(arg))&&!(["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))}function isAllowedRepositoryExecutable(directory,workingDirectory,executable,contractValidated){if(!/[\\/]/.test(executable))return!0;if(path337.isAbsolute(executable))return!1;let workspace=resolveContainedDirectory(directory,workingDirectory);if(!workspace)return!1;let resolved=path337.resolve(workspace.absolute,executable),canonicalExecutable;try{canonicalExecutable=fs207.realpathSync(resolved)}catch{return!1}let canonicalRoot=(()=>{try{return fs207.realpathSync(path337.resolve(directory))}catch{return path337.resolve(directory)}})(),relative87=path337.relative(canonicalRoot,canonicalExecutable);if(relative87===".."||relative87.startsWith(`..${path337.sep}`)||path337.isAbsolute(relative87))return!1;let basename54=path337.basename(canonicalExecutable).toLowerCase().replace(/\.(?:cmd|bat|exe)$/,"");if(!contractValidated&&!["gradlew","mvnw"].includes(basename54))return!1;return fs207.statSync(canonicalExecutable).isFile()}function normalizedExecutable(command){return path337.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"")}function parseSimpleRepositoryScript(script){if(/[;&|><`\r\n]/.test(script)||script.includes("$(")||script.includes("${"))return;let tokens=script.match(/"(?:\\.|[^"\\])*"|'[^']*'|[^\s]+/g)?.map((token)=>{if(token.startsWith('"')&&token.endsWith('"')||token.startsWith("'")&&token.endsWith("'"))return token.slice(1,-1);return token})??[];return tokens.length>0?tokens:void 0}function packageManagerSelectedScriptName(command){let executable=normalizedExecutable(command);if(!["npm","bun","pnpm","yarn"].includes(executable))return;let positional=command.slice(1,command.indexOf("--")>=0?command.indexOf("--"):void 0).filter((arg)=>!arg.startsWith("-"));if(executable==="npm")return["run","run-script"].includes(positional[0]??"")?positional[1]:void 0;if(executable==="bun")return positional[0]==="run"?positional[1]:void 0;return positional[0]==="run"?positional[1]:positional[0]}function packageManagerSelectsExactScript(command,scriptName){return packageManagerSelectedScriptName(command)===scriptName}function isExactRepositoryPackageManagerScript(directory,workingDirectory,category,command){let scriptName=packageManagerSelectedScriptName(command),workspace=resolveContainedDirectory(directory,workingDirectory);if(!scriptName||!workspace||!categoryMatchesScriptName(category,scriptName))return!1;let packageText=readBoundedText(path337.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&isPlausibleStageACommand(category,declared))}catch{return!1}}function commandMatchesObligationSource(directory,obligation,check3,contractValidated){let executable=normalizedExecutable(check3.command),effectiveExecutable=executable==="npx"&&check3.command[1]?path337.basename(check3.command[1]).toLowerCase():executable,source=obligation.source;if(source.includes(".pr-validation.json#")){let separator=source.lastIndexOf("#"),contractPath=source.slice(0,separator),validatorId=source.slice(separator+1);return contractValidated&&check3.validator_contract?.id===validatorId&&check3.validator_contract?.path.replaceAll("\\","/").replace(/^\.\//,"")===contractPath.replace(/^\.\//,"")}if(source.startsWith("package.json#")){let scriptName=source.slice(13),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),packageText=workspace?readBoundedText(path337.join(workspace.absolute,"package.json")):void 0;if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared)&&declared?.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])||packageManagerSelectsExactScript(check3.command,scriptName)}catch{return!1}}if(source==="Cargo.toml")return effectiveExecutable==="cargo";if(source==="go.mod")return effectiveExecutable==="go";if(source==="pom.xml")return["mvn","mvnw"].includes(effectiveExecutable);if(/^build\.gradle(?:\.kts)?$/.test(source))return["gradle","gradlew"].includes(effectiveExecutable);if(/^(?:Makefile|makefile)$/.test(source))return effectiveExecutable==="make";if(source==="CMakeLists.txt")return effectiveExecutable==="cmake";if(source==="Package.swift")return["swift","swiftc"].includes(effectiveExecutable);if(source==="setup.py"||source==="pyproject.toml#build-system")return["python","python3"].includes(effectiveExecutable);if(/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(source))return["dotnet","msbuild"].includes(effectiveExecutable);if(/\.(?:xcodeproj|xcworkspace)$/i.test(source))return effectiveExecutable==="xcodebuild";let sourceExecutables={"tsconfig.json":["tsc"],"pyrightconfig.json":["pyright"],".flowconfig":["flow"],"phpstan.neon":["phpstan"],"phpstan.neon.dist":["phpstan"],"psalm.xml":["psalm"],"psalm.xml.dist":["psalm"],"mypy.ini":["mypy"],"pyproject.toml#mypy":["mypy"],"biome.json":["biome"],"biome.jsonc":["biome"],"ruff.toml":["ruff"],".ruff.toml":["ruff"],"pyproject.toml#ruff":["ruff"],".rubocop.yml":["rubocop"],".swiftlint.yml":["swiftlint"],".golangci.yml":["golangci-lint"],".golangci.yaml":["golangci-lint"],".stylelintrc":["stylelint"],".stylelintrc.json":["stylelint"]};if(/^(?:\.eslintrc|eslint\.config\.)/.test(source))return effectiveExecutable==="eslint";return sourceExecutables[source]?.includes(effectiveExecutable)??!1}function discoverApplicableStageAObligations(directory,contractBase){let root=path337.resolve(directory),canonicalRoot=(()=>{try{return fs207.realpathSync(root)}catch{return root}})(),candidateRoots=[],seenRoots=new Set,discoveryOverflow,addCandidateRoot=(candidate2)=>{if(candidateRoots.length>=256){discoveryOverflow="Stage A repository discovery exceeded 256 contained workspace roots";return}try{if(!fs207.statSync(candidate2).isDirectory())return;let canonicalCandidate=fs207.realpathSync(candidate2),relative87=path337.relative(canonicalRoot,canonicalCandidate);if(relative87.startsWith(`..${path337.sep}`)||relative87===".."||path337.isAbsolute(relative87)||seenRoots.has(canonicalCandidate))return;seenRoots.add(canonicalCandidate),candidateRoots.push(canonicalCandidate)}catch{}},addWorkspacePattern=(pattern)=>{let normalized=pattern.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!normalized||normalized.startsWith("!")||path337.posix.isAbsolute(normalized)||normalized.split("/").includes("..")){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}if(!normalized.includes("*")){addCandidateRoot(path337.resolve(root,normalized));return}let wildcard=normalized.match(/^([^*?[\]]+)\/\*\/?$/);if(!wildcard){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}let container=path337.resolve(root,wildcard[1]);try{let entries2=fs207.readdirSync(container,{withFileTypes:!0});if(entries2.length>256){discoveryOverflow=`Stage A workspace container ${wildcard[1]} exceeds the 256-entry bounded discovery limit`;return}for(let entry of entries2)if(entry.isDirectory())addCandidateRoot(path337.join(container,entry.name))}catch{}};addCandidateRoot(root);for(let containerName of["packages","apps","services","libs","crates"])addWorkspacePattern(`${containerName}/*`);let rootPackageText=readPresentRepositoryText(canonicalRoot,path337.join(root,"package.json"),"root package.json workspace declaration");if(rootPackageText)try{let value=JSON.parse(rootPackageText),workspacePatterns=Array.isArray(value.workspaces)?value.workspaces:value.workspaces?.packages;for(let pattern of workspacePatterns??[])if(typeof pattern==="string")addWorkspacePattern(pattern)}catch{discoveryOverflow="Stage A cannot safely inspect malformed root package.json workspace metadata"}let pnpmWorkspaceText=readPresentRepositoryText(canonicalRoot,path337.join(root,"pnpm-workspace.yaml"),"pnpm-workspace.yaml declaration");for(let match of pnpmWorkspaceText?.matchAll(/^\s*-\s*['"]?([^'"#\r\n]+?)['"]?\s*$/gm)??[])addWorkspacePattern(match[1]);let cargoMembers=readPresentRepositoryText(canonicalRoot,path337.join(root,"Cargo.toml"),"Cargo.toml workspace declaration")?.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/m)?.[1];for(let match of cargoMembers?.matchAll(/['"]([^'"]+)['"]/g)??[])addWorkspacePattern(match[1]);let mavenText=readPresentRepositoryText(canonicalRoot,path337.join(root,"pom.xml"),"pom.xml module declaration");for(let match of mavenText?.matchAll(/<module>\s*([^<]+?)\s*<\/module>/gi)??[])addWorkspacePattern(match[1]);let goWorkText=readPresentRepositoryText(canonicalRoot,path337.join(root,"go.work"),"go.work workspace declaration");for(let match of goWorkText?.matchAll(/^\s*(?:use\s+)?(\.\.?\/[^\s/]+(?:\/[^\s]+)*)\s*$/gm)??[])addWorkspacePattern(match[1]);for(let settingsName of["settings.gradle","settings.gradle.kts"]){let settingsText=readPresentRepositoryText(canonicalRoot,path337.join(root,settingsName),`${settingsName} workspace declaration`);for(let includeMatch of settingsText?.matchAll(/\binclude\s*\(?([^\r\n)]+)/g)??[])for(let projectMatch of includeMatch[1].matchAll(/['"]:?(.*?)['"]/g)){let projectPath=projectMatch[1].replaceAll(":","/");if(projectPath)addWorkspacePattern(projectPath)}}let obligations=new Map,addObligation=(category,candidateRoot,source,validatorContract)=>{let workspace=path337.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||".",id=`${category}:${workspace}:${source}`;if(!obligations.has(id)&&obligations.size>=256){discoveryOverflow="Stage A repository discovery exceeded 256 concrete validation obligations";return}obligations.set(id,{id,category,workingDirectory:workspace,source,...validatorContract?{validatorContract}:{}})},buildFiles=new Set(["Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","Makefile","makefile","CMakeLists.txt","Package.swift","setup.py"]),typecheckFiles=new Set(["tsconfig.json","pyrightconfig.json",".flowconfig","phpstan.neon","phpstan.neon.dist","psalm.xml","psalm.xml.dist","mypy.ini"]),lintFiles=new Set(["biome.json","biome.jsonc",".eslintrc",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml",".eslintrc.js",".eslintrc.cjs",".eslintrc.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","ruff.toml",".ruff.toml",".rubocop.yml",".swiftlint.yml",".golangci.yml",".golangci.yaml",".stylelintrc",".stylelintrc.json"]);for(let candidateRoot of candidateRoots){let entries2=[];try{if(entries2=fs207.readdirSync(candidateRoot,{withFileTypes:!0}),entries2.length>2048){discoveryOverflow=`Stage A workspace ${path337.relative(canonicalRoot,candidateRoot)||"."} exceeds the 2048-entry bounded manifest scan`;continue}}catch{continue}for(let entry of entries2){if(entry.isFile()&&buildFiles.has(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isFile()&&typecheckFiles.has(entry.name))addObligation("typecheck",candidateRoot,entry.name);if(entry.isFile()&&lintFiles.has(entry.name))addObligation("lint",candidateRoot,entry.name);if(entry.isFile()&&/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isDirectory()&&/\.(?:xcodeproj|xcworkspace)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name)}let contractPath=path337.join(candidateRoot,".pr-validation.json"),contractRelative=path337.relative(canonicalRoot,contractPath).replaceAll("\\","/"),untrustedContract=readRepositoryValidationContract(canonicalRoot,contractRelative),contract=readTrustedRepositoryValidationContract(canonicalRoot,contractRelative,contractBase);if(fs207.existsSync(contractPath)&&!untrustedContract)discoveryOverflow=`Stage A found an invalid, oversized, unreadable, or escaping validation contract at ${contractRelative}`;else if(untrustedContract&&!contract)discoveryOverflow=`Stage A validation contract at ${contractRelative} must be unchanged from the immutable merge base named by base_ref and base_sha`;let contractValidatorsCoveredByScripts=new Set,packageText=readPresentRepositoryText(canonicalRoot,path337.join(candidateRoot,"package.json"),`${path337.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json manifest`);if(packageText)try{let value=JSON.parse(packageText);for(let[script,commandText]of Object.entries(value.scripts??{})){let declaredCommand=typeof commandText==="string"?parseSimpleRepositoryScript(commandText):void 0;for(let category of OPTIONAL_STAGE_A_CATEGORIES){if(!categoryMatchesScriptName(category,script))continue;let authorizingValidator=contract?.validators.find((validator)=>{let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);return validator.category===category&&validatorWorkspace?.absolute===candidateRoot&&(!declaredCommand||declaredCommand.length===validator.command.length&&declaredCommand.every((part,index)=>part===validator.command[index]))});if(!declaredCommand){if(!authorizingValidator)discoveryOverflow=`Stage A opaque package script ${path337.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json#${script} requires a trusted base-identical contract validator for ${category}`;continue}if(isPlausibleStageACommand(category,declaredCommand)||Boolean(authorizingValidator)){if(addObligation(category,candidateRoot,`package.json#${script}`,authorizingValidator?{path:contractRelative,id:authorizingValidator.id}:void 0),authorizingValidator)contractValidatorsCoveredByScripts.add(authorizingValidator.id)}}}}catch{discoveryOverflow=`Stage A cannot safely inspect malformed package manifest at ${path337.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json`}let pyprojectText=readPresentRepositoryText(canonicalRoot,path337.join(candidateRoot,"pyproject.toml"),`${path337.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/pyproject.toml manifest`);if(pyprojectText?.match(/\[build-system\]/i))addObligation("build",candidateRoot,"pyproject.toml#build-system");if(pyprojectText?.match(/\[(?:tool\.)?mypy\]/i))addObligation("typecheck",candidateRoot,"pyproject.toml#mypy");if(pyprojectText?.match(/\[tool\.ruff(?:\.|\])/i))addObligation("lint",candidateRoot,"pyproject.toml#ruff");for(let validator of contract?.validators??[]){if(contractValidatorsCoveredByScripts.has(validator.id))continue;if(OPTIONAL_STAGE_A_CATEGORIES.includes(validator.category)){let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);if(!validatorWorkspace)continue;addObligation(validator.category,validatorWorkspace.absolute,`${contractRelative}#${validator.id}`)}}}if(discoveryOverflow)throw Error(`BLOCKED: ${discoveryOverflow}`);return[...obligations.values()]}function discoverApplicableStageACategories(directory,contractBase){let applicable=new Set(discoverApplicableStageAObligations(directory,contractBase).map(({category})=>category));return OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicable.has(category))}async function executeRunPrFeedbackStageA(args2,directory,context={}){let parsed=RunPrFeedbackStageAArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback Stage A request: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);if(!context.sessionID?.trim())return failure2("PR-feedback Stage A requires an active sessionID");let categories=parsed.data.checks.map((check3)=>check3.category);for(let requiredSingleton of ALWAYS_REQUIRED_CATEGORIES)if(categories.filter((category)=>category===requiredSingleton).length!==1)return failure2(`Stage A requires exactly one ${requiredSingleton} receipt`);let contractBase;try{contractBase=await resolveContractBaseProvenance(directory,parsed.data.pr_head_sha,parsed.data.base_ref,parsed.data.base_sha)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableObligations;try{applicableObligations=_internals277.discoverApplicableStageAObligations(directory,contractBase)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableCategories=OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicableObligations.some((obligation)=>obligation.category===category)),matchedObligationIds=new Set,selectedObligations=new Map,normalizedCheckDirectories=new Map;for(let check3 of parsed.data.checks){let workspace=resolveContainedDirectory(directory,check3.working_directory??".");if(!workspace)return failure2(`Stage A ${check3.category} working_directory is not a contained repository workspace`);if(normalizedCheckDirectories.set(check3,workspace.relative),!OPTIONAL_STAGE_A_CATEGORIES.includes(check3.category))continue;let candidates=applicableObligations.filter((obligation)=>obligation.category===check3.category&&obligation.workingDirectory===workspace.relative);if(candidates.length===0&&!check3.obligation_id)continue;let selected=check3.obligation_id?candidates.find((candidate2)=>candidate2.id===check3.obligation_id):candidates.length===1?candidates[0]:void 0;if(!selected)return failure2(`Stage A ${check3.category} must name one exact discovered obligation_id for workspace ${workspace.relative}: ${candidates.map(({id})=>id).join(", ")||"none discovered"}`);if(matchedObligationIds.has(selected.id))return failure2(`Stage A repeats discovered obligation ${selected.id}`);matchedObligationIds.add(selected.id),selectedObligations.set(check3,selected),check3.obligation_id=selected.id,check3.working_directory=workspace.relative}let missingObligations=applicableObligations.filter(({id})=>!matchedObligationIds.has(id));if(missingObligations.length>0)return failure2(`Stage A is missing concrete repository validation obligations: ${missingObligations.map(({id})=>id).join(", ")}`);let diffCheck=parsed.data.checks.find((check3)=>check3.category==="diff-check");if(!diffCheck||!isExactDiffCheck(diffCheck.command))return failure2('Stage A diff-check must execute array-form ["git", "diff", "--check"]');for(let check3 of parsed.data.checks){let directContractValidated=isExactRepositoryContractValidator(directory,check3,contractBase),selectedObligation=selectedObligations.get(check3),obligationContractValidated=selectedObligation?isExactObligationContractAuthorization(directory,selectedObligation,check3,contractBase):!1,contractValidated=directContractValidated||obligationContractValidated;if(selectedObligation?.validatorContract&&!obligationContractValidated)return failure2(`Stage A obligation ${selectedObligation.id} requires exact validator_contract ${selectedObligation.validatorContract.path}#${selectedObligation.validatorContract.id}`);let executable=normalizedExecutable(check3.command);if(selectedObligation&&!commandMatchesObligationSource(directory,selectedObligation,check3,contractValidated))return failure2(`Stage A command does not prove its exact source obligation ${selectedObligation.id}`);if(!isPlausibleStageACommand(check3.category,check3.command)&&!(contractValidated&&isSafeContractCommand(check3.command)))return failure2(`Stage A ${check3.category} command is not a recognized non-publishing ${check3.category} validation command`);let isPackageManagerCommand=["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&check3.command[1]==="run";if(!selectedObligation&&isPackageManagerCommand&&(check3.category!=="reproduction"||!isExactRepositoryPackageManagerScript(directory,normalizedCheckDirectories.get(check3)??".",check3.category,check3.command)))return failure2(`Stage A ${check3.category} package-manager command must select one exact inspected repository script`);if(!isAllowedRepositoryExecutable(directory,normalizedCheckDirectories.get(check3)??".",check3.command[0],contractValidated))return failure2(`Stage A rejects escaping or undeclared repository wrapper executables: ${check3.command[0]}`)}let normalizedCommands=parsed.data.checks.map((check3)=>`${check3.obligation_id??check3.category}\x00${normalizedCheckDirectories.get(check3)??"."}\x00${check3.command.join("\x00")}`.toLowerCase());if(new Set(normalizedCommands).size!==normalizedCommands.length)return failure2("Stage A categories require distinct commands; one command cannot prove multiple obligations");let reproduction=parsed.data.checks.find((check3)=>check3.category==="reproduction");if(!reproduction?.targets?.length)return failure2("Stage A reproduction requires at least one explicit test/regression target");let reproductionSelectors=reproductionSelectorValues(reproduction.command),missingTargets=reproduction.targets.filter((target)=>![...reproductionSelectors].some((selector)=>selector===target||selector.replaceAll("\\","/")===target.replaceAll("\\","/")));if(missingTargets.length>0)return failure2(`Stage A reproduction command does not select declared target(s): ${missingTargets.join(", ")}`);for(let target of reproduction.targets){if(!/[\\/]/.test(target))continue;let pathTarget=target.split("::",1)[0].replace(/:\d+(?::\d+)?$/,""),resolved=path337.resolve(directory,pathTarget),relative87=path337.relative(path337.resolve(directory),resolved);if(!relative87||relative87.startsWith("..")||path337.isAbsolute(relative87)||!fs207.existsSync(resolved)||!fs207.statSync(resolved).isFile())return failure2(`Stage A reproduction target is not a contained existing file: ${target}`)}try{let state=await assertPrFeedbackVerificationSettled(directory,context.sessionID),feedbackTargets=reproduction.feedback_targets??[],mappedFeedbackIds=feedbackTargets.map((mapping)=>mapping.feedback_item_id);if(mappedFeedbackIds.length!==new Set(mappedFeedbackIds).size||mappedFeedbackIds.length!==(state.prFeedbackInventory?.length??0)||!mappedFeedbackIds.every((itemId,index)=>itemId===state.prFeedbackInventory?.[index])||feedbackTargets.some((mapping)=>!reproduction.targets?.includes(mapping.target)))return failure2("Stage A reproduction requires one exact target and expected-behavior mapping for every immutable feedback item in declared order");if(state.prHeadSha!==parsed.data.pr_head_sha)return failure2(`PR_FEEDBACK head mismatch: expected ${state.prHeadSha??"(unbound)"}, received ${parsed.data.pr_head_sha}`);await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,"PR_FEEDBACK");let beforeDigest=await _internals277.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!beforeDigest)return failure2("Could not compute a bounded Stage A revision digest");let boundHead=(await _internals277.resolveCurrentGitHeadAsync(directory))?.trim(),boundControlState=await _internals277.resolveGitControlStateDigestAsync(directory);if(!boundHead||!boundControlState)return failure2("Could not bind Stage A to the current Git HEAD, refs, config, and index state");let results=[],receipts=[];for(let check3 of parsed.data.checks){let commandRevision=await _internals277.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),commandControl=await _internals277.resolveGitControlStateDigestAsync(directory);if(commandRevision!==beforeDigest||commandControl!==boundControlState||(await _internals277.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A Git or content state changed before ${check3.category}; restart the complete sequence`,results,directory,context.sessionID);let started=Date.now(),[executable,...commandArgs]=check3.command,checkDirectory=resolveContainedDirectory(directory,check3.working_directory??".");if(!checkDirectory)return failure2(`Stage A ${check3.category} workspace disappeared before execution`,results,directory,context.sessionID);let result;try{result=await _internals277.runExternalTool({executable,args:commandArgs,cwd:checkDirectory.absolute,timeoutMs:check3.timeout_ms??120000,maxStdoutBytes:MAX_OUTPUT_BYTES9,maxStderrBytes:MAX_OUTPUT_BYTES9})}catch(error93){let afterThrowRevision=await _internals277.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterThrowControl=await _internals277.resolveGitControlStateDigestAsync(directory);if(afterThrowRevision!==beforeDigest||afterThrowControl!==boundControlState||(await _internals277.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} threw after mutating content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);return failure2(`Stage A ${check3.category} execution threw: ${error93 instanceof Error?error93.message:String(error93)}`,results,directory,context.sessionID)}let durationMs=Date.now()-started;results.push({category:check3.category,working_directory:checkDirectory.relative,...check3.obligation_id?{obligation_id:check3.obligation_id}:{},command:check3.command,status:result.status,exit_code:result.exitCode,duration_ms:durationMs,stdout:result.stdout,stderr:result.stderr,stdout_truncated:result.stdoutTruncated,stderr_truncated:result.stderrTruncated,...result.message?{message:result.message}:{}});let afterCommandRevision=await _internals277.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterCommandControl=await _internals277.resolveGitControlStateDigestAsync(directory);if(afterCommandRevision!==beforeDigest||afterCommandControl!==boundControlState||(await _internals277.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} mutated content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);if(result.status!=="completed"||result.exitCode!==0)return failure2(`Stage A ${check3.category} failed (${result.status}, exit ${result.exitCode??"unknown"})`,results,directory,context.sessionID);if(check3.validator_contract&&!`${result.stdout}
7487
7487
  ${result.stderr}`.trim())return failure2(`Stage A repository-contract validator ${check3.validator_contract.id} produced no machine-observable evidence`,results,directory,context.sessionID);if(check3.category==="reproduction"&&outputReportsZeroTests(result))return failure2("Stage A reproduction produced truncated proof or reported that zero tests executed",results,directory,context.sessionID);if(check3.category==="reproduction"&&!`${result.stdout}
7488
7488
  ${result.stderr}`.trim())return failure2("Stage A reproduction produced no machine-observable execution evidence",results,directory,context.sessionID);receipts.push({category:check3.category,workingDirectory:checkDirectory.relative,...check3.obligation_id?{obligationId:check3.obligation_id}:{},...check3.validator_contract?{validatorContract:{path:check3.validator_contract.path,id:check3.validator_contract.id}}:{},command:check3.command,...check3.targets?{targets:check3.targets}:{},...check3.feedback_targets?{feedbackTargets:check3.feedback_targets.map((mapping)=>({feedbackItemId:mapping.feedback_item_id,target:mapping.target,expectedBehavior:mapping.expected_behavior,proofKind:mapping.proof_kind}))}:{},durationMs})}let afterDigest=await _internals277.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!afterDigest||afterDigest!==beforeDigest)return failure2("Stage A changed the working-tree revision; rerun all Stage A checks on the resulting diff",results,directory,context.sessionID);if(await _internals277.resolveGitControlStateDigestAsync(directory)!==boundControlState||(await _internals277.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2("Stage A changed HEAD, refs, Git config, or index state; rerun the complete sequence",results,directory,context.sessionID);await recordPrFeedbackStageA(directory,context.sessionID,afterDigest,receipts,{applicableCategories,applicableObligations});let successPayload={success:!0,pr_head_sha:parsed.data.pr_head_sha,revision_digest:afterDigest,checks:results.map(summarizeCheckEntry)};return JSON.stringify(successPayload,null,2)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}}var _internals277={runExternalTool,storeSummary,readGitTextAtRevision,resolveExactMergeBase,resolveExactMergeBaseAsync,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveGitControlStateDigest,resolveGitControlStateDigestAsync,resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,isPlausibleStageACommand,discoverApplicableStageACategories,discoverApplicableStageAObligations,commandMatchesObligationSource},run_pr_feedback_stage_a=createSwarmTool({description:"Execute and persist mandatory PR-feedback Stage A diff-check and targeted reproduction receipts plus every build, typecheck, or lint check mechanically applicable to this repository, on one content-bound revision.",args:{pr_head_sha:RunPrFeedbackStageAArgsSchema.shape.pr_head_sha,checks:RunPrFeedbackStageAArgsSchema.shape.checks},execute:executeRunPrFeedbackStageA});init_sast_scan();init_zod();init_plan_schema();init_qa_gate_profile();init_file_locks();import*as fs208 from"node:fs";import*as path338 from"node:path";init_ledger();init_manager();init_planning_profile();init_utils3();init_scope_binding();init_effective_spec();init_project_boundary();init_create_tool();function executionProfilesEqual(a,b){return a.parallelization_enabled===b.parallelization_enabled&&a.max_concurrent_tasks===b.max_concurrent_tasks&&a.council_parallel===b.council_parallel&&a.locked===b.locked&&a.auto_proceed===b.auto_proceed&&a.commit_after_each_completed_task===b.commit_after_each_completed_task&&a.planning_profile===b.planning_profile}function isLedgerProjectionReconcileRequest(args2){return args2.reconcile_ledger_projection===!0}function isPureLedgerProjectionReconcileRequest(args2){return isLedgerProjectionReconcileRequest(args2)&&args2.reset_statuses!==!0&&(args2.removed_task_ids?.length??0)===0&&(args2.removal_reason?.trim().length??0)===0&&args2.confirm_destructive_reset!==!0&&args2.confirm_identity_change!==!0&&args2.confirm_requirement_coverage_gaps!==!0}function derivePhaseStatusesForComparison(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((task2)=>task2.status==="completed"))phase.status="complete";else if(tasks.some((task2)=>task2.status==="in_progress"))phase.status="in_progress";else if(tasks.some((task2)=>task2.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function normalizePlanForReconcileComparison(plan){return{schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:plan.execution_profile?{parallelization_enabled:plan.execution_profile.parallelization_enabled,max_concurrent_tasks:plan.execution_profile.max_concurrent_tasks,council_parallel:plan.execution_profile.council_parallel,locked:plan.execution_profile.locked,auto_proceed:plan.execution_profile.auto_proceed,commit_after_each_completed_task:plan.execution_profile.commit_after_each_completed_task,...plan.execution_profile.planning_profile!==void 0?{planning_profile:plan.execution_profile.planning_profile}:{}}:void 0,phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,tasks:phase.tasks.map((task2)=>({id:task2.id,phase:task2.phase,status:task2.status,size:task2.size,description:task2.description,depends:task2.depends,acceptance:task2.acceptance,files_touched:task2.files_touched,fr_refs:task2.fr_refs}))}))}}async function readLedgerTailCapture(directory){let events=await readLedgerEvents(directory),tail2=events[events.length-1];if(!tail2)return null;return{seq:tail2.seq,plan_hash_after:tail2.plan_hash_after}}function materializeResolvedExecutionProfile(profile,persistedPlanningProfile){if(persistedPlanningProfile===void 0){let{planning_profile:_planningProfile,...withoutPlanningProfile}=profile;return withoutPlanningProfile}return{...profile,planning_profile:persistedPlanningProfile}}function canRatchetLockedPlanningProfile(existingProfile,requestedProfile){return existingProfile.planning_profile==="balanced"&&requestedProfile.planning_profile==="strict"&&existingProfile.parallelization_enabled===requestedProfile.parallelization_enabled&&existingProfile.max_concurrent_tasks===requestedProfile.max_concurrent_tasks&&existingProfile.council_parallel===requestedProfile.council_parallel&&existingProfile.locked===requestedProfile.locked&&existingProfile.auto_proceed===requestedProfile.auto_proceed&&existingProfile.commit_after_each_completed_task===requestedProfile.commit_after_each_completed_task}function evaluateRequirementCoverage(specContent,args2){if(!specContent)return null;let requirements=extractRequirements(specContent);if(requirements.length===0)return null;let covered=[],missing=[];for(let requirement of requirements){let mappedTaskIds=[],idPattern=new RegExp(`\\b${requirement.id}\\b`,"i");for(let phase of args2.phases)for(let task2 of phase.tasks){let taskText=`${task2.description}
7489
- ${task2.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=task2.fr_refs?.includes(requirement.id)??!1;if(matchesFreeText||matchesFrRefs)mappedTaskIds.push(task2.id)}let entry={id:requirement.id,obligation:requirement.obligation,text:requirement.text,mapped_task_ids:mappedTaskIds};if(mappedTaskIds.length>0)covered.push(entry);else missing.push(entry)}let blockingMissing=missing.filter((entry)=>entry.obligation==="MUST"||entry.obligation==="SHALL");return{status:blockingMissing.length>0?args2.confirm_requirement_coverage_gaps===!0?"override":"failed":"passed",total_requirements:requirements.length,covered_count:covered.length,missing_count:missing.length,blocking_missing_count:blockingMissing.length,covered,missing,blocking_missing:blockingMissing}}function detectPlaceholderContent(args2){let issues=[],placeholderPattern=/^\[\w[\w\s]*\]$/;if(placeholderPattern.test(args2.title.trim()))issues.push(`Plan title appears to be a template placeholder: "${args2.title}"`);for(let phase of args2.phases){if(placeholderPattern.test(phase.name.trim()))issues.push(`Phase ${phase.id} name appears to be a template placeholder: "${phase.name}"`);for(let task2 of phase.tasks)if(placeholderPattern.test(task2.description.trim()))issues.push(`Task ${task2.id} description appears to be a template placeholder: "${task2.description}"`)}return issues}function validateTargetWorkspace(target,source){if(target===void 0||target===null)return`Target workspace is required: ${source} not provided`;let trimmed=target.trim();if(trimmed.length===0)return`Target workspace cannot be empty or whitespace: ${source}`;if(trimmed.replace(/\\/g,"/").includes(".."))return`Target workspace cannot contain path traversal: ${source} contains ".."`;return}async function executeSavePlan(args2,fallbackDir){let validationErrors=[];for(let phase of args2.phases){if(!Number.isInteger(phase.id)||phase.id<=0)validationErrors.push(`Phase ${phase.id} has invalid id: must be a positive integer`);let taskIdPattern=/^\d+\.\d+(\.\d+)*$/;for(let task2 of phase.tasks)if(!taskIdPattern.test(task2.id))validationErrors.push(`Task '${task2.id}' in phase ${phase.id} has invalid id format: must match N.M pattern (e.g. '1.1', '2.3')`)}if(validationErrors.length>0)return{success:!1,message:"Plan rejected: invalid phase or task IDs",errors:validationErrors,recovery_guidance:'Phase IDs must be positive integers: 1, 2, 3 (not 0, -1, or decimals). Task IDs must use N.M format: "1.1", "2.3", "3.1". Call save_plan again with corrected ids. Never write .swarm/plan.json or .swarm/plan.md directly.'};let placeholderIssues=detectPlaceholderContent(args2);if(placeholderIssues.length>0)return{success:!1,message:"Plan rejected: contains template placeholder content",errors:placeholderIssues,recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};let targetWorkspace=args2.working_directory??fallbackDir,workspaceError=validateTargetWorkspace(targetWorkspace,args2.working_directory?"working_directory":"fallbackDir");if(workspaceError)return{success:!1,message:"Target workspace validation failed: provide working_directory parameter to save_plan",errors:[workspaceError],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};try{assertProjectRoot(targetWorkspace)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message],recovery_guidance:"Pass the project root, or add an explicit local .git/.opencode project boundary before retrying save_plan."}}if(args2.working_directory&&fallbackDir){let resolvedTarget=path338.resolve(args2.working_directory),resolvedRoot=path338.resolve(fallbackDir),fallbackExists=!1;try{fs208.accessSync(resolvedRoot,fs208.constants.F_OK),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(isStrictPathDescendant(resolvedTarget,resolvedRoot)){if(!hasExplicitProjectBoundary(resolvedTarget))return{success:!1,message:`working_directory must be the project root. Got "${args2.working_directory}" (resolves to "${resolvedTarget}"), which is a subdirectory of fallback "${resolvedRoot}". Omit working_directory or pass the project root explicitly.`,errors:[`working_directory "${resolvedTarget}" is a subdirectory of fallback "${resolvedRoot}"`],recovery_guidance:`Pass working_directory: "${resolvedRoot}" or omit the field entirely.`}}}}let dir=targetWorkspace,reconcileLedgerProjection=isLedgerProjectionReconcileRequest(args2);if(reconcileLedgerProjection&&!isPureLedgerProjectionReconcileRequest(args2))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_INVALID: reconcile_ledger_projection only permits an unchanged semantic re-save.",errors:["Remove reset_statuses, task-removal acknowledgements, identity overrides, and requirement-coverage overrides before retrying reconcile_ledger_projection."],recovery_guidance:"Retry with reconcile_ledger_projection: true only when save_plan is re-saving the same identity, task graph, statuses, and execution_profile to reconverge a stale projection."};let existingStatusMap=new Map,existingFilesMap=new Map,priorTaskIds=new Set,preservedExecutionProfile,existingPlan=null;try{existingPlan=await loadPlanJsonOnly(dir)}catch{}if(existingPlan){for(let phase of existingPlan.phases)for(let task2 of phase.tasks)priorTaskIds.add(task2.id),existingFilesMap.set(task2.id,[...task2.files_touched]);if(!args2.reset_statuses)for(let phase of existingPlan.phases)for(let task2 of phase.tasks)existingStatusMap.set(task2.id,task2.status);preservedExecutionProfile=existingPlan.execution_profile}let reconcileLedgerTailCapture=reconcileLedgerProjection?await readLedgerTailCapture(dir).catch(()=>null):null,specMtime=reconcileLedgerProjection?existingPlan?.specMtime:void 0,specHash=reconcileLedgerProjection?existingPlan?.specHash:void 0,specContent,planningProfileResolution=resolvePlanningProfile({directory:dir,incomingExecutionProfile:args2.execution_profile,existingExecutionProfile:preservedExecutionProfile,resetStatuses:args2.reset_statuses}),effectivePlanningProfile=planningProfileResolution.effective,persistedPlanningProfile=planningProfileResolution.persisted;if(existingPlan?.execution_profile?.locked&&args2.execution_profile!==void 0&&!args2.reset_statuses){let requestedProfile=ExecutionProfileSchema.safeParse({...existingPlan.execution_profile,...args2.execution_profile});if(!requestedProfile.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:requestedProfile.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};let requestedMaterializedProfile=materializeResolvedExecutionProfile(requestedProfile.data,persistedPlanningProfile);if(executionProfilesEqual(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=existingPlan.execution_profile;else if(canRatchetLockedPlanningProfile(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=requestedMaterializedProfile;else return{success:!1,message:"EXECUTION_PROFILE_LOCKED: The execution_profile for this plan is locked and cannot be changed.",errors:["execution_profile.locked is true — only a balanced→strict planning_profile ratchet is allowed without reset_statuses. All other profile changes are rejected."],recovery_guidance:"Remove the execution_profile field from this save_plan call to preserve the locked profile, or use reset_statuses: true to start fresh (this clears the lock). Never modify execution_profile directly in plan.json."}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_SPEC_GATE!=="1"){let spec=readEffectiveSpecSync(targetWorkspace);if(!spec&&effectivePlanningProfile==="strict")return{success:!1,message:"SPEC_REQUIRED: an effective spec (native .swarm/spec.md, OpenSpec openspec/specs or openspec/changes, or Spec-Kit .specify/) must exist before saving a plan.",errors:["No effective spec found — .swarm/spec.md is absent and no OpenSpec/Spec-Kit projection succeeded."],recovery_guidance:"Obtain explicit user consent, then run /swarm sdd project (agent-invocable) to materialize an effective spec from SDD sources. If .swarm/spec.md already exists, pass --overwrite after consent. Alternatively, run /swarm specify to author a native spec. Never write .swarm/plan.json or .swarm/plan.md directly."};if(spec){specMtime=spec.mtime??void 0,specHash=spec.hash,specContent=spec.content;try{let snapshotPath=path338.join(targetWorkspace,".swarm","spec-snapshot.md");await fs208.promises.writeFile(snapshotPath,spec.content,"utf-8")}catch{}}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_GATE_SELECTION!=="1"){let profileLookup;try{profileLookup=getProfileLookupForIdentity(targetWorkspace,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not verify the durable QA gate selection.",errors:[error93 instanceof Error?`QA gate profile store read failed: ${error93.message}`:"QA gate profile store read failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry get_qa_gate_profile and save_plan with the same swarm_id and title."}}if(profileLookup.kind==="missing")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not create the default balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile bootstrap failed: ${error93.message}`:"QA gate profile bootstrap failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",errors:["No QA gate profile found for the exact plan identity"],recovery_guidance:`Present the PLAN gate dialogue, then call set_qa_gates with swarm_id=${JSON.stringify(args2.swarm_id)} and plan_title=${JSON.stringify(args2.title)} before retrying save_plan with the identical identity.`};else if(profileLookup.kind==="unbound_legacy")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not exact-bind the balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile exact-bind failed: ${error93.message}`:"QA gate profile exact-bind failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",errors:["QA gate profile exists for the readable plan id, but no exact swarm_id/plan_title binding has been adopted yet."],recovery_guidance:formatLegacyQaBindingRecovery({swarm:args2.swarm_id,title:args2.title},"retry save_plan with the identical identity")}}let requirementCoverage=evaluateRequirementCoverage(specContent,args2);if(!reconcileLedgerProjection&&requirementCoverage?.status==="failed"&&args2.confirm_requirement_coverage_gaps!==!0)return{success:!1,message:"REQUIREMENT_COVERAGE_GAPS: save_plan rejected because required FR-### MUST/SHALL requirements are not mapped to any task.",errors:requirementCoverage.blocking_missing.map((requirement)=>`${requirement.id} (${requirement.obligation}): ${requirement.text}`),recovery_guidance:"Add each required FR-### id to a task description or acceptance criterion, or retry with confirm_requirement_coverage_gaps: true only after surfacing the gaps to the user.",requirement_coverage:requirementCoverage};{let existing=existingPlan;if(existing){if(args2.confirm_identity_change!==!0){if(!(existing.swarm===args2.swarm_id&&existing.title===args2.title)){let existingId=derivePlanId(existing),incomingId=derivePlanId({swarm:args2.swarm_id,title:args2.title});return{success:!1,message:"PLAN_IDENTITY_MISMATCH: The incoming plan identity does not match the existing plan. To overwrite with a new identity, set confirm_identity_change: true.",errors:[`Existing plan identity: ${existingId} (swarm: "${existing.swarm}", title: "${existing.title}")`,`Incoming plan identity: ${incomingId} (swarm: "${args2.swarm_id}", title: "${args2.title}")`],recovery_guidance:"Verify the title and swarm_id match the intended plan. If the identity change is intentional, retry with confirm_identity_change: true. Never write .swarm/plan.json or .swarm/plan.md directly."}}}}}let resolvedProfile=preservedExecutionProfile;if(args2.execution_profile!==void 0){let merged={...preservedExecutionProfile??(args2.execution_profile.parallelization_enabled===void 0?{parallelization_enabled:!0}:{}),...args2.execution_profile},parsed=ExecutionProfileSchema.safeParse(merged);if(!parsed.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};resolvedProfile=materializeResolvedExecutionProfile(parsed.data,persistedPlanningProfile)}if(resolvedProfile===void 0)resolvedProfile={...ExecutionProfileSchema.parse({}),parallelization_enabled:!0,...persistedPlanningProfile!==void 0?{planning_profile:persistedPlanningProfile}:{}};else if(resolvedProfile.planning_profile===void 0&&persistedPlanningProfile!==void 0)resolvedProfile={...resolvedProfile,planning_profile:persistedPlanningProfile};let incomingTaskIds=new Set;for(let phase of args2.phases)for(let task2 of phase.tasks)incomingTaskIds.add(task2.id);let missingTaskIds=[];for(let id of priorTaskIds)if(!incomingTaskIds.has(id))missingTaskIds.push(id);let rawRemovedIds=args2.removed_task_ids??[];if(rawRemovedIds.length>0){let seen=new Set;for(let id of rawRemovedIds){if(seen.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains duplicate entries",errors:[`Duplicate id in removed_task_ids: "${id}"`],recovery_guidance:"Deduplicate removed_task_ids and retry save_plan."};seen.add(id)}for(let id of rawRemovedIds)if(incomingTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains a task that also appears in args.phases",errors:[`Task "${id}" appears in both removed_task_ids and args.phases — these are contradictory`],recovery_guidance:"A task cannot be both kept and removed in the same save_plan call. Either drop it from args.phases or remove it from removed_task_ids."};for(let id of rawRemovedIds)if(!priorTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains an id that was not in the prior plan",errors:[`Task "${id}" is in removed_task_ids but not present in the prior plan`],recovery_guidance:"Re-read the prior plan and update removed_task_ids to only list tasks that actually existed."}}let resolvedRemovedIds=[...rawRemovedIds],resolvedRemovalReason=args2.removal_reason;if(args2.reset_statuses===!0&&missingTaskIds.length>0){if(args2.confirm_destructive_reset!==!0)return{success:!1,message:"PLAN_DESTRUCTIVE_RESET_NOT_CONFIRMED: reset_statuses with missing tasks requires confirm_destructive_reset: true",errors:[`reset_statuses: true would drop ${missingTaskIds.length} task(s) from the prior plan: ${missingTaskIds.join(", ")}`],recovery_guidance:"Surface the list of dropped tasks to the user and confirm intent before retrying. Pass confirm_destructive_reset: true (with reset_statuses: true) to acknowledge the destructive reset, or list removed_task_ids explicitly with a removal_reason."};if(rawRemovedIds.length===0)resolvedRemovedIds=[...missingTaskIds],resolvedRemovalReason="destructive reset acknowledged"}if(resolvedRemovedIds.length>0){if((resolvedRemovalReason??"").trim().length===0)return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removal_reason is required when removed_task_ids is non-empty",errors:["removal_reason must be a non-empty, non-whitespace string"],recovery_guidance:"Provide a removal_reason describing why these tasks are being dropped."}}if(missingTaskIds.length>0){let ackSet=new Set(resolvedRemovedIds),unacked=missingTaskIds.filter((id)=>!ackSet.has(id));if(unacked.length>0)return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[`The following prior tasks are missing from the new save and were not listed in removed_task_ids: ${unacked.join(", ")}`],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(unacked)} and a non-empty removal_reason. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation.`}}let resolvedFilesByTask=new Map;for(let phase of args2.phases)for(let task2 of phase.tasks){if(task2.files_touched===void 0){resolvedFilesByTask.set(task2.id,existingFilesMap.get(task2.id)??[]);continue}if(task2.files_touched.length===0){resolvedFilesByTask.set(task2.id,[]);continue}let normalized=normalizeScopeFiles(task2.files_touched);if(!normalized)return{success:!1,message:"PLAN_TASK_SCOPE_INVALID: files_touched must contain valid project-relative paths",errors:[`Task "${task2.id}" has an invalid files_touched list. Absolute paths, traversal, empty entries, and control characters are not allowed.`],recovery_guidance:"Retry save_plan with normalized project-relative paths, omit files_touched to preserve the prior task scope, or pass [] to clear it explicitly."};resolvedFilesByTask.set(task2.id,normalized)}let plan={schema_version:"1.0.0",title:args2.title,swarm:args2.swarm_id,migration_status:reconcileLedgerProjection?existingPlan?.migration_status:"native",current_phase:reconcileLedgerProjection?existingPlan?.current_phase:args2.phases[0]?.id,specMtime,specHash,...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},phases:args2.phases.map((phase)=>{let existingPhase=reconcileLedgerProjection?existingPlan?.phases.find((candidate2)=>candidate2.id===phase.id):void 0;return{id:phase.id,name:phase.name,status:"pending",type:existingPhase?.type,required_agents:existingPhase?.required_agents?[...existingPhase.required_agents]:void 0,tasks:phase.tasks.map((task2)=>{let existingTask=existingPhase?.tasks.find((candidate2)=>candidate2.id===task2.id);return{id:task2.id,phase:phase.id,status:existingStatusMap.get(task2.id)??"pending",size:task2.size??existingTask?.size??"small",description:task2.description,depends:task2.depends??existingTask?.depends??[],acceptance:task2.acceptance??existingTask?.acceptance,files_touched:resolvedFilesByTask.get(task2.id)??[],evidence_path:existingTask?.evidence_path,blocked_reason:existingTask?.blocked_reason,fr_refs:task2.fr_refs??existingTask?.fr_refs}})}})},tasksCount=plan.phases.reduce((acc,phase)=>acc+phase.tasks.length,0),lockTaskId=`save-plan-${Date.now()}`,planFilePath="plan.json";try{let lockResult=await tryAcquireLock(dir,planFilePath,"architect",lockTaskId);if(!lockResult.acquired)return{success:!1,message:`Plan write blocked: file is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry save_plan. The lock will expire automatically if the holding agent fails."};try{if(reconcileLedgerProjection){let lockedRuntimePlan=await loadPlan(dir).catch(()=>null);if(lockedRuntimePlan?._ledgerReplayStale!==!0)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_NOT_STALE: reconcile_ledger_projection is only allowed when loadPlan reports a stale projection.",errors:[lockedRuntimePlan?"The current plan projection is not marked _ledgerReplayStale.":"The current plan could not be loaded for stale-projection reconciliation."],recovery_guidance:"Use reconcile_ledger_projection only to reconverge a workspace whose plan.json still hash-mismatches the ledger after replay failure."};let lockedTailCapture=await readLedgerTailCapture(dir).catch(()=>null);if(reconcileLedgerTailCapture===null||lockedTailCapture===null||reconcileLedgerTailCapture.seq!==lockedTailCapture.seq||reconcileLedgerTailCapture.plan_hash_after!==lockedTailCapture.plan_hash_after)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_STALE: the ledger tail changed before save_plan acquired the lock.",errors:["Re-read the stale plan and retry reconcile_ledger_projection against the latest ledger tail."],recovery_guidance:"Retry reconcile_ledger_projection only when the incoming plan still matches the current stale projection exactly."};let comparableIncomingPlan=PlanSchema.parse(JSON.parse(JSON.stringify(plan)));derivePhaseStatusesForComparison(comparableIncomingPlan);let comparableLoadedPlan=PlanSchema.parse(lockedRuntimePlan);if(JSON.stringify(normalizePlanForReconcileComparison(comparableIncomingPlan))!==JSON.stringify(normalizePlanForReconcileComparison(comparableLoadedPlan)))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_MISMATCH: reconcile_ledger_projection may not change plan semantics.",errors:["Incoming save_plan content does not exactly match the loaded stale projection (identity, task graph, statuses, or execution_profile changed)."],recovery_guidance:"Remove semantic edits and retry reconcile_ledger_projection with the exact stale plan content, or retry save_plan without reconcile_ledger_projection for a normal plan revision."}}await savePlan(dir,plan,{preserveCompletedStatuses:!args2.reset_statuses,planLockAlreadyHeld:!0,...reconcileLedgerProjection&&reconcileLedgerTailCapture?{staleProjectionReconcile:{expectedSeq:reconcileLedgerTailCapture.seq,expectedLedgerHash:reconcileLedgerTailCapture.plan_hash_after}}:{},...resolvedRemovedIds.length>0?{acknowledged_removals:{ids:resolvedRemovedIds,reason:(resolvedRemovalReason??"").trim(),source:"save_plan_tool"}}:{}});let savedPlan=await loadPlanJsonOnly(dir);if(savedPlan)await takeSnapshotWithRetry(dir,savedPlan);if(resolvedProfile!==void 0&&savedPlan){let planId=derivePlanId(plan),planHashAfter=computePlanLedgerHash(savedPlan);if(JSON.stringify(resolvedProfile)!==JSON.stringify(preservedExecutionProfile))await appendLedgerEvent(dir,{event_type:"execution_profile_set",source:"save_plan",plan_id:planId,payload:{execution_profile:resolvedProfile}},{planHashAfter}).catch(()=>{});let wasAlreadyLocked=preservedExecutionProfile?.locked===!0;if(resolvedProfile.locked&&!wasAlreadyLocked)await appendLedgerEvent(dir,{event_type:"execution_profile_locked",source:"save_plan",plan_id:planId},{planHashAfter}).catch(()=>{})}await writeCheckpoint(dir).catch(()=>{});try{let markerPath=path338.join(dir,".swarm",".plan-write-marker"),marker=JSON.stringify({source:"save_plan",timestamp:new Date().toISOString(),phases_count:plan.phases.length,tasks_count:tasksCount});await fs208.promises.writeFile(markerPath,marker,"utf8")}catch{}let warnings=[];if(requirementCoverage?.status==="override"){let missingIds=requirementCoverage.blocking_missing.map((requirement)=>requirement.id).join(", ");warnings.push(`Requirement coverage override used. Missing required FR mappings: ${missingIds}`)}return{success:!0,message:"Plan saved successfully",plan_path:path338.join(dir,".swarm","plan.json"),phases_count:plan.phases.length,tasks_count:tasksCount,...requirementCoverage?{requirement_coverage:requirementCoverage}:{},...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},...warnings.length>0?{warnings}:{}}}finally{if(lockResult.acquired&&lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}catch(error93){if(error93 instanceof PlanTaskRemovalNotAcknowledgedError){let ids=error93.missingTasks.map((t)=>t.id);return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[error93.message],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(ids)} and a non-empty removal_reason.`}}return{success:!1,message:"Failed to save plan: retry with save_plan after resolving the error above",errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."}}}var save_plan=createSwarmTool({description:"Save or revise a structured implementation plan to .swarm/plan.json and .swarm/plan.md. "+"Use this tool for all structural plan changes on an existing plan (adding/removing tasks, updating descriptions, dependencies, or phase names) — existing task statuses are preserved by default (set reset_statuses: true to start fresh). "+"Task descriptions and phase names MUST contain real content from the spec — "+"bracket placeholders like [task] or [Project] will be rejected.",args:{title:exports_external.string().min(1).describe("Plan title — the REAL project name from the spec. NOT a placeholder like [Project]."),swarm_id:exports_external.string().min(1).describe('Swarm identifier (e.g. "mega")'),phases:exports_external.array(exports_external.object({id:exports_external.number().int().min(1).describe("Phase number — a positive integer starting at 1. Use 1, 2, 3, etc."),name:exports_external.string().min(1).describe("Descriptive phase name derived from the spec"),tasks:exports_external.array(exports_external.object({id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M format, e.g. "1.1"').describe('Task ID in N.M format, e.g. "1.1", "2.3"'),description:exports_external.string().min(1).describe("Specific task description from the spec. NOT a placeholder like [task]."),size:exports_external.enum(["small","medium","large"]).optional().describe("Task size estimate. When omitted on a revision, the existing task keeps its size; new tasks default to small."),depends:exports_external.array(exports_external.string()).optional().describe('Task IDs this task depends on, e.g. ["1.1", "1.2"]'),acceptance:exports_external.string().optional().describe("Acceptance criteria for this task"),files_touched:exports_external.array(exports_external.string()).max(1e4).optional().describe("Exact project-relative files or directories this task may modify. Omit on revision to preserve the prior scope; pass [] to clear it explicitly."),fr_refs:exports_external.array(exports_external.string()).optional().describe('Spec FR-###/SC-### IDs this task maps to, e.g. ["FR-001", "SC-002"]')})).min(1).describe("Tasks in this phase")})).min(1).describe("Implementation phases"),working_directory:exports_external.string().optional().describe("Working directory (explicit path, required - no fallback)"),reset_statuses:exports_external.boolean().optional().describe("When true, reset ALL task statuses to pending regardless of prior completion state. Use only when deliberately re-planning a phase from scratch. Default false (preserves existing task statuses across plan revisions)."),removed_task_ids:exports_external.array(exports_external.string()).optional().describe("Task IDs that are present in the prior plan but intentionally being removed by this save. Every task missing from `phases` MUST be enumerated here, otherwise save_plan rejects with PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation."),removal_reason:exports_external.string().optional().describe("Required when removed_task_ids is non-empty. Human-readable reason recorded on each task_removed ledger event."),confirm_destructive_reset:exports_external.boolean().optional().describe("Required when reset_statuses is true AND at least one task is missing from the new plan. Set true to acknowledge that the destructive reset drops unfinished work. When set together with reset_statuses, save_plan auto-populates removed_task_ids from the missing set."),confirm_identity_change:exports_external.boolean().optional().describe("When true, allows overwriting an existing plan that has a different identity (swarm_id + title). Without this flag, save_plan rejects with PLAN_IDENTITY_MISMATCH if the identity differs."),confirm_requirement_coverage_gaps:exports_external.boolean().optional().describe("When true, allows saving a plan even when required FR-### MUST/SHALL requirements from the effective spec are not explicitly mapped in task descriptions or acceptance criteria. Use only after surfacing the structured requirement_coverage gaps to the user."),execution_profile:exports_external.object({parallelization_enabled:exports_external.boolean().optional().describe("When true, enables parallel task dispatch for this plan. Default false (serial)."),max_concurrent_tasks:exports_external.number().int().min(1).max(64).optional().describe("Maximum tasks that may run concurrently when parallelization is enabled. Default 10."),council_parallel:exports_external.boolean().optional().describe("When true, council review phases may run in parallel. Default true."),locked:exports_external.boolean().optional().describe("When true, locks the profile — future save_plan calls that include "+"execution_profile will be rejected (fail-closed). Unlock by resetting the plan (reset_statuses: true)."),auto_proceed:exports_external.boolean().optional().describe("When true, the architect advances to the next phase automatically without asking for confirmation. Default false."),commit_after_each_completed_task:exports_external.boolean().optional().describe("When true, execution creates a checkpoint commit after each successfully completed task. Default false."),planning_profile:exports_external.enum(["balanced","strict"]).optional().describe("Planning-policy profile. balanced auto-seeds durable defaults and minimizes ceremony; strict requires the full QA questionnaire and an effective spec.")}).optional().describe("Architect-facing concurrency controls. Once locked, cannot be changed without resetting. Omit to preserve the existing profile."),reconcile_ledger_projection:exports_external.boolean().optional().describe("Narrow stale-ledger recovery mode. When true, save_plan only permits an unchanged semantic re-save that reconverges a _ledgerReplayStale plan.json with the authoritative ledger.")},execute:async(args2,_directory2)=>{return JSON.stringify(await executeSavePlan(args2,_directory2),null,2)}});init_zod();init_config();init_manager2();import*as fs209 from"node:fs";import*as path339 from"node:path";init_utils();init_logger();function parsePubspecLock(content){let components=[];if(!content.match(/^packages:\s*$/m))return components;let lines=content.split(`
7489
+ ${task2.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=task2.fr_refs?.includes(requirement.id)??!1;if(matchesFreeText||matchesFrRefs)mappedTaskIds.push(task2.id)}let entry={id:requirement.id,obligation:requirement.obligation,text:requirement.text,mapped_task_ids:mappedTaskIds};if(mappedTaskIds.length>0)covered.push(entry);else missing.push(entry)}let blockingMissing=missing.filter((entry)=>entry.obligation==="MUST"||entry.obligation==="SHALL");return{status:blockingMissing.length>0?args2.confirm_requirement_coverage_gaps===!0?"override":"failed":"passed",total_requirements:requirements.length,covered_count:covered.length,missing_count:missing.length,blocking_missing_count:blockingMissing.length,covered,missing,blocking_missing:blockingMissing}}function detectPlaceholderContent(args2){let issues=[],placeholderPattern=/^\[\w[\w\s]*\]$/;if(placeholderPattern.test(args2.title.trim()))issues.push(`Plan title appears to be a template placeholder: "${args2.title}"`);for(let phase of args2.phases){if(placeholderPattern.test(phase.name.trim()))issues.push(`Phase ${phase.id} name appears to be a template placeholder: "${phase.name}"`);for(let task2 of phase.tasks)if(placeholderPattern.test(task2.description.trim()))issues.push(`Task ${task2.id} description appears to be a template placeholder: "${task2.description}"`)}return issues}function validateTargetWorkspace(target,source){if(target===void 0||target===null)return`Target workspace is required: ${source} not provided`;let trimmed=target.trim();if(trimmed.length===0)return`Target workspace cannot be empty or whitespace: ${source}`;if(trimmed.replace(/\\/g,"/").includes(".."))return`Target workspace cannot contain path traversal: ${source} contains ".."`;return}async function executeSavePlan(args2,fallbackDir){let validationErrors=[];for(let phase of args2.phases){if(!Number.isInteger(phase.id)||phase.id<=0)validationErrors.push(`Phase ${phase.id} has invalid id: must be a positive integer`);let taskIdPattern=/^\d+\.\d+(\.\d+)*$/;for(let task2 of phase.tasks)if(!taskIdPattern.test(task2.id))validationErrors.push(`Task '${task2.id}' in phase ${phase.id} has invalid id format: must match N.M pattern (e.g. '1.1', '2.3')`)}if(validationErrors.length>0)return{success:!1,message:"Plan rejected: invalid phase or task IDs",errors:validationErrors,recovery_guidance:'Phase IDs must be positive integers: 1, 2, 3 (not 0, -1, or decimals). Task IDs must use N.M format: "1.1", "2.3", "3.1". Call save_plan again with corrected ids. Never write .swarm/plan.json or .swarm/plan.md directly.'};let placeholderIssues=detectPlaceholderContent(args2);if(placeholderIssues.length>0)return{success:!1,message:"Plan rejected: contains template placeholder content",errors:placeholderIssues,recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};let targetWorkspace=args2.working_directory??fallbackDir,workspaceError=validateTargetWorkspace(targetWorkspace,args2.working_directory?"working_directory":"fallbackDir");if(workspaceError)return{success:!1,message:"Target workspace validation failed: provide working_directory parameter to save_plan",errors:[workspaceError],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};try{assertProjectRoot(targetWorkspace)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message],recovery_guidance:"Pass the project root, or add an explicit local .git/.opencode project boundary before retrying save_plan."}}if(args2.working_directory&&fallbackDir){let resolvedTarget=path338.resolve(args2.working_directory),resolvedRoot=path338.resolve(fallbackDir),fallbackExists=!1;try{fs208.accessSync(resolvedRoot,fs208.constants.F_OK),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(isStrictPathDescendant(resolvedTarget,resolvedRoot)){if(!hasExplicitProjectBoundary(resolvedTarget))return{success:!1,message:`working_directory must be the project root. Got "${args2.working_directory}" (resolves to "${resolvedTarget}"), which is a subdirectory of fallback "${resolvedRoot}". Omit working_directory or pass the project root explicitly.`,errors:[`working_directory "${resolvedTarget}" is a subdirectory of fallback "${resolvedRoot}"`],recovery_guidance:`Pass working_directory: "${resolvedRoot}" or omit the field entirely.`}}}}let dir=targetWorkspace,reconcileLedgerProjection=isLedgerProjectionReconcileRequest(args2);if(reconcileLedgerProjection&&!isPureLedgerProjectionReconcileRequest(args2))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_INVALID: reconcile_ledger_projection only permits an unchanged semantic re-save.",errors:["Remove reset_statuses, task-removal acknowledgements, identity overrides, and requirement-coverage overrides before retrying reconcile_ledger_projection."],recovery_guidance:"Retry with reconcile_ledger_projection: true only when save_plan is re-saving the same identity, task graph, statuses, and execution_profile to reconverge a stale projection."};let existingStatusMap=new Map,existingFilesMap=new Map,priorTaskIds=new Set,preservedExecutionProfile,existingPlan=null;try{existingPlan=await loadPlanJsonOnly(dir)}catch{}if(existingPlan){for(let phase of existingPlan.phases)for(let task2 of phase.tasks)priorTaskIds.add(task2.id),existingFilesMap.set(task2.id,[...task2.files_touched]);if(!args2.reset_statuses)for(let phase of existingPlan.phases)for(let task2 of phase.tasks)existingStatusMap.set(task2.id,task2.status);preservedExecutionProfile=existingPlan.execution_profile}let reconcileLedgerTailCapture=reconcileLedgerProjection?await readLedgerTailCapture(dir).catch(()=>null):null,specMtime=reconcileLedgerProjection?existingPlan?.specMtime:void 0,specHash=reconcileLedgerProjection?existingPlan?.specHash:void 0,specContent,planningProfileResolution=resolvePlanningProfile({directory:dir,incomingExecutionProfile:args2.execution_profile,existingExecutionProfile:preservedExecutionProfile,resetStatuses:args2.reset_statuses}),effectivePlanningProfile=planningProfileResolution.effective,persistedPlanningProfile=planningProfileResolution.persisted;if(existingPlan?.execution_profile?.locked&&args2.execution_profile!==void 0&&!args2.reset_statuses){let requestedProfile=ExecutionProfileSchema.safeParse({...existingPlan.execution_profile,...args2.execution_profile});if(!requestedProfile.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:requestedProfile.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};let requestedMaterializedProfile=materializeResolvedExecutionProfile(requestedProfile.data,persistedPlanningProfile);if(executionProfilesEqual(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=existingPlan.execution_profile;else if(canRatchetLockedPlanningProfile(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=requestedMaterializedProfile;else return{success:!1,message:"EXECUTION_PROFILE_LOCKED: The execution_profile for this plan is locked and cannot be changed.",errors:["execution_profile.locked is true — only a balanced→strict planning_profile ratchet is allowed without reset_statuses. All other profile changes are rejected."],recovery_guidance:"Remove the execution_profile field from this save_plan call to preserve the locked profile, or use reset_statuses: true to start fresh (this clears the lock). Never modify execution_profile directly in plan.json."}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_SPEC_GATE!=="1"){let spec=readEffectiveSpecSync(targetWorkspace);if(!spec&&effectivePlanningProfile==="strict")return{success:!1,message:"SPEC_REQUIRED: an effective spec (native .swarm/spec.md, OpenSpec openspec/specs or openspec/changes, or Spec-Kit .specify/) must exist before saving a plan.",errors:["No effective spec found — .swarm/spec.md is absent and no OpenSpec/Spec-Kit projection succeeded."],recovery_guidance:"Obtain explicit user consent, then run /swarm sdd project (agent-invocable) to materialize an effective spec from SDD sources. If .swarm/spec.md already exists, pass --overwrite after consent. Alternatively, run /swarm specify to author a native spec. Never write .swarm/plan.json or .swarm/plan.md directly."};if(spec){specMtime=spec.mtime??void 0,specHash=spec.hash,specContent=spec.content;try{let snapshotPath=path338.join(targetWorkspace,".swarm","spec-snapshot.md");await fs208.promises.writeFile(snapshotPath,spec.content,"utf-8")}catch{}}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_GATE_SELECTION!=="1"){let profileLookup;try{profileLookup=getProfileLookupForIdentity(targetWorkspace,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not verify the durable QA gate selection.",errors:[error93 instanceof Error?`QA gate profile store read failed: ${error93.message}`:"QA gate profile store read failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry get_qa_gate_profile and save_plan with the same swarm_id and title."}}if(profileLookup.kind==="missing")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not create the default balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile bootstrap failed: ${error93.message}`:"QA gate profile bootstrap failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",errors:["No QA gate profile found for the exact plan identity"],recovery_guidance:`Present the PLAN gate dialogue, then call set_qa_gates with swarm_id=${JSON.stringify(args2.swarm_id)} and plan_title=${JSON.stringify(args2.title)} before retrying save_plan with the identical identity.`};else if(profileLookup.kind==="unbound_legacy")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not exact-bind the balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile exact-bind failed: ${error93.message}`:"QA gate profile exact-bind failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",errors:["QA gate profile exists for the readable plan id, but no exact swarm_id/plan_title binding has been adopted yet."],recovery_guidance:formatLegacyQaBindingRecovery({swarm:args2.swarm_id,title:args2.title},"retry save_plan with the identical identity")}}let requirementCoverage=evaluateRequirementCoverage(specContent,args2);if(!reconcileLedgerProjection&&requirementCoverage?.status==="failed"&&args2.confirm_requirement_coverage_gaps!==!0)return{success:!1,message:"REQUIREMENT_COVERAGE_GAPS: save_plan rejected because required FR-### MUST/SHALL requirements are not mapped to any task.",errors:requirementCoverage.blocking_missing.map((requirement)=>`${requirement.id} (${requirement.obligation}): ${requirement.text}`),recovery_guidance:"Add each required FR-### id to a task description or acceptance criterion, or retry with confirm_requirement_coverage_gaps: true only after surfacing the gaps to the user.",requirement_coverage:requirementCoverage};{let existing=existingPlan;if(existing){if(args2.confirm_identity_change!==!0){if(!(existing.swarm===args2.swarm_id&&existing.title===args2.title)){let existingId=derivePlanId(existing),incomingId=derivePlanId({swarm:args2.swarm_id,title:args2.title});return{success:!1,message:"PLAN_IDENTITY_MISMATCH: The incoming plan identity does not match the existing plan. To overwrite with a new identity, set confirm_identity_change: true.",errors:[`Existing plan identity: ${existingId} (swarm: "${existing.swarm}", title: "${existing.title}")`,`Incoming plan identity: ${incomingId} (swarm: "${args2.swarm_id}", title: "${args2.title}")`],recovery_guidance:"Verify the title and swarm_id match the intended plan. If the identity change is intentional, retry with confirm_identity_change: true. Never write .swarm/plan.json or .swarm/plan.md directly."}}}}}let resolvedProfile=preservedExecutionProfile;if(args2.execution_profile!==void 0){let merged={...preservedExecutionProfile??(args2.execution_profile.parallelization_enabled===void 0?{parallelization_enabled:!0}:{}),...args2.execution_profile},parsed=ExecutionProfileSchema.safeParse(merged);if(!parsed.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};resolvedProfile=materializeResolvedExecutionProfile(parsed.data,persistedPlanningProfile)}if(resolvedProfile===void 0)resolvedProfile={...ExecutionProfileSchema.parse({}),parallelization_enabled:!0,...persistedPlanningProfile!==void 0?{planning_profile:persistedPlanningProfile}:{}};else if(resolvedProfile.planning_profile===void 0&&persistedPlanningProfile!==void 0)resolvedProfile={...resolvedProfile,planning_profile:persistedPlanningProfile};let incomingTaskIds=new Set;for(let phase of args2.phases)for(let task2 of phase.tasks)incomingTaskIds.add(task2.id);let missingTaskIds=[];for(let id of priorTaskIds)if(!incomingTaskIds.has(id))missingTaskIds.push(id);let rawRemovedIds=args2.removed_task_ids??[];if(rawRemovedIds.length>0){let seen=new Set;for(let id of rawRemovedIds){if(seen.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains duplicate entries",errors:[`Duplicate id in removed_task_ids: "${id}"`],recovery_guidance:"Deduplicate removed_task_ids and retry save_plan."};seen.add(id)}for(let id of rawRemovedIds)if(incomingTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains a task that also appears in args.phases",errors:[`Task "${id}" appears in both removed_task_ids and args.phases — these are contradictory`],recovery_guidance:"A task cannot be both kept and removed in the same save_plan call. Either drop it from args.phases or remove it from removed_task_ids."};for(let id of rawRemovedIds)if(!priorTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains an id that was not in the prior plan",errors:[`Task "${id}" is in removed_task_ids but not present in the prior plan`],recovery_guidance:"Re-read the prior plan and update removed_task_ids to only list tasks that actually existed."}}let resolvedRemovedIds=[...rawRemovedIds],resolvedRemovalReason=args2.removal_reason;if(args2.reset_statuses===!0&&missingTaskIds.length>0){if(args2.confirm_destructive_reset!==!0)return{success:!1,message:"PLAN_DESTRUCTIVE_RESET_NOT_CONFIRMED: reset_statuses with missing tasks requires confirm_destructive_reset: true",errors:[`reset_statuses: true would drop ${missingTaskIds.length} task(s) from the prior plan: ${missingTaskIds.join(", ")}`],recovery_guidance:"Surface the list of dropped tasks to the user and confirm intent before retrying. Pass confirm_destructive_reset: true (with reset_statuses: true) to acknowledge the destructive reset, or list removed_task_ids explicitly with a removal_reason."};if(rawRemovedIds.length===0)resolvedRemovedIds=[...missingTaskIds],resolvedRemovalReason="destructive reset acknowledged"}if(resolvedRemovedIds.length>0){if((resolvedRemovalReason??"").trim().length===0)return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removal_reason is required when removed_task_ids is non-empty",errors:["removal_reason must be a non-empty, non-whitespace string"],recovery_guidance:"Provide a removal_reason describing why these tasks are being dropped."}}if(missingTaskIds.length>0){let ackSet=new Set(resolvedRemovedIds),unacked=missingTaskIds.filter((id)=>!ackSet.has(id));if(unacked.length>0)return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[`The following prior tasks are missing from the new save and were not listed in removed_task_ids: ${unacked.join(", ")}`],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(unacked)} and a non-empty removal_reason. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation.`}}let resolvedFilesByTask=new Map;for(let phase of args2.phases)for(let task2 of phase.tasks){if(task2.files_touched===void 0){resolvedFilesByTask.set(task2.id,existingFilesMap.get(task2.id)??[]);continue}if(task2.files_touched.length===0){resolvedFilesByTask.set(task2.id,[]);continue}let normalized=normalizeScopeFiles(task2.files_touched);if(!normalized)return{success:!1,message:"PLAN_TASK_SCOPE_INVALID: files_touched must contain valid project-relative paths",errors:[`Task "${task2.id}" has an invalid files_touched list. Absolute paths, traversal, empty entries, and control characters are not allowed.`],recovery_guidance:"Retry save_plan with normalized project-relative paths, omit files_touched to preserve the prior task scope, or pass [] to clear it explicitly."};resolvedFilesByTask.set(task2.id,normalized)}let plan={schema_version:"1.0.0",title:args2.title,swarm:args2.swarm_id,migration_status:reconcileLedgerProjection?existingPlan?.migration_status:"native",current_phase:reconcileLedgerProjection?existingPlan?.current_phase:args2.phases[0]?.id,specMtime,specHash,...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},phases:args2.phases.map((phase)=>{let existingPhase=reconcileLedgerProjection?existingPlan?.phases.find((candidate2)=>candidate2.id===phase.id):void 0;return{id:phase.id,name:phase.name,status:"pending",type:existingPhase?.type,required_agents:existingPhase?.required_agents?[...existingPhase.required_agents]:void 0,tasks:phase.tasks.map((task2)=>{let existingTask=existingPhase?.tasks.find((candidate2)=>candidate2.id===task2.id);return{id:task2.id,phase:phase.id,status:existingStatusMap.get(task2.id)??"pending",size:task2.size??existingTask?.size??"small",description:task2.description,depends:task2.depends??existingTask?.depends??[],acceptance:task2.acceptance??existingTask?.acceptance,files_touched:resolvedFilesByTask.get(task2.id)??[],evidence_path:existingTask?.evidence_path,blocked_reason:existingTask?.blocked_reason,fr_refs:task2.fr_refs??existingTask?.fr_refs}})}})},tasksCount=plan.phases.reduce((acc,phase)=>acc+phase.tasks.length,0),lockTaskId=`save-plan-${Date.now()}`,planFilePath="plan.json";try{let lockResult=await tryAcquireLock(dir,planFilePath,"architect",lockTaskId);if(!lockResult.acquired)return{success:!1,message:`Plan write blocked: file is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry save_plan. The lock will expire automatically if the holding agent fails."};try{if(reconcileLedgerProjection){let lockedRuntimePlan=await loadPlan(dir).catch(()=>null);if(lockedRuntimePlan?._ledgerReplayStale!==!0)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_NOT_STALE: reconcile_ledger_projection is only allowed when loadPlan reports a stale projection.",errors:[lockedRuntimePlan?"The current plan projection is not marked _ledgerReplayStale.":"The current plan could not be loaded for stale-projection reconciliation."],recovery_guidance:"Use reconcile_ledger_projection only to reconverge a workspace whose plan.json still hash-mismatches the ledger after replay failure."};let lockedTailCapture=await readLedgerTailCapture(dir).catch(()=>null);if(reconcileLedgerTailCapture===null||lockedTailCapture===null||reconcileLedgerTailCapture.seq!==lockedTailCapture.seq||reconcileLedgerTailCapture.plan_hash_after!==lockedTailCapture.plan_hash_after)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_STALE: the ledger tail changed before save_plan acquired the lock.",errors:["Re-read the stale plan and retry reconcile_ledger_projection against the latest ledger tail."],recovery_guidance:"Retry reconcile_ledger_projection only when the incoming plan still matches the current stale projection exactly."};let comparableIncomingPlan=PlanSchema.parse(JSON.parse(JSON.stringify(plan)));derivePhaseStatusesForComparison(comparableIncomingPlan);let comparableLoadedPlan=PlanSchema.parse(lockedRuntimePlan);if(JSON.stringify(normalizePlanForReconcileComparison(comparableIncomingPlan))!==JSON.stringify(normalizePlanForReconcileComparison(comparableLoadedPlan)))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_MISMATCH: reconcile_ledger_projection may not change plan semantics.",errors:["Incoming save_plan content does not exactly match the loaded stale projection (identity, task graph, statuses, or execution_profile changed)."],recovery_guidance:"Remove semantic edits and retry reconcile_ledger_projection with the exact stale plan content, or retry save_plan without reconcile_ledger_projection for a normal plan revision."}}let saveDurability=await savePlan(dir,plan,{preserveCompletedStatuses:!args2.reset_statuses,planLockAlreadyHeld:!0,...reconcileLedgerProjection&&reconcileLedgerTailCapture?{staleProjectionReconcile:{expectedSeq:reconcileLedgerTailCapture.seq,expectedLedgerHash:reconcileLedgerTailCapture.plan_hash_after}}:{},...resolvedRemovedIds.length>0?{acknowledged_removals:{ids:resolvedRemovedIds,reason:(resolvedRemovalReason??"").trim(),source:"save_plan_tool"}}:{}}),savedPlan=await loadPlanJsonOnly(dir);if(savedPlan)await takeSnapshotWithRetry(dir,savedPlan);if(resolvedProfile!==void 0&&savedPlan){let planId=derivePlanId(plan),planHashAfter=computePlanLedgerHash(savedPlan);if(JSON.stringify(resolvedProfile)!==JSON.stringify(preservedExecutionProfile))await appendLedgerEvent(dir,{event_type:"execution_profile_set",source:"save_plan",plan_id:planId,payload:{execution_profile:resolvedProfile}},{planHashAfter}).catch(()=>{});let wasAlreadyLocked=preservedExecutionProfile?.locked===!0;if(resolvedProfile.locked&&!wasAlreadyLocked)await appendLedgerEvent(dir,{event_type:"execution_profile_locked",source:"save_plan",plan_id:planId},{planHashAfter}).catch(()=>{})}await writeCheckpoint(dir).catch(()=>{});try{let markerPath=path338.join(dir,".swarm",".plan-write-marker"),marker=JSON.stringify({source:"save_plan",timestamp:new Date().toISOString(),phases_count:plan.phases.length,tasks_count:tasksCount});await fs208.promises.writeFile(markerPath,marker,"utf8")}catch{}let warnings=[];if(saveDurability.durability==="incomplete")warnings.push(`Plan saved with incomplete durability; degraded surfaces: ${saveDurability.degraded_surfaces.join(", ")}`+(saveDurability.md_write_error?` (${saveDurability.md_write_error})`:""));if(requirementCoverage?.status==="override"){let missingIds=requirementCoverage.blocking_missing.map((requirement)=>requirement.id).join(", ");warnings.push(`Requirement coverage override used. Missing required FR mappings: ${missingIds}`)}return{success:!0,message:"Plan saved successfully",plan_path:path338.join(dir,".swarm","plan.json"),phases_count:plan.phases.length,tasks_count:tasksCount,...requirementCoverage?{requirement_coverage:requirementCoverage}:{},...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},...warnings.length>0?{warnings}:{}}}finally{if(lockResult.acquired&&lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}catch(error93){if(error93 instanceof PlanTaskRemovalNotAcknowledgedError){let ids=error93.missingTasks.map((t)=>t.id);return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[error93.message],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(ids)} and a non-empty removal_reason.`}}return{success:!1,message:"Failed to save plan: retry with save_plan after resolving the error above",errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."}}}var save_plan=createSwarmTool({description:"Save or revise a structured implementation plan to .swarm/plan.json and .swarm/plan.md. "+"Use this tool for all structural plan changes on an existing plan (adding/removing tasks, updating descriptions, dependencies, or phase names) — existing task statuses are preserved by default (set reset_statuses: true to start fresh). "+"Task descriptions and phase names MUST contain real content from the spec — "+"bracket placeholders like [task] or [Project] will be rejected.",args:{title:exports_external.string().min(1).describe("Plan title — the REAL project name from the spec. NOT a placeholder like [Project]."),swarm_id:exports_external.string().min(1).describe('Swarm identifier (e.g. "mega")'),phases:exports_external.array(exports_external.object({id:exports_external.number().int().min(1).describe("Phase number — a positive integer starting at 1. Use 1, 2, 3, etc."),name:exports_external.string().min(1).describe("Descriptive phase name derived from the spec"),tasks:exports_external.array(exports_external.object({id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M format, e.g. "1.1"').describe('Task ID in N.M format, e.g. "1.1", "2.3"'),description:exports_external.string().min(1).describe("Specific task description from the spec. NOT a placeholder like [task]."),size:exports_external.enum(["small","medium","large"]).optional().describe("Task size estimate. When omitted on a revision, the existing task keeps its size; new tasks default to small."),depends:exports_external.array(exports_external.string()).optional().describe('Task IDs this task depends on, e.g. ["1.1", "1.2"]'),acceptance:exports_external.string().optional().describe("Acceptance criteria for this task"),files_touched:exports_external.array(exports_external.string()).max(1e4).optional().describe("Exact project-relative files or directories this task may modify. Omit on revision to preserve the prior scope; pass [] to clear it explicitly."),fr_refs:exports_external.array(exports_external.string()).optional().describe('Spec FR-###/SC-### IDs this task maps to, e.g. ["FR-001", "SC-002"]')})).min(1).describe("Tasks in this phase")})).min(1).describe("Implementation phases"),working_directory:exports_external.string().optional().describe("Working directory (explicit path, required - no fallback)"),reset_statuses:exports_external.boolean().optional().describe("When true, reset ALL task statuses to pending regardless of prior completion state. Use only when deliberately re-planning a phase from scratch. Default false (preserves existing task statuses across plan revisions)."),removed_task_ids:exports_external.array(exports_external.string()).optional().describe("Task IDs that are present in the prior plan but intentionally being removed by this save. Every task missing from `phases` MUST be enumerated here, otherwise save_plan rejects with PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation."),removal_reason:exports_external.string().optional().describe("Required when removed_task_ids is non-empty. Human-readable reason recorded on each task_removed ledger event."),confirm_destructive_reset:exports_external.boolean().optional().describe("Required when reset_statuses is true AND at least one task is missing from the new plan. Set true to acknowledge that the destructive reset drops unfinished work. When set together with reset_statuses, save_plan auto-populates removed_task_ids from the missing set."),confirm_identity_change:exports_external.boolean().optional().describe("When true, allows overwriting an existing plan that has a different identity (swarm_id + title). Without this flag, save_plan rejects with PLAN_IDENTITY_MISMATCH if the identity differs."),confirm_requirement_coverage_gaps:exports_external.boolean().optional().describe("When true, allows saving a plan even when required FR-### MUST/SHALL requirements from the effective spec are not explicitly mapped in task descriptions or acceptance criteria. Use only after surfacing the structured requirement_coverage gaps to the user."),execution_profile:exports_external.object({parallelization_enabled:exports_external.boolean().optional().describe("When true, enables parallel task dispatch for this plan. Default false (serial)."),max_concurrent_tasks:exports_external.number().int().min(1).max(64).optional().describe("Maximum tasks that may run concurrently when parallelization is enabled. Default 10."),council_parallel:exports_external.boolean().optional().describe("When true, council review phases may run in parallel. Default true."),locked:exports_external.boolean().optional().describe("When true, locks the profile — future save_plan calls that include "+"execution_profile will be rejected (fail-closed). Unlock by resetting the plan (reset_statuses: true)."),auto_proceed:exports_external.boolean().optional().describe("When true, the architect advances to the next phase automatically without asking for confirmation. Default false."),commit_after_each_completed_task:exports_external.boolean().optional().describe("When true, execution creates a checkpoint commit after each successfully completed task. Default false."),planning_profile:exports_external.enum(["balanced","strict"]).optional().describe("Planning-policy profile. balanced auto-seeds durable defaults and minimizes ceremony; strict requires the full QA questionnaire and an effective spec.")}).optional().describe("Architect-facing concurrency controls. Once locked, cannot be changed without resetting. Omit to preserve the existing profile."),reconcile_ledger_projection:exports_external.boolean().optional().describe("Narrow stale-ledger recovery mode. When true, save_plan only permits an unchanged semantic re-save that reconverges a _ledgerReplayStale plan.json with the authoritative ledger.")},execute:async(args2,_directory2)=>{return JSON.stringify(await executeSavePlan(args2,_directory2),null,2)}});init_zod();init_config();init_manager2();import*as fs209 from"node:fs";import*as path339 from"node:path";init_utils();init_logger();function parsePubspecLock(content){let components=[];if(!content.match(/^packages:\s*$/m))return components;let lines=content.split(`
7490
7490
  `),inPackages=!1,currentPackage="",currentVersion="";for(let i=0;i<lines.length;i++){let line=lines[i],trimmed=line.replace(/^ {2}/,"");if(trimmed==="packages:"||trimmed.startsWith("packages:")){inPackages=!0;continue}if(!inPackages)continue;let packageMatch=line.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(packageMatch){if(currentPackage&&currentVersion)components.push({name:currentPackage,version:currentVersion,type:"library",purl:generatePurl("pub",currentPackage,currentVersion)});currentPackage=packageMatch[1],currentVersion="";continue}if(currentPackage&&line.includes("version:")){let versionMatch=line.match(/version:\s*"([^"]+)"/);if(versionMatch)currentVersion=versionMatch[1]}}if(currentPackage&&currentVersion)components.push({name:currentPackage,version:currentVersion,type:"library",purl:generatePurl("pub",currentPackage,currentVersion)});return components}function parsePubspecYaml(content){let components=[],lines=content.split(`
7491
7491
  `),inDependencies=!1,inDevDependencies=!1;for(let line of lines){let trimmed=line.trim();if(trimmed==="dependencies:"){inDependencies=!0,inDevDependencies=!1;continue}if(trimmed==="dev_dependencies:"){inDependencies=!1,inDevDependencies=!0;continue}if(trimmed==="dependencies_overrides:"||trimmed==="dev_dependencies_overrides:"||trimmed.startsWith("environment:")){inDependencies=!1,inDevDependencies=!1;continue}if(!inDependencies&&!inDevDependencies)continue;if(!trimmed||trimmed.startsWith("#")||trimmed.includes("sdk:"))continue;let match=trimmed.match(/^([a-zA-Z0-9_-]+):\s*(.+)?$/);if(match){let name=match[1],value=match[2]||"";if(name==="flutter"||name==="environment")continue;let version5="unknown",caretMatch=value.match(/\^?([\d.]+)/);if(caretMatch)version5=caretMatch[1];let hostedMatch=value.match(/version:\s*"?\^?([\d.]+)/);if(hostedMatch)version5=hostedMatch[1];if(name&&version5!=="unknown")components.push({name,version:version5,type:"library",purl:generatePurl("pub",name,version5)})}}return components}var dartDetectors=[{name:"Dart pubspec.lock",patterns:["pubspec.lock"],detect:(_filePath,content)=>{return parsePubspecLock(content)}},{name:"Dart pubspec.yaml",patterns:["pubspec.yaml"],detect:(_filePath,content)=>{return parsePubspecYaml(content)}}];function parsePackagesLockJson(content){let components=[];try{let lock=JSON.parse(content),targets=lock.targets||lock.dependencies||{};for(let[_target,targetDeps]of Object.entries(targets)){if(!targetDeps||typeof targetDeps!=="object")continue;for(let[pkgSpec,pkgData]of Object.entries(targetDeps)){if(!pkgSpec.includes("/"))continue;let[name,version5]=pkgSpec.split("/"),pkg=pkgData;if(name&&version5)components.push({name,version:version5,type:"library",purl:generatePurl("nuget",name,version5),license:pkg.license})}}}catch{}return components}function parsePaketLock(content){let components=[],lines=content.split(`
7492
7492
  `),inNuGetSection=!1;for(let line of lines){let trimmed=line.trim();if(trimmed==="NUGET"||trimmed.startsWith("NUGET")){inNuGetSection=!0;continue}if(trimmed==="GITHUB"||trimmed.startsWith("GITHUB")){inNuGetSection=!1;continue}if(!inNuGetSection)continue;if(!trimmed||trimmed.startsWith("remote:")||trimmed.startsWith("->"))continue;let match=trimmed.match(/^([a-zA-Z0-9_.-]+)\s+\(([^)]+)\)/);if(match){let name=match[1],version5=match[2];if(name&&version5)components.push({name,version:version5,type:"library",purl:generatePurl("nuget",name,version5)})}}return components}var dotnetDetectors=[{name:".NET packages.lock.json",patterns:["packages.lock.json"],detect:(_filePath,content)=>{return parsePackagesLockJson(content)}},{name:".NET paket.lock",patterns:["paket.lock"],detect:(_filePath,content)=>{return parsePaketLock(content)}}];function parseGoMod(content){let components=[],lines=content.split(`