opencode-swarm 7.188.5 → 7.188.6

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 (90) hide show
  1. package/README.md +2 -2
  2. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  3. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  4. package/dist/cli/{auto-checkpoint-6z6dhqak.js → auto-checkpoint-q2xwy0hz.js} +8 -8
  5. package/dist/cli/{checkpoint-99vqentz.js → checkpoint-9cbytsxe.js} +13 -13
  6. package/dist/cli/{coder-settlement-07dkrqvy.js → coder-settlement-a74xcmtn.js} +9 -9
  7. package/dist/cli/{config-doctor-0pqexbab.js → config-doctor-jec44ph0.js} +12 -12
  8. package/dist/cli/{core-zx4az38t.js → core-yvx60mhw.js} +2 -2
  9. package/dist/cli/{curation-policy-nxcx99yp.js → curation-policy-65ckmmd5.js} +5 -5
  10. package/dist/cli/{curator-drift-0ne6gnj0.js → curator-drift-t95vqagz.js} +6 -6
  11. package/dist/cli/{curator-llm-factory-gdedzs6k.js → curator-llm-factory-znjp0g9d.js} +36 -36
  12. package/dist/cli/{curator-s08eqma1.js → curator-wr25srz6.js} +36 -36
  13. package/dist/cli/{doctor-knowledge-receipt-phase-id-kpzaepq8.js → doctor-knowledge-receipt-phase-id-hxyxqqya.js} +7 -7
  14. package/dist/cli/{evidence-summary-service-xadab4ym.js → evidence-summary-service-pzr0aw1h.js} +16 -16
  15. package/dist/cli/{gate-evidence-c3d7ewv4.js → gate-evidence-0dwbqya4.js} +6 -6
  16. package/dist/cli/{guardrail-explain-enbr5ne9.js → guardrail-explain-etssbwma.js} +37 -37
  17. package/dist/cli/{guardrail-log-0g59n4ae.js → guardrail-log-055340sb.js} +7 -7
  18. package/dist/cli/{guardrail-reset-e0m3p15n.js → guardrail-reset-zdnshfqh.js} +36 -36
  19. package/dist/cli/{hive-promoter-1jb0t5g2.js → hive-promoter-nphztsfb.js} +36 -36
  20. package/dist/cli/{index-1kd2cbcz.js → index-06c2j365.js} +3 -3
  21. package/dist/cli/{index-vn8phy76.js → index-0bf26e0h.js} +1 -1
  22. package/dist/cli/{index-8f0j6kf2.js → index-0gdyd1mx.js} +3 -3
  23. package/dist/cli/{index-f1wqew85.js → index-15836xvt.js} +2 -2
  24. package/dist/cli/{index-98zfmfnn.js → index-16f28gya.js} +4 -4
  25. package/dist/cli/{index-n7vy4gb3.js → index-1cz2j033.js} +6 -6
  26. package/dist/cli/{index-sg2agtt5.js → index-1pfga0cy.js} +1 -1
  27. package/dist/cli/{index-jevq7a7b.js → index-1r5k2b4v.js} +2 -2
  28. package/dist/cli/{index-j9swvmt3.js → index-1xa8wq76.js} +1 -1
  29. package/dist/cli/{index-fbwerevq.js → index-2sc36smx.js} +1 -1
  30. package/dist/cli/{index-dd258pfn.js → index-35ythzj4.js} +4 -4
  31. package/dist/cli/{index-dmnvgc03.js → index-46zge5zc.js} +4 -4
  32. package/dist/cli/{index-9qbn3chx.js → index-6p6m98bb.js} +1 -1
  33. package/dist/cli/{index-txr48a64.js → index-6yb7fhah.js} +38 -38
  34. package/dist/cli/{index-03ng9y76.js → index-71b12k03.js} +7 -7
  35. package/dist/cli/{index-wx43mc8h.js → index-8q8783g0.js} +1 -1
  36. package/dist/cli/{index-z11watrb.js → index-8xabhfwr.js} +2 -2
  37. package/dist/cli/{index-br33a6v7.js → index-99h4ez5x.js} +3 -3
  38. package/dist/cli/{index-vktygb4k.js → index-9bdz8cbx.js} +2 -2
  39. package/dist/cli/{index-cjekszvy.js → index-9c2t70wh.js} +3 -3
  40. package/dist/cli/{index-ykaaejka.js → index-9czp2dcg.js} +3 -3
  41. package/dist/cli/{index-9f7y0rym.js → index-akg9rdt1.js} +36 -36
  42. package/dist/cli/{index-85npnq5t.js → index-aq962xjf.js} +4 -4
  43. package/dist/cli/{index-h83221w1.js → index-d3rjvm9e.js} +3 -3
  44. package/dist/cli/{index-3b71hf2k.js → index-fce5drxa.js} +2 -2
  45. package/dist/cli/{index-0cdkb7e8.js → index-g1avjt26.js} +4 -4
  46. package/dist/cli/{index-5nwfz9bn.js → index-hh7pa3yk.js} +1 -1
  47. package/dist/cli/{index-4ak3ewt2.js → index-hshx5znv.js} +3 -3
  48. package/dist/cli/{index-ar33mkxc.js → index-jp7qd7r4.js} +4 -4
  49. package/dist/cli/{index-w5p9crxx.js → index-jy33tgeb.js} +4 -4
  50. package/dist/cli/{index-jc2ndtdt.js → index-k8sarme1.js} +1 -1
  51. package/dist/cli/{index-p746x44z.js → index-mv2ptr24.js} +4 -4
  52. package/dist/cli/{index-hq7mfqe5.js → index-q9kefh33.js} +1 -1
  53. package/dist/cli/{index-4m7cywkf.js → index-qkhssaay.js} +90 -77
  54. package/dist/cli/{index-3jn6155r.js → index-s0r30djy.js} +1 -1
  55. package/dist/cli/{index-1tgkj4mf.js → index-sqkz9hyj.js} +2 -2
  56. package/dist/cli/{index-4zran0jk.js → index-twb3f4tk.js} +1 -1
  57. package/dist/cli/{index-dmdg2zay.js → index-wrdktgpy.js} +2 -2
  58. package/dist/cli/{index-bjh6cw86.js → index-xhgq58e1.js} +4 -4
  59. package/dist/cli/{index-d95b3yce.js → index-yn5r962a.js} +6 -6
  60. package/dist/cli/{index-bstjg81q.js → index-zfbxfm2m.js} +33 -33
  61. package/dist/cli/index.js +37 -37
  62. package/dist/cli/{knowledge-escalator-c65r55bv.js → knowledge-escalator-h4wqey95.js} +13 -13
  63. package/dist/cli/{knowledge-events-exc94dr2.js → knowledge-events-jdj0kg0x.js} +11 -11
  64. package/dist/cli/{knowledge-link-kgt3zx0c.js → knowledge-link-h4pdcnya.js} +4 -4
  65. package/dist/cli/{knowledge-store-b2qm637m.js → knowledge-store-9pkka657.js} +5 -5
  66. package/dist/cli/{knowledge-validator-44pn1xrn.js → knowledge-validator-2hh4838s.js} +7 -7
  67. package/dist/cli/{mcp-6qjt8ey7.js → mcp-dr2qg42d.js} +1 -1
  68. package/dist/cli/{model-preflight-dh9dadg8.js → model-preflight-t6megn5m.js} +80 -36
  69. package/dist/cli/{pending-delegations-vcqw78d8.js → pending-delegations-96j63y3v.js} +7 -7
  70. package/dist/cli/{pr-subscriptions-2vp2sxjb.js → pr-subscriptions-qrc475pd.js} +7 -7
  71. package/dist/cli/{pr-workflow-gate-cy24tc3c.js → pr-workflow-gate-1hf06vw7.js} +36 -36
  72. package/dist/cli/{runner-zeqpd2c2.js → runner-4hfmp1ag.js} +5 -5
  73. package/dist/cli/{scan-cursor-3hyz0qnh.js → scan-cursor-wfa7239s.js} +6 -6
  74. package/dist/cli/{schema-4s2nnpqt.js → schema-v3z4wgje.js} +2 -2
  75. package/dist/cli/{scope-persistence-1bvaeene.js → scope-persistence-k2zq1h9h.js} +12 -12
  76. package/dist/cli/{server-zb4j57w6.js → server-qk8e60ah.js} +36 -36
  77. package/dist/cli/{skill-generator-fqh79jr7.js → skill-generator-q6jzjcer.js} +15 -15
  78. package/dist/cli/{snapshot-coordination-init-v50k6v2v.js → snapshot-coordination-init-h8cqcmve.js} +36 -36
  79. package/dist/cli/{speckit-checkoff-mcxxpmy4.js → speckit-checkoff-mh45c204.js} +4 -4
  80. package/dist/cli/{telemetry-eq1cwq2x.js → telemetry-kvhe94gs.js} +1 -1
  81. package/dist/cli/{worktree-collision-ownership-fk6spbrf.js → worktree-collision-ownership-hm5y77hr.js} +7 -7
  82. package/dist/cli/{worktree-isolation-ht89tqrc.js → worktree-isolation-tdst4qs1.js} +36 -36
  83. package/dist/host/v2/events.d.ts +19 -1
  84. package/dist/host/v2/model-apply.d.ts +39 -0
  85. package/dist/host/v2/setup.d.ts +0 -35
  86. package/dist/index.js +12 -12
  87. package/dist/models/task-model-routing.d.ts +8 -0
  88. package/dist/services/model-preflight.d.ts +24 -0
  89. package/dist/utils/provider-error-classification.d.ts +30 -4
  90. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.188.5",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",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.188.6",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",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
 
@@ -116,7 +116,7 @@ This is the only sanctioned dispatch path. Don't use \`lean_turbo_run_phase\`; d
116
116
  Phase reviewer + critic still required at \`phase_complete\` (Epic Mode doesn't change Stage B).
117
117
 
118
118
  Audit (no architect needed): \`/swarm epic status | last | decide | calibration\`.
119
- `;var init_constants=__esm(()=>{init_agent_names();init_tool_metadata();init_agent_names();init_merge();OPENCODE_NATIVE_AGENTS=new Set(["build","plan","general","explore","compaction","title","summary"]);CLAUDE_CODE_NATIVE_COMMANDS=freezeSet(["clear","new","reset","resume","continue","exit","quit","compact","fork","branch","undo","checkpoint","rewind","rename","doctor","help","status","statusline","cost","usage","stats","context","debug","insights","recap","release-notes","heapdump","powerup","config","settings","model","effort","fast","theme","color","keybindings","privacy-settings","init","focus","sandbox","terminal-setup","permissions","allowed-tools","security-review","fewer-permission-prompts","plugin","reload-plugins","hooks","mcp","ide","chrome","desktop","app","mobile","ios","android","remote-control","rc","remote-env","login","logout","review","pr-comments","agents","batch","loop","proactive","claude-api","schedule","routines","autofix-pr","plan","diff","export","copy","feedback","bug","btw","add-dir","memory","skills","upgrade","vim","voice","extra-usage","install-github-app","install-slack-app","passes","setup-bedrock","install","tasks","history","term","teleport","ultrareview","ultraplan","web-setup","setup-vertex","tui","simplify","summary","stickers","tp","team-onboarding","bashes"]),OPENCODE_NATIVE_COMMANDS=freezeSet(["plan","new","share","clear","undo","redo","compact","export","help","exit","models","themes","edit","resume","copy","log","messages","summary","tree","session"],"OPENCODE_NATIVE_COMMANDS"),MEMORY_AGENT_TOOL_MAP={architect:["swarm_memory_recall","swarm_memory_propose","swarm_memory_outcome"],explorer:["swarm_memory_recall","swarm_memory_propose","swarm_memory_outcome"],coder:["swarm_memory_recall","swarm_memory_propose","swarm_memory_outcome"],reviewer:["swarm_memory_recall","swarm_memory_outcome"],test_engineer:["swarm_memory_recall","swarm_memory_propose"],sme:["swarm_memory_recall","swarm_memory_propose"],critic:["swarm_memory_recall","swarm_memory_outcome"],critic_sounding_board:["swarm_memory_recall"],critic_drift_verifier:["swarm_memory_recall"],critic_hallucination_verifier:["swarm_memory_recall"],critic_architecture_supervisor:["swarm_memory_recall"],critic_finding_validator:["swarm_memory_recall"],docs:["swarm_memory_recall","swarm_memory_propose"],docs_design:["swarm_memory_recall","swarm_memory_propose"],designer:["swarm_memory_recall","swarm_memory_propose"],curator_init:["swarm_memory_recall"],curator_phase:["swarm_memory_recall"],curator_postmortem:["swarm_memory_recall"],curator_consolidation:["swarm_memory_recall"],skill_improver:["swarm_memory_recall","swarm_memory_propose"],spec_writer:["swarm_memory_recall","swarm_memory_propose"]},EXTERNAL_SKILL_TOOL_NAMES=["external_skill_discover","external_skill_list","external_skill_inspect","external_skill_promote","external_skill_reject","external_skill_delete","external_skill_revoke"],EXTERNAL_SKILL_AGENT_TOOL_MAP={architect:[...EXTERNAL_SKILL_TOOL_NAMES]},COUNCIL_TOOL_NAMES=["submit_council_verdicts","submit_phase_council_verdicts","declare_council_criteria","write_final_council_evidence"],COUNCIL_AGENT_TOOL_MAP={architect:[...COUNCIL_TOOL_NAMES]},GENERAL_COUNCIL_TOOL_NAMES=["convene_general_council","web_search","web_fetch"],GENERAL_COUNCIL_AGENT_TOOL_MAP={architect:[...GENERAL_COUNCIL_TOOL_NAMES]},TURBO_TOOL_NAMES=["lean_turbo_plan_lanes","lean_turbo_acquire_locks","lean_turbo_runner_status","lean_turbo_review","lean_turbo_critic","lean_turbo_run_phase","lean_turbo_status"],TURBO_AGENT_TOOL_MAP={architect:[...TURBO_TOOL_NAMES]},SKILL_TOOL_NAMES=["skill_generate","skill_list","skill_apply","skill_inspect","skill_regenerate","skill_retire","skill_improve"],SKILL_AGENT_TOOL_MAP={architect:[...SKILL_TOOL_NAMES]},PR_REVIEW_CHILD_TOOL_NAMES=["submit_pr_review_result"],PR_REVIEW_CHILD_AGENT_TOOL_MAP={explorer:[...PR_REVIEW_CHILD_TOOL_NAMES]},WRITE_TOOL_NAMES=["write","edit","patch","apply_patch","swarm_apply_patch","create_file","insert","replace","append","prepend","extract_code_blocks"],SUMMARIZER_EXEMPT_TOOL_NAMES=["retrieve_summary","retrieve_lane_output","task","read","dispatch_lanes","dispatch_lanes_async","collect_lane_results","parse_lane_candidates"],DEFAULT_MODELS={explorer:"opencode/big-pickle",coder:"opencode/minimax-m2.5-free",reviewer:"opencode/big-pickle",test_engineer:"opencode/gpt-5-nano",sme:"opencode/big-pickle",researcher:"opencode/big-pickle",critic:"opencode/big-pickle",critic_sounding_board:"opencode/gpt-5-nano",critic_drift_verifier:"opencode/gpt-5-nano",critic_hallucination_verifier:"opencode/gpt-5-nano",critic_oversight:"opencode/gpt-5-nano",critic_architecture_supervisor:"opencode/big-pickle",critic_finding_validator:"opencode/big-pickle",docs:"opencode/big-pickle",docs_design:"opencode/big-pickle",designer:"opencode/big-pickle",curator_init:"opencode/gpt-5-nano",curator_phase:"opencode/gpt-5-nano",curator_postmortem:"opencode/gpt-5-nano",curator_consolidation:"opencode/gpt-5-nano",skill_improver:"opencode/big-pickle",spec_writer:"opencode/big-pickle",default:"opencode/big-pickle"},DEFAULT_AGENT_CONFIGS={coder:{model:"opencode/minimax-m2.5-free",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},reviewer:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},test_engineer:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},explorer:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},sme:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},researcher:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},critic:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},docs:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},docs_design:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},designer:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]},critic_sounding_board:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},critic_drift_verifier:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},critic_hallucination_verifier:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},critic_oversight:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},critic_architecture_supervisor:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano"]},critic_finding_validator:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano"]},curator_init:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},curator_phase:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},curator_postmortem:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},curator_consolidation:{model:"opencode/gpt-5-nano",fallback_models:["opencode/big-pickle"]},skill_improver:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano"]},spec_writer:{model:"opencode/big-pickle",fallback_models:["opencode/gpt-5-nano"]}};DEFAULT_SCORING_CONFIG={enabled:!1,max_candidates:100,weights:{phase:1,current_task:2,blocked_task:1.5,recent_failure:2.5,recent_success:0.5,evidence_presence:1,decision_recency:1.5,dependency_proximity:1},decision_decay:{mode:"exponential",half_life_hours:24},token_ratios:{prose:0.25,code:0.4,markdown:0.3,json:0.35}},LOW_CAPABILITY_MODELS=["mini","nano","small","free"];DEFAULT_LEAN_TURBO_CONFIG={max_parallel_coders:4,require_declared_scope:!0,conflict_policy:"serialize",degrade_on_risk:!0,phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!0,allow_docs_only_without_reviewer:!1,worktree_isolation:!0,merge_strategy:"merge",worktree_dir:void 0,deps_strategy:"skip",runtime_isolation:{enabled:!1,port_stride:1}},DEFAULT_WORKTREE_ISOLATION_CONFIG={policy:"auto",merge_strategy:"merge",worktree_dir:void 0,deps_strategy:"skip",lane_permissions:"scoped_allow",serialization_release_after_dispatches:5,serialization_release_after_ms:60000,session_create_timeout_ms:30000,runtime_isolation:{enabled:!1,port_stride:1}}});function $constructor(name,initializer,params){function init(inst,def){if(!inst._zod)Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1});if(inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer(inst,def);let proto=_.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k=keys[i];if(!(k in inst))inst[k]=proto[k].bind(inst)}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a;let inst=params?.Parent?new Definition:this;init(inst,def),(_a=inst._zod).deferred??(_a.deferred=[]);for(let fn2 of inst._zod.deferred)fn2();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return globalConfig}var NEVER,$brand,$ZodAsyncError,$ZodEncodeError,globalConfig;var init_core=__esm(()=>{NEVER=Object.freeze({status:"aborted"});$brand=Symbol("zod_brand");$ZodAsyncError=class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$ZodEncodeError=class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}};globalConfig={}});var exports_util={};__export(exports_util,{unwrapMessage:()=>unwrapMessage,uint8ArrayToHex:()=>uint8ArrayToHex,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToBase64:()=>uint8ArrayToBase64,stringifyPrimitive:()=>stringifyPrimitive,slugify:()=>slugify,shallowClone:()=>shallowClone,safeExtend:()=>safeExtend,required:()=>required,randomString:()=>randomString,propertyKeyTypes:()=>propertyKeyTypes,promiseAllObject:()=>promiseAllObject,primitiveTypes:()=>primitiveTypes,prefixIssues:()=>prefixIssues,pick:()=>pick,partial:()=>partial,parsedType:()=>parsedType,optionalKeys:()=>optionalKeys,omit:()=>omit,objectClone:()=>objectClone,numKeys:()=>numKeys,nullish:()=>nullish,normalizeParams:()=>normalizeParams,mergeDefs:()=>mergeDefs,merge:()=>merge,jsonStringifyReplacer:()=>jsonStringifyReplacer,joinValues:()=>joinValues,issue:()=>issue,isPlainObject:()=>isPlainObject,isObject:()=>isObject,hexToUint8Array:()=>hexToUint8Array,getSizableOrigin:()=>getSizableOrigin,getParsedType:()=>getParsedType,getLengthableOrigin:()=>getLengthableOrigin,getEnumValues:()=>getEnumValues,getElementAtPath:()=>getElementAtPath,floatSafeRemainder:()=>floatSafeRemainder,finalizeIssue:()=>finalizeIssue,extend:()=>extend,escapeRegex:()=>escapeRegex,esc:()=>esc,defineLazy:()=>defineLazy,createTransparentProxy:()=>createTransparentProxy,cloneDef:()=>cloneDef,clone:()=>clone,cleanRegex:()=>cleanRegex,cleanEnum:()=>cleanEnum,captureStackTrace:()=>captureStackTrace,cached:()=>cached,base64urlToUint8Array:()=>base64urlToUint8Array,base64ToUint8Array:()=>base64ToUint8Array,assignProp:()=>assignProp,assertNotEqual:()=>assertNotEqual,assertNever:()=>assertNever,assertIs:()=>assertIs,assertEqual:()=>assertEqual,assert:()=>assert,allowsEval:()=>allowsEval,aborted:()=>aborted,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,Class:()=>Class,BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter((v)=>typeof v==="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues(array,separator="|"){return array.map((val)=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){if(typeof value==="bigint")return value.toString();return value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw Error("cached value already set")}}}function nullish(input){return input===null||input===void 0}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString(),stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){let match=stepString.match(/\d?e-(\d?)/);if(match?.[1])stepDecCount=Number.parseInt(match[1])}let decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}function defineLazy(object,key,getter){let value=void 0;Object.defineProperty(object,key,{get(){if(value===EVALUATING)return;if(value===void 0)value=EVALUATING,value=getter();return value},set(v){Object.defineProperty(object,key,{value:v})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){if(!path)return obj;return path.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map((key)=>promisesObj[key]);return Promise.all(promises).then((results)=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let str="";for(let i=0;i<length;i++)str+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;if(typeof ctor!=="function")return!0;let prot=ctor.prototype;if(isObject(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}function shallowClone(o){if(isPlainObject(o))return{...o};if(Array.isArray(o))return[...o];return o}function numKeys(data){let keyCount=0;for(let key in data)if(Object.prototype.hasOwnProperty.call(data,key))keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional"})}function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;newShape[key]=currDef.shape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function merge(a,b){let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone(a,def)}function partial(Class,schema,mask){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=Class?new Class({type:"optional",innerType:oldShape[key]}):oldShape[key]}else for(let key in oldShape)shape[key]=Class?new Class({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required(Class,schema,mask){let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=new Class({type:"nonoptional",innerType:oldShape[key]})}else for(let key in oldShape)shape[key]=new Class({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema,def)}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues(path,issues){return issues.map((iss)=>{var _a;return(_a=iss).path??(_a.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){let full={...iss,path:iss.path??[]};if(!iss.message){let message=unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input";full.message=message}if(delete full.inst,delete full.continue,!ctx?.reportInput)delete full.input;return full}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args2){let[iss,input,inst]=args2;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array(base64){let binaryString=atob(base64),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url){let base64=base64url.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base64.length%4)%4);return base64ToUint8Array(base64+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class{constructor(..._args){}}var EVALUATING,captureStackTrace,allowsEval,getParsedType=(data)=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data))return"array";if(data===null)return"null";if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return"promise";if(typeof Map<"u"&&data instanceof Map)return"map";if(typeof Set<"u"&&data instanceof Set)return"set";if(typeof Date<"u"&&data instanceof Date)return"date";if(typeof File<"u"&&data instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES;var init_util=__esm(()=>{EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function flattenError(error,mapper=(issue2)=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error.issues)if(sub.path.length>0)fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub));else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error,mapper=(issue2)=>issue2.message){let fieldErrors={_errors:[]},processError=(error2)=>{for(let issue2 of error2.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map((issues)=>processError({issues}));else if(issue2.code==="invalid_key")processError({issues:issue2.issues});else if(issue2.code==="invalid_element")processError({issues:issue2.issues});else if(issue2.path.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;while(i<issue2.path.length){let el=issue2.path[i];if(i!==issue2.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2));curr=curr[el],i++}}};return processError(error),fieldErrors}function treeifyError(error,mapper=(issue2)=>issue2.message){let result={errors:[]},processError=(error2,path=[])=>{var _a,_b;for(let issue2 of error2.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map((issues)=>processError({issues},issue2.path));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},issue2.path);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},issue2.path);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result,i=0;while(i<fullpath.length){let el=fullpath[i],terminal=i===fullpath.length-1;if(typeof el==="string")curr.properties??(curr.properties={}),(_a=curr.properties)[el]??(_a[el]={errors:[]}),curr=curr.properties[el];else curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el];if(terminal)curr.errors.push(mapper(issue2));i++}}};return processError(error),result}function toDotPath(_path){let segs=[],path=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(let seg of path)if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}return segs.join("")}function prettifyError(error){let lines=[],issues=[...error.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue2 of issues)if(lines.push(`✖ ${issue2.message}`),issue2.path?.length)lines.push(` → at ${toDotPath(issue2.path)}`);return lines.join(`
119
+ `;var init_constants=__esm(()=>{init_agent_names();init_tool_metadata();init_agent_names();init_merge();OPENCODE_NATIVE_AGENTS=new Set(["build","plan","general","explore","compaction","title","summary"]);CLAUDE_CODE_NATIVE_COMMANDS=freezeSet(["clear","new","reset","resume","continue","exit","quit","compact","fork","branch","undo","checkpoint","rewind","rename","doctor","help","status","statusline","cost","usage","stats","context","debug","insights","recap","release-notes","heapdump","powerup","config","settings","model","effort","fast","theme","color","keybindings","privacy-settings","init","focus","sandbox","terminal-setup","permissions","allowed-tools","security-review","fewer-permission-prompts","plugin","reload-plugins","hooks","mcp","ide","chrome","desktop","app","mobile","ios","android","remote-control","rc","remote-env","login","logout","review","pr-comments","agents","batch","loop","proactive","claude-api","schedule","routines","autofix-pr","plan","diff","export","copy","feedback","bug","btw","add-dir","memory","skills","upgrade","vim","voice","extra-usage","install-github-app","install-slack-app","passes","setup-bedrock","install","tasks","history","term","teleport","ultrareview","ultraplan","web-setup","setup-vertex","tui","simplify","summary","stickers","tp","team-onboarding","bashes"]),OPENCODE_NATIVE_COMMANDS=freezeSet(["plan","new","share","clear","undo","redo","compact","export","help","exit","models","themes","edit","resume","copy","log","messages","summary","tree","session"],"OPENCODE_NATIVE_COMMANDS"),MEMORY_AGENT_TOOL_MAP={architect:["swarm_memory_recall","swarm_memory_propose","swarm_memory_outcome"],explorer:["swarm_memory_recall","swarm_memory_propose","swarm_memory_outcome"],coder:["swarm_memory_recall","swarm_memory_propose","swarm_memory_outcome"],reviewer:["swarm_memory_recall","swarm_memory_outcome"],test_engineer:["swarm_memory_recall","swarm_memory_propose"],sme:["swarm_memory_recall","swarm_memory_propose"],critic:["swarm_memory_recall","swarm_memory_outcome"],critic_sounding_board:["swarm_memory_recall"],critic_drift_verifier:["swarm_memory_recall"],critic_hallucination_verifier:["swarm_memory_recall"],critic_architecture_supervisor:["swarm_memory_recall"],critic_finding_validator:["swarm_memory_recall"],docs:["swarm_memory_recall","swarm_memory_propose"],docs_design:["swarm_memory_recall","swarm_memory_propose"],designer:["swarm_memory_recall","swarm_memory_propose"],curator_init:["swarm_memory_recall"],curator_phase:["swarm_memory_recall"],curator_postmortem:["swarm_memory_recall"],curator_consolidation:["swarm_memory_recall"],skill_improver:["swarm_memory_recall","swarm_memory_propose"],spec_writer:["swarm_memory_recall","swarm_memory_propose"]},EXTERNAL_SKILL_TOOL_NAMES=["external_skill_discover","external_skill_list","external_skill_inspect","external_skill_promote","external_skill_reject","external_skill_delete","external_skill_revoke"],EXTERNAL_SKILL_AGENT_TOOL_MAP={architect:[...EXTERNAL_SKILL_TOOL_NAMES]},COUNCIL_TOOL_NAMES=["submit_council_verdicts","submit_phase_council_verdicts","declare_council_criteria","write_final_council_evidence"],COUNCIL_AGENT_TOOL_MAP={architect:[...COUNCIL_TOOL_NAMES]},GENERAL_COUNCIL_TOOL_NAMES=["convene_general_council","web_search","web_fetch"],GENERAL_COUNCIL_AGENT_TOOL_MAP={architect:[...GENERAL_COUNCIL_TOOL_NAMES]},TURBO_TOOL_NAMES=["lean_turbo_plan_lanes","lean_turbo_acquire_locks","lean_turbo_runner_status","lean_turbo_review","lean_turbo_critic","lean_turbo_run_phase","lean_turbo_status"],TURBO_AGENT_TOOL_MAP={architect:[...TURBO_TOOL_NAMES]},SKILL_TOOL_NAMES=["skill_generate","skill_list","skill_apply","skill_inspect","skill_regenerate","skill_retire","skill_improve"],SKILL_AGENT_TOOL_MAP={architect:[...SKILL_TOOL_NAMES]},PR_REVIEW_CHILD_TOOL_NAMES=["submit_pr_review_result"],PR_REVIEW_CHILD_AGENT_TOOL_MAP={explorer:[...PR_REVIEW_CHILD_TOOL_NAMES]},WRITE_TOOL_NAMES=["write","edit","patch","apply_patch","swarm_apply_patch","create_file","insert","replace","append","prepend","extract_code_blocks"],SUMMARIZER_EXEMPT_TOOL_NAMES=["retrieve_summary","retrieve_lane_output","task","read","dispatch_lanes","dispatch_lanes_async","collect_lane_results","parse_lane_candidates"],DEFAULT_MODELS={explorer:"opencode/big-pickle",coder:"opencode/nemotron-3-ultra-free",reviewer:"opencode/big-pickle",test_engineer:"opencode/mimo-v2.6-flash-free",sme:"opencode/big-pickle",researcher:"opencode/big-pickle",critic:"opencode/big-pickle",critic_sounding_board:"opencode/mimo-v2.6-flash-free",critic_drift_verifier:"opencode/mimo-v2.6-flash-free",critic_hallucination_verifier:"opencode/mimo-v2.6-flash-free",critic_oversight:"opencode/mimo-v2.6-flash-free",critic_architecture_supervisor:"opencode/big-pickle",critic_finding_validator:"opencode/big-pickle",docs:"opencode/big-pickle",docs_design:"opencode/big-pickle",designer:"opencode/big-pickle",curator_init:"opencode/mimo-v2.6-flash-free",curator_phase:"opencode/mimo-v2.6-flash-free",curator_postmortem:"opencode/mimo-v2.6-flash-free",curator_consolidation:"opencode/mimo-v2.6-flash-free",skill_improver:"opencode/big-pickle",spec_writer:"opencode/big-pickle",default:"opencode/big-pickle"},DEFAULT_AGENT_CONFIGS={coder:{model:"opencode/nemotron-3-ultra-free",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},reviewer:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},test_engineer:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},explorer:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},sme:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},researcher:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},critic:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},docs:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},docs_design:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},designer:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free","opencode/big-pickle"]},critic_sounding_board:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},critic_drift_verifier:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},critic_hallucination_verifier:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},critic_oversight:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},critic_architecture_supervisor:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free"]},critic_finding_validator:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free"]},curator_init:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},curator_phase:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},curator_postmortem:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},curator_consolidation:{model:"opencode/mimo-v2.6-flash-free",fallback_models:["opencode/big-pickle"]},skill_improver:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free"]},spec_writer:{model:"opencode/big-pickle",fallback_models:["opencode/mimo-v2.6-flash-free"]}};DEFAULT_SCORING_CONFIG={enabled:!1,max_candidates:100,weights:{phase:1,current_task:2,blocked_task:1.5,recent_failure:2.5,recent_success:0.5,evidence_presence:1,decision_recency:1.5,dependency_proximity:1},decision_decay:{mode:"exponential",half_life_hours:24},token_ratios:{prose:0.25,code:0.4,markdown:0.3,json:0.35}},LOW_CAPABILITY_MODELS=["mini","nano","small","free"];DEFAULT_LEAN_TURBO_CONFIG={max_parallel_coders:4,require_declared_scope:!0,conflict_policy:"serialize",degrade_on_risk:!0,phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!0,allow_docs_only_without_reviewer:!1,worktree_isolation:!0,merge_strategy:"merge",worktree_dir:void 0,deps_strategy:"skip",runtime_isolation:{enabled:!1,port_stride:1}},DEFAULT_WORKTREE_ISOLATION_CONFIG={policy:"auto",merge_strategy:"merge",worktree_dir:void 0,deps_strategy:"skip",lane_permissions:"scoped_allow",serialization_release_after_dispatches:5,serialization_release_after_ms:60000,session_create_timeout_ms:30000,runtime_isolation:{enabled:!1,port_stride:1}}});function $constructor(name,initializer,params){function init(inst,def){if(!inst._zod)Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1});if(inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer(inst,def);let proto=_.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k=keys[i];if(!(k in inst))inst[k]=proto[k].bind(inst)}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a;let inst=params?.Parent?new Definition:this;init(inst,def),(_a=inst._zod).deferred??(_a.deferred=[]);for(let fn2 of inst._zod.deferred)fn2();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return globalConfig}var NEVER,$brand,$ZodAsyncError,$ZodEncodeError,globalConfig;var init_core=__esm(()=>{NEVER=Object.freeze({status:"aborted"});$brand=Symbol("zod_brand");$ZodAsyncError=class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$ZodEncodeError=class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}};globalConfig={}});var exports_util={};__export(exports_util,{unwrapMessage:()=>unwrapMessage,uint8ArrayToHex:()=>uint8ArrayToHex,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToBase64:()=>uint8ArrayToBase64,stringifyPrimitive:()=>stringifyPrimitive,slugify:()=>slugify,shallowClone:()=>shallowClone,safeExtend:()=>safeExtend,required:()=>required,randomString:()=>randomString,propertyKeyTypes:()=>propertyKeyTypes,promiseAllObject:()=>promiseAllObject,primitiveTypes:()=>primitiveTypes,prefixIssues:()=>prefixIssues,pick:()=>pick,partial:()=>partial,parsedType:()=>parsedType,optionalKeys:()=>optionalKeys,omit:()=>omit,objectClone:()=>objectClone,numKeys:()=>numKeys,nullish:()=>nullish,normalizeParams:()=>normalizeParams,mergeDefs:()=>mergeDefs,merge:()=>merge,jsonStringifyReplacer:()=>jsonStringifyReplacer,joinValues:()=>joinValues,issue:()=>issue,isPlainObject:()=>isPlainObject,isObject:()=>isObject,hexToUint8Array:()=>hexToUint8Array,getSizableOrigin:()=>getSizableOrigin,getParsedType:()=>getParsedType,getLengthableOrigin:()=>getLengthableOrigin,getEnumValues:()=>getEnumValues,getElementAtPath:()=>getElementAtPath,floatSafeRemainder:()=>floatSafeRemainder,finalizeIssue:()=>finalizeIssue,extend:()=>extend,escapeRegex:()=>escapeRegex,esc:()=>esc,defineLazy:()=>defineLazy,createTransparentProxy:()=>createTransparentProxy,cloneDef:()=>cloneDef,clone:()=>clone,cleanRegex:()=>cleanRegex,cleanEnum:()=>cleanEnum,captureStackTrace:()=>captureStackTrace,cached:()=>cached,base64urlToUint8Array:()=>base64urlToUint8Array,base64ToUint8Array:()=>base64ToUint8Array,assignProp:()=>assignProp,assertNotEqual:()=>assertNotEqual,assertNever:()=>assertNever,assertIs:()=>assertIs,assertEqual:()=>assertEqual,assert:()=>assert,allowsEval:()=>allowsEval,aborted:()=>aborted,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,Class:()=>Class,BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter((v)=>typeof v==="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues(array,separator="|"){return array.map((val)=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){if(typeof value==="bigint")return value.toString();return value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw Error("cached value already set")}}}function nullish(input){return input===null||input===void 0}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString(),stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){let match=stepString.match(/\d?e-(\d?)/);if(match?.[1])stepDecCount=Number.parseInt(match[1])}let decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}function defineLazy(object,key,getter){let value=void 0;Object.defineProperty(object,key,{get(){if(value===EVALUATING)return;if(value===void 0)value=EVALUATING,value=getter();return value},set(v){Object.defineProperty(object,key,{value:v})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){if(!path)return obj;return path.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map((key)=>promisesObj[key]);return Promise.all(promises).then((results)=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let str="";for(let i=0;i<length;i++)str+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;if(typeof ctor!=="function")return!0;let prot=ctor.prototype;if(isObject(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}function shallowClone(o){if(isPlainObject(o))return{...o};if(Array.isArray(o))return[...o];return o}function numKeys(data){let keyCount=0;for(let key in data)if(Object.prototype.hasOwnProperty.call(data,key))keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional"})}function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;newShape[key]=currDef.shape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape))throw Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function merge(a,b){let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone(a,def)}function partial(Class,schema,mask){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=Class?new Class({type:"optional",innerType:oldShape[key]}):oldShape[key]}else for(let key in oldShape)shape[key]=Class?new Class({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required(Class,schema,mask){let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=new Class({type:"nonoptional",innerType:oldShape[key]})}else for(let key in oldShape)shape[key]=new Class({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema,def)}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues(path,issues){return issues.map((iss)=>{var _a;return(_a=iss).path??(_a.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){let full={...iss,path:iss.path??[]};if(!iss.message){let message=unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input";full.message=message}if(delete full.inst,delete full.continue,!ctx?.reportInput)delete full.input;return full}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args2){let[iss,input,inst]=args2;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array(base64){let binaryString=atob(base64),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url){let base64=base64url.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base64.length%4)%4);return base64ToUint8Array(base64+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class{constructor(..._args){}}var EVALUATING,captureStackTrace,allowsEval,getParsedType=(data)=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data))return"array";if(data===null)return"null";if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return"promise";if(typeof Map<"u"&&data instanceof Map)return"map";if(typeof Set<"u"&&data instanceof Set)return"set";if(typeof Date<"u"&&data instanceof Date)return"date";if(typeof File<"u"&&data instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES;var init_util=__esm(()=>{EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function flattenError(error,mapper=(issue2)=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error.issues)if(sub.path.length>0)fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub));else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error,mapper=(issue2)=>issue2.message){let fieldErrors={_errors:[]},processError=(error2)=>{for(let issue2 of error2.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map((issues)=>processError({issues}));else if(issue2.code==="invalid_key")processError({issues:issue2.issues});else if(issue2.code==="invalid_element")processError({issues:issue2.issues});else if(issue2.path.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;while(i<issue2.path.length){let el=issue2.path[i];if(i!==issue2.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2));curr=curr[el],i++}}};return processError(error),fieldErrors}function treeifyError(error,mapper=(issue2)=>issue2.message){let result={errors:[]},processError=(error2,path=[])=>{var _a,_b;for(let issue2 of error2.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map((issues)=>processError({issues},issue2.path));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},issue2.path);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},issue2.path);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result,i=0;while(i<fullpath.length){let el=fullpath[i],terminal=i===fullpath.length-1;if(typeof el==="string")curr.properties??(curr.properties={}),(_a=curr.properties)[el]??(_a[el]={errors:[]}),curr=curr.properties[el];else curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el];if(terminal)curr.errors.push(mapper(issue2));i++}}};return processError(error),result}function toDotPath(_path){let segs=[],path=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(let seg of path)if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}return segs.join("")}function prettifyError(error){let lines=[],issues=[...error.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue2 of issues)if(lines.push(`✖ ${issue2.message}`),issue2.path?.length)lines.push(` → at ${toDotPath(issue2.path)}`);return lines.join(`
120
120
  `)}var initializer=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError,$ZodRealError;var init_errors=__esm(()=>{init_core();init_util();$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})});var _parse=(_Err)=>(schema,value,_ctx,_params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!1}):{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},parse,_parseAsync=(_Err)=>async(schema,value,_ctx,params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){let e=new(params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},parseAsync,_safeParse=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse,_safeParseAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?{success:!1,error:new _Err(result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync,_encode=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parse(_Err)(schema,value,ctx)},encode,_decode=(_Err)=>(schema,value,_ctx)=>{return _parse(_Err)(schema,value,_ctx)},decode,_encodeAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)},encodeAsync,_decodeAsync=(_Err)=>async(schema,value,_ctx)=>{return _parseAsync(_Err)(schema,value,_ctx)},decodeAsync,_safeEncode=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},safeEncode,_safeDecode=(_Err)=>(schema,value,_ctx)=>{return _safeParse(_Err)(schema,value,_ctx)},safeDecode,_safeEncodeAsync=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},safeEncodeAsync,_safeDecodeAsync=(_Err)=>async(schema,value,_ctx)=>{return _safeParseAsync(_Err)(schema,value,_ctx)},safeDecodeAsync;var init_parse=__esm(()=>{init_core();init_errors();init_util();parse=_parse($ZodRealError),parseAsync=_parseAsync($ZodRealError),safeParse=_safeParse($ZodRealError),safeParseAsync=_safeParseAsync($ZodRealError),encode=_encode($ZodRealError),decode=_decode($ZodRealError),encodeAsync=_encodeAsync($ZodRealError),decodeAsync=_decodeAsync($ZodRealError),safeEncode=_safeEncode($ZodRealError),safeDecode=_safeDecode($ZodRealError),safeEncodeAsync=_safeEncodeAsync($ZodRealError),safeDecodeAsync=_safeDecodeAsync($ZodRealError)});var exports_regexes={};__export(exports_regexes,{xid:()=>xid,uuid7:()=>uuid7,uuid6:()=>uuid6,uuid4:()=>uuid4,uuid:()=>uuid,uppercase:()=>uppercase,unicodeEmail:()=>unicodeEmail,undefined:()=>_undefined,ulid:()=>ulid,time:()=>time,string:()=>string,sha512_hex:()=>sha512_hex,sha512_base64url:()=>sha512_base64url,sha512_base64:()=>sha512_base64,sha384_hex:()=>sha384_hex,sha384_base64url:()=>sha384_base64url,sha384_base64:()=>sha384_base64,sha256_hex:()=>sha256_hex,sha256_base64url:()=>sha256_base64url,sha256_base64:()=>sha256_base64,sha1_hex:()=>sha1_hex,sha1_base64url:()=>sha1_base64url,sha1_base64:()=>sha1_base64,rfc5322Email:()=>rfc5322Email,number:()=>number,null:()=>_null,nanoid:()=>nanoid,md5_hex:()=>md5_hex,md5_base64url:()=>md5_base64url,md5_base64:()=>md5_base64,mac:()=>mac,lowercase:()=>lowercase,ksuid:()=>ksuid,ipv6:()=>ipv6,ipv4:()=>ipv4,integer:()=>integer,idnEmail:()=>idnEmail,html5Email:()=>html5Email,hostname:()=>hostname,hex:()=>hex,guid:()=>guid,extendedDuration:()=>extendedDuration,emoji:()=>emoji,email:()=>email,e164:()=>e164,duration:()=>duration,domain:()=>domain,datetime:()=>datetime,date:()=>date,cuid2:()=>cuid2,cuid:()=>cuid,cidrv6:()=>cidrv6,cidrv4:()=>cidrv4,browserEmail:()=>browserEmail,boolean:()=>boolean,bigint:()=>bigint,base64url:()=>base64url,base64:()=>base64});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args2){return typeof args2.precision==="number"?args2.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":args2.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${args2.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function time(args2){return new RegExp(`^${timeSource(args2)}$`)}function datetime(args2){let time2=timeSource({precision:args2.precision}),opts=["Z"];if(args2.local)opts.push("");if(args2.offset)opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time2}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}function fixedBase64(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,extendedDuration,guid,uuid=(version)=>{if(!version)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},uuid4,uuid6,uuid7,email,html5Email,rfc5322Email,unicodeEmail,idnEmail,browserEmail,_emoji="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ipv4,ipv6,mac=(delimiter)=>{let escapedDelim=escapeRegex(delimiter??":");return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`)},cidrv4,cidrv6,base64,base64url,hostname,domain,e164,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date,string=(params)=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint,integer,number,boolean,_null,_undefined,lowercase,uppercase,hex,md5_hex,md5_base64,md5_base64url,sha1_hex,sha1_base64,sha1_base64url,sha256_hex,sha256_base64,sha256_base64url,sha384_hex,sha384_base64,sha384_base64url,sha512_hex,sha512_base64,sha512_base64url;var init_regexes=__esm(()=>{init_util();cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid4=uuid(4),uuid6=uuid(6),uuid7=uuid(7),email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail=unicodeEmail,browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,e164=/^\+[1-9]\d{6,14}$/,date=new RegExp(`^${dateSource}$`);bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,_undefined=/^undefined$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,hex=/^[0-9a-fA-F]*$/;md5_hex=/^[0-9a-fA-F]{32}$/,md5_base64=fixedBase64(22,"=="),md5_base64url=fixedBase64url(22),sha1_hex=/^[0-9a-fA-F]{40}$/,sha1_base64=fixedBase64(27,"="),sha1_base64url=fixedBase64url(27),sha256_hex=/^[0-9a-fA-F]{64}$/,sha256_base64=fixedBase64(43,"="),sha256_base64url=fixedBase64url(43),sha384_hex=/^[0-9a-fA-F]{96}$/,sha384_base64=fixedBase64(64,""),sha384_base64url=fixedBase64url(64),sha512_hex=/^[0-9a-fA-F]{128}$/,sha512_base64=fixedBase64(86,"=="),sha512_base64url=fixedBase64url(86)});function handleCheckPropertyResult(result,payload,property){if(result.issues.length)payload.issues.push(...prefixIssues(property,result.issues))}var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckBigIntFormat,$ZodCheckMaxSize,$ZodCheckMinSize,$ZodCheckSizeEquals,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckProperty,$ZodCheckMimeType,$ZodCheckOverwrite;var init_checks=__esm(()=>{init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a;inst._zod??(inst._zod={}),inst._zod.def=def,(_a=inst._zod).onattach??(_a.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(def.value<curr)if(def.inclusive)bag.maximum=def.value;else bag.exclusiveMaximum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value)return;payload.issues.push({origin,code:"too_big",maximum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(def.value>curr)if(def.inclusive)bag.minimum=def.value;else bag.exclusiveMinimum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value)return;payload.issues.push({origin,code:"too_small",minimum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.onattach.push((inst2)=>{var _a;(_a=inst2._zod.bag).multipleOf??(_a.multipleOf=def.value)}),inst._zod.check=(payload)=>{if(typeof payload.value!==typeof def.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof payload.value==="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt)bag.pattern=integer}),inst._zod.check=(payload)=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0)payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});else payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}if(input<minimum)payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck.init(inst,def);let[minimum,maximum]=BIGINT_FORMAT_RANGES[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input<minimum)payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=(payload)=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=(payload)=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=(payload)=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.size,bag.maximum=def.size,bag.size=def.size}),inst._zod.check=(payload)=>{let input=payload.value,size=input.size;if(size===def.size)return;let tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=(payload)=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=(payload)=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=(payload)=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=(payload)=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a,_b;if($ZodCheck.init(inst,def),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,def.pattern)bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern)}),def.pattern)(_a=inst._zod).check??(_a.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position==="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty=$constructor("$ZodCheckProperty",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=(payload)=>{let result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise)return result.then((result2)=>handleCheckPropertyResult(result2,payload,def.property));handleCheckPropertyResult(result,payload,def.property);return}}),$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(inst,def)=>{$ZodCheck.init(inst,def);let mimeSet=new Set(def.mime);inst._zod.onattach.push((inst2)=>{inst2._zod.bag.mime=def.mime}),inst._zod.check=(payload)=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=(payload)=>{payload.value=def.tx(payload.value)}})});class Doc{constructor(args2=[]){if(this.content=[],this.indent=0,this)this.args=args2}indented(fn2){this.indent+=1,fn2(this),this.indent-=1}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
121
121
  `).filter((x)=>x),minIndent=Math.min(...lines.map((x)=>x.length-x.trimStart().length)),dedented=lines.map((x)=>x.slice(minIndent)).map((x)=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,args2=this?.args,lines=[...(this?.content??[""]).map((x)=>` ${x}`)];return new F(...args2,lines.join(`
122
122
  `))}}var version;var init_versions=__esm(()=>{version={major:4,minor:3,patch:6}});function isValidBase64(data){if(data==="")return!0;if(data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64url.test(data))return!1;let base642=data.replace(/[-_]/g,(c)=>c==="-"?"+":"/"),padded=base642.padEnd(Math.ceil(base642.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));if("typ"in parsedHeader&&parsedHeader?.typ!=="JWT")return!1;if(!parsedHeader.alg)return!1;if(algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))return!1;return!0}catch{return!1}}function handleArrayResult(result,final,index){if(result.issues.length)final.issues.push(...prefixIssues(index,result.issues));final.value[index]=result.value}function handlePropertyResult(result,final,key,input,isOptionalOut){if(result.issues.length){if(isOptionalOut&&!(key in input))return;final.issues.push(...prefixIssues(key,result.issues))}if(result.value===void 0){if(key in input)final.value[key]=void 0}else final.value[key]=result.value}function normalizeDef(def){let keys=Object.keys(def.shape);for(let k of keys)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${k}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,keys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,isOptionalOut=_catchall.optout==="optional";for(let key in input){if(keySet.has(key))continue;if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);if(r instanceof Promise)proms.push(r.then((r2)=>handlePropertyResult(r2,payload,key,input,isOptionalOut)));else handlePropertyResult(r,payload,key,input,isOptionalOut)}if(unrecognized.length)payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst});if(!proms.length)return payload;return Promise.all(proms).then(()=>{return payload})}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter((r)=>!aborted(r));if(nonaborted.length===1)return final.value=nonaborted[0].value,nonaborted[0];return final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))}),final}function handleExclusiveUnionResults(results,final,inst,ctx){let successes=results.filter((r)=>r.issues.length===0);if(successes.length===1)return final.value=successes[0].value,final;if(successes.length===0)final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))});else final.issues.push({code:"invalid_union",input:final.value,inst,errors:[],inclusive:!1});return final}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a===+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter((key)=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(let k of iss.keys){if(!unrecKeys.has(k))unrecKeys.set(k,{});unrecKeys.get(k).l=!0}}else result.issues.push(iss);for(let iss of right.issues)if(iss.code==="unrecognized_keys")for(let k of iss.keys){if(!unrecKeys.has(k))unrecKeys.set(k,{});unrecKeys.get(k).r=!0}else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length&&unrecIssue)result.issues.push({...unrecIssue,keys:bothKeys});if(aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}function handleTupleResult(result,final,index){if(result.issues.length)final.issues.push(...prefixIssues(index,result.issues));final.value[index]=result.value}function handleMapResult(keyResult,valueResult,final,key,input,inst,ctx){if(keyResult.issues.length)if(propertyKeyTypes.has(typeof key))final.issues.push(...prefixIssues(key,keyResult.issues));else final.issues.push({code:"invalid_key",origin:"map",input,inst,issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config()))});if(valueResult.issues.length)if(propertyKeyTypes.has(typeof key))final.issues.push(...prefixIssues(key,valueResult.issues));else final.issues.push({origin:"map",code:"invalid_element",input,inst,key,issues:valueResult.issues.map((iss)=>finalizeIssue(iss,ctx,config()))});final.value.set(keyResult.value,valueResult.value)}function handleSetResult(result,final){if(result.issues.length)final.issues.push(...result.issues);final.value.add(result.value)}function handleOptionalResult(result,input){if(result.issues.length&&input===void 0)return{issues:[],value:void 0};return result}function handleDefaultResult(payload,def){if(payload.value===void 0)payload.value=def.defaultValue;return payload}function handleNonOptionalResult(payload,inst){if(!payload.issues.length&&payload.value===void 0)payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst});return payload}function handlePipeResult(left,next,ctx){if(left.issues.length)return left.aborted=!0,left;return next._zod.run({value:left.value,issues:left.issues},ctx)}function handleCodecAResult(result,def,ctx){if(result.issues.length)return result.aborted=!0,result;if((ctx.direction||"forward")==="forward"){let transformed=def.transform(result.value,result);if(transformed instanceof Promise)return transformed.then((value)=>handleCodecTxResult(result,value,def.out,ctx));return handleCodecTxResult(result,transformed,def.out,ctx)}else{let transformed=def.reverseTransform(result.value,result);if(transformed instanceof Promise)return transformed.then((value)=>handleCodecTxResult(result,value,def.in,ctx));return handleCodecTxResult(result,transformed,def.in,ctx)}}function handleCodecTxResult(left,value,nextSchema,ctx){if(left.issues.length)return left.aborted=!0,left;return nextSchema._zod.run({value,issues:left.issues},ctx)}function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};if(inst._zod.def.params)_iss.params=inst._zod.def.params;payload.issues.push(issue(_iss))}}var $ZodType,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,$ZodIPv6,$ZodMAC,$ZodCIDRv4,$ZodCIDRv6,$ZodBase64,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodCustomStringFormat,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodBigIntFormat,$ZodSymbol,$ZodUndefined,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodVoid,$ZodDate,$ZodArray,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodXor,$ZodDiscriminatedUnion,$ZodIntersection,$ZodTuple,$ZodRecord,$ZodMap,$ZodSet,$ZodEnum,$ZodLiteral,$ZodFile,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodSuccess,$ZodCatch,$ZodNaN,$ZodPipe,$ZodCodec,$ZodReadonly,$ZodTemplateLiteral,$ZodFunction,$ZodPromise,$ZodLazy,$ZodCustom;var init_schemas=__esm(()=>{init_checks();init_core();init_parse();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];if(inst._zod.traits.has("$ZodCheck"))checks.unshift(inst);for(let ch of checks)for(let fn2 of ch._zod.onattach)fn2(inst);if(checks.length===0)(_a=inst._zod).deferred??(_a.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{if(await _,payload.issues.length===currLen)return;if(!isAborted)isAborted=aborted(payload,currLen)});else{if(payload.issues.length===currLen)continue;if(!isAborted)isAborted=aborted(payload,currLen)}}if(asyncResult)return asyncResult.then(()=>{return payload});return payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then((checkResult2)=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});if(canary instanceof Promise)return canary.then((canary2)=>{return handleCanaryResult(canary2,payload,ctx)});return handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then((result2)=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:(value)=>{try{let r=safeParse(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(_){return safeParseAsync(inst,value).then((r)=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag),inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch(_2){}if(typeof payload.value==="string")return payload;return payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v===void 0)throw Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{try{let trimmed=payload.value.trim(),url=new URL(trimmed);if(def.hostname){if(def.hostname.lastIndex=0,!def.hostname.test(url.hostname))payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})}if(def.protocol){if(def.protocol.lastIndex=0,!def.protocol.test(url.protocol.endsWith(":")?url.protocol.slice(0,-1):url.protocol))payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})}if(def.normalize)payload.value=url.href;else payload.value=trimmed;return}catch(_){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv6",inst._zod.check=(payload)=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}}),$ZodMAC=$constructor("$ZodMAC",(inst,def)=>{def.pattern??(def.pattern=mac(def.delimiter)),$ZodStringFormat.init(inst,def),inst._zod.bag.format="mac"}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{let parts=payload.value.split("/");try{if(parts.length!==2)throw Error();let[address,prefix]=parts;if(!prefix)throw Error();let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw Error();if(prefixNum<0||prefixNum>128)throw Error();new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64",inst._zod.check=(payload)=>{if(isValidBase64(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64url",inst._zod.check=(payload)=>{if(isValidBase64URL(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(isValidJWT(payload.value,def.alg))return;payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=(payload)=>{if(def.fn(payload.value))return;payload.issues.push({code:"invalid_format",format:def.format,input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=inst._zod.bag.pattern??number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch(_){}let input=payload.value;if(typeof input==="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input==="number"?Number.isNaN(input)?"NaN":!Number.isFinite(input)?"Infinity":void 0:void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Boolean(payload.value)}catch(_){}let input=payload.value;if(typeof input==="boolean")return payload;return payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch(_){}if(typeof payload.value==="bigint")return payload;return payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodBigIntFormat=$constructor("$ZodBigIntFormat",(inst,def)=>{$ZodCheckBigIntFormat.init(inst,def),$ZodBigInt.init(inst,def)}),$ZodSymbol=$constructor("$ZodSymbol",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(typeof input==="symbol")return payload;return payload.issues.push({expected:"symbol",code:"invalid_type",input,inst}),payload}}),$ZodUndefined=$constructor("$ZodUndefined",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_undefined,inst._zod.values=new Set([void 0]),inst._zod.optin="optional",inst._zod.optout="optional",inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(typeof input>"u")return payload;return payload.issues.push({expected:"undefined",code:"invalid_type",input,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(input===null)return payload;return payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload)=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload)=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{return payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodVoid=$constructor("$ZodVoid",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(typeof input>"u")return payload;return payload.issues.push({expected:"void",code:"invalid_type",input,inst}),payload}}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch(_err){}let input=payload.value,isDate=input instanceof Date;if(isDate&&!Number.isNaN(input.getTime()))return payload;return payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleArrayResult(result2,payload,i)));else handleArrayResult(result,payload,i)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodObject=$constructor("$ZodObject",(inst,def)=>{if($ZodType.init(inst,def),!Object.getOwnPropertyDescriptor(def,"shape")?.get){let sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),newSh}})}let _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{let shape=def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(let v of field.values)propValues[key].add(v)}}return propValues});let isObject2=isObject,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value={};let proms=[],shape=value.shape;for(let key of value.keys){let el=shape[key],isOptionalOut=el._zod.optout==="optional",r=el._zod.run({value:input[key],issues:[]},ctx);if(r instanceof Promise)proms.push(r.then((r2)=>handlePropertyResult(r2,payload,key,input,isOptionalOut)));else handlePropertyResult(r,payload,key,input,isOptionalOut)}if(!catchall)return proms.length?Promise.all(proms).then(()=>payload):payload;return handleCatchall(proms,input,payload,ctx,_normalized.value,inst)}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),generateFastpass=(shape)=>{let doc=new Doc(["shape","payload","ctx"]),normalized=_normalized.value,parseStr=(key)=>{let k=esc(key);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};doc.write("const input = payload.value;");let ids=Object.create(null),counter=0;for(let key of normalized.keys)ids[key]=`key_${counter++}`;doc.write("const newResult = {};");for(let key of normalized.keys){let id=ids[key],k=esc(key),isOptionalOut=shape[key]?._zod?.optout==="optional";if(doc.write(`const ${id} = ${parseStr(key)};`),isOptionalOut)doc.write(`
@@ -471,7 +471,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
471
471
  lease_expires_at = excluded.lease_expires_at, payload = excluded.payload,
472
472
  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
473
473
  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
474
- (source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals14.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,_internals14;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals14={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 _internals15.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,_internals15;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals15={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:405"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:465"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:452"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:291"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:678",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:682",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:686",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:746",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:794",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:976",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:984",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1009",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:690",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:700",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:733",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:991",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:2120",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:2140",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:827",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:841",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:755",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:772",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:759",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:782",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:689",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1178",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:798",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:817",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1411",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:864",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:868",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:964",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:972",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:994",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:882",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:903",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:917",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:934",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:951",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1392",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1024",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1038",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1051",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1065",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1090",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:388",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:2207",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1620",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_recovery_superseded",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1428",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:NO_WORKFLOW_IDS,forbiddenWorkflowIds:FORBID_SESSION,allowsLinks:!1}],["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:1127",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:199",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:1149",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:1193",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:1230",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:1256",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:1280",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:1303",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:1332",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:1376",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["execution_attempt_recorded",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/services/execution-attempt.ts:265",consumers:["src/commands/report.ts:60"],retentionOwnerIssue:2676,requiredWorkflowIds:REQUIRE_SESSION,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND,otelMapping:"none"}]],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(),callId:exports_external.string().optional(),invocationId: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 callId=nonEmptyString(record2.callId);if(callId!==void 0)ids.callId=callId;let invocationId=nonEmptyString(record2.invocationId);if(invocationId!==void 0)ids.invocationId=invocationId;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 was `delegation_end` (`src/telemetry.ts` `delegationEnd`): before issue #2789 it coerced token axes with `?? 0`, so they could never appear in `unknown`; it now emits held-null token axes (`?? null`), matching `cost_usd`, and `cost_source: 'unavailable'` still records absence of a cost basis.","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"]),execution_attempt_recorded:Object.freeze(["sessionId","taskId","callId","invocationId","attemptClass","generation","retryIndex","laneId","knowledgeTraceId","outcomeStatus","captured","unknown","cost","duplicateOf"]),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"]),plan_recovery_superseded:Object.freeze(["count","trigger"]),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:()=>_internals16,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=_internals16.createObservation(event,data),content=_internals16.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,_internals16.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,_internals16;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals16.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals16.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals16.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals16.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals16.emit("delegation_end",{sessionId,agentName,taskId,result,...costFields,tokens_input:costFields?.tokens_input??null,tokens_output:costFields?.tokens_output??null,tokens_reasoning:costFields?.tokens_reasoning??null,tokens_cache:costFields?.tokens_cache??null,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals16.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals16.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals16.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals16.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals16.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals16.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals16.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals16.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals16.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals16.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals16.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals16.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals16.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals16.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals16.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals16.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals16.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals16.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals16.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals16.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals16.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals16.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals16.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals16.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals16.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals16.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals16.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},prmHardStopTerminal(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_terminal",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals16.emit("close_archive_result",data)},residueHealth(data){_internals16.emit("residue_health",data)},trainingVaultHealth(data){_internals16.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals16.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals16.emit("skill_usage_health",data)},coreEventsHealth(data){_internals16.emit("core_events_health",data)},shellAuditHealth(data){_internals16.emit("shell_audit_health",data)},trajectoryHealth(data){_internals16.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals16.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals16.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals16.emit("retrieval_routed",{sessionId,...data})},planRecoverySuperseded(data){_internals16.emit("plan_recovery_superseded",data)}},_internals16={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=_internals17.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 walkProjectBoundary(resolved,dependencies){if(hasExplicitProjectBoundary(resolved))return{outcome:"marker-root"};let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)return{outcome:"fail-closed",reason:"depth"};depth++;let parent=path14.dirname(current);if(parent===current)return{outcome:"unclaimed"};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}return{outcome:"fail-closed",reason:"ancestor-swarm",path:parentSwarm}}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")return{outcome:"fail-closed",reason:"ancestor-indicators",path:parent};if(indicatorState==="present")return{outcome:"claimed",ancestor:parent}}current=parent}}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`)}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return;if(walk.outcome==="claimed")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${walk.ancestor}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${walk.ancestor}" already contains a .swarm/ folder. Runtime state must be written to the project root.`);if(walk.reason==="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`);if(walk.reason==="ancestor-swarm")throw warn(`[project-boundary] Cannot inspect ancestor state "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${walk.path}" is inaccessible`);throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${walk.path}" are inaccessible`)}function resolveProjectRootDecision(directory,dependencies=fs8){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{return{kind:"fail-closed",directory,reason:`cannot canonicalize directory "${directory}" — it may not exist or is inaccessible`}}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return{kind:"root",directory:resolved};if(walk.outcome==="claimed")return{kind:"redirect",directory:resolved,owningRoot:walk.ancestor};let reason=walk.reason==="depth"?`ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`:walk.reason==="ancestor-swarm"?`ancestor state "${walk.path}" is inaccessible`:`project indicators in ancestor "${walk.path}" are inaccessible`;return{kind:"fail-closed",directory:resolved,reason}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals17;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()}];_internals17={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(`
474
+ (source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals14.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,_internals14;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals14={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 _internals15.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,_internals15;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals15={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:405"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:465"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:452"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:291"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:678",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:682",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:686",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:746",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:794",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:976",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:984",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1009",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:690",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:700",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:733",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:995",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:2124",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:2144",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:827",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:841",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:755",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:772",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:759",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:782",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:689",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1178",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:798",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:817",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1411",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:864",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:868",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:964",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:972",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:994",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:882",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:903",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:917",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:934",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:951",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1392",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1024",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1038",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1051",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1065",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1090",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:388",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:2207",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1620",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_recovery_superseded",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1428",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:NO_WORKFLOW_IDS,forbiddenWorkflowIds:FORBID_SESSION,allowsLinks:!1}],["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:1127",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:199",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:1149",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:1193",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:1230",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:1256",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:1280",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:1303",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:1332",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:1376",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["execution_attempt_recorded",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/services/execution-attempt.ts:265",consumers:["src/commands/report.ts:60"],retentionOwnerIssue:2676,requiredWorkflowIds:REQUIRE_SESSION,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND,otelMapping:"none"}]],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(),callId:exports_external.string().optional(),invocationId: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 callId=nonEmptyString(record2.callId);if(callId!==void 0)ids.callId=callId;let invocationId=nonEmptyString(record2.invocationId);if(invocationId!==void 0)ids.invocationId=invocationId;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 was `delegation_end` (`src/telemetry.ts` `delegationEnd`): before issue #2789 it coerced token axes with `?? 0`, so they could never appear in `unknown`; it now emits held-null token axes (`?? null`), matching `cost_usd`, and `cost_source: 'unavailable'` still records absence of a cost basis.","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"]),execution_attempt_recorded:Object.freeze(["sessionId","taskId","callId","invocationId","attemptClass","generation","retryIndex","laneId","knowledgeTraceId","outcomeStatus","captured","unknown","cost","duplicateOf"]),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"]),plan_recovery_superseded:Object.freeze(["count","trigger"]),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:()=>_internals16,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=_internals16.createObservation(event,data),content=_internals16.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,_internals16.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,_internals16;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals16.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals16.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals16.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals16.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals16.emit("delegation_end",{sessionId,agentName,taskId,result,...costFields,tokens_input:costFields?.tokens_input??null,tokens_output:costFields?.tokens_output??null,tokens_reasoning:costFields?.tokens_reasoning??null,tokens_cache:costFields?.tokens_cache??null,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals16.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals16.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals16.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals16.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals16.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals16.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals16.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals16.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals16.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals16.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals16.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals16.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals16.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals16.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals16.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals16.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals16.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals16.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals16.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals16.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals16.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals16.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals16.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals16.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals16.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals16.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals16.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},prmHardStopTerminal(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_terminal",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals16.emit("close_archive_result",data)},residueHealth(data){_internals16.emit("residue_health",data)},trainingVaultHealth(data){_internals16.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals16.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals16.emit("skill_usage_health",data)},coreEventsHealth(data){_internals16.emit("core_events_health",data)},shellAuditHealth(data){_internals16.emit("shell_audit_health",data)},trajectoryHealth(data){_internals16.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals16.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals16.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals16.emit("retrieval_routed",{sessionId,...data})},planRecoverySuperseded(data){_internals16.emit("plan_recovery_superseded",data)}},_internals16={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=_internals17.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 walkProjectBoundary(resolved,dependencies){if(hasExplicitProjectBoundary(resolved))return{outcome:"marker-root"};let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)return{outcome:"fail-closed",reason:"depth"};depth++;let parent=path14.dirname(current);if(parent===current)return{outcome:"unclaimed"};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}return{outcome:"fail-closed",reason:"ancestor-swarm",path:parentSwarm}}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")return{outcome:"fail-closed",reason:"ancestor-indicators",path:parent};if(indicatorState==="present")return{outcome:"claimed",ancestor:parent}}current=parent}}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`)}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return;if(walk.outcome==="claimed")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${walk.ancestor}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${walk.ancestor}" already contains a .swarm/ folder. Runtime state must be written to the project root.`);if(walk.reason==="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`);if(walk.reason==="ancestor-swarm")throw warn(`[project-boundary] Cannot inspect ancestor state "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${walk.path}" is inaccessible`);throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${walk.path}" are inaccessible`)}function resolveProjectRootDecision(directory,dependencies=fs8){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{return{kind:"fail-closed",directory,reason:`cannot canonicalize directory "${directory}" — it may not exist or is inaccessible`}}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return{kind:"root",directory:resolved};if(walk.outcome==="claimed")return{kind:"redirect",directory:resolved,owningRoot:walk.ancestor};let reason=walk.reason==="depth"?`ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`:walk.reason==="ancestor-swarm"?`ancestor state "${walk.path}" is inaccessible`:`project indicators in ancestor "${walk.path}" are inaccessible`;return{kind:"fail-closed",directory:resolved,reason}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals17;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()}];_internals17={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(`
475
475
  `).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}
476
476
  `,"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()}
477
477
  `,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(`
@@ -1032,7 +1032,7 @@ ${transcriptTail}`].join(`
1032
1032
  `;if(Buffer.byteLength(line,"utf-8")>TRAJECTORY_LIMITS.maxLineBytes){warn(`[trajectory-store] Skipped oversize trajectory entry (${Buffer.byteLength(line,"utf-8")} B > ${TRAJECTORY_LIMITS.maxLineBytes} B)`);return}let trajectoryPath=getTrajectoryPath(sessionId,directory);await fs49.mkdir(path79.dirname(trajectoryPath),{recursive:!0});let lock=null;try{lock=await acquireTrajectoryLock(getLockPath(trajectoryPath));let tail=await readTailBytes(trajectoryPath,1),needsReframe=tail!==null&&tail.totalBytes>0&&tail.content!==`
1033
1033
  `;if(tail!==null&&tail.totalBytes>sessionMaxBytesFor(maxLines))await compactTrajectoryFile(trajectoryPath,maxLines,directory);await fs49.appendFile(trajectoryPath,needsReframe?`
1034
1034
  ${line}`:line,"utf-8");let sinceCheck=(appendCheckCounters.get(key)??0)+1;if(sinceCheck>=TRAJECTORY_LIMITS.checkIntervalAppends){setAppendCheckCounter(key,0);let window2=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.readMaxBytes);if(window2!==null&&window2.totalBytes>0){let windowParsed=parseWindow(window2.content,window2.offset>0);if(window2.offset>0||windowParsed.entries.length>maxLines)await compactTrajectoryFile(trajectoryPath,maxLines,directory)}}else setAppendCheckCounter(key,sinceCheck)}finally{if(lock)await lock.release()}let cached3=_inMemoryTrajectoryCache.get(key)??[];setTrajectoryCache(key,[...cached3,entry],maxLines)})}catch(err){let busy=err instanceof Error&&err.message.includes("lock busy");if(log(`[trajectory-store] Failed to append trajectory entry: ${err}`),busy){skippedLockAppends+=1;let now=Date.now();if(now-lastAppendSkipEventAtMs>=TRAJECTORY_LIMITS.appendSkipEventCooldownMs)lastAppendSkipEventAtMs=now,emitTrajectoryHealth(directory,{trigger:"append_skip",retained_count:0,dropped_count:0,corrupt_count:0,bytes:0,limit_bytes:0}),skippedLockAppends=0}}}async function readTrajectoryWithCoverage(sessionId,directory,maxLines=1000){try{let trajectoryPath=getTrajectoryPath(sessionId,directory),tail=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.readMaxBytes),checkpoint2=await readCheckpointByPath(getMetaPath2(trajectoryPath));if(tail===null)return{entries:[],coverage:"empty",droppedByCompaction:checkpoint2?.droppedEntries??0,skippedMalformed:0};let parsed=parseWindow(tail.content,tail.offset>0),key=compositeSessionKey(directory,sessionId);setTrajectoryCache(key,parsed.entries,maxLines);let dropped=checkpoint2?.droppedEntries??0,droppedBytes=checkpoint2?.droppedBytes??0,coverage=parsed.entries.length===0&&tail.totalBytes===0?"empty":tail.offset>0||dropped>0||droppedBytes>0?"truncated":"complete";return{entries:parsed.entries,coverage,droppedByCompaction:dropped,skippedMalformed:parsed.skippedMalformed+parsed.skippedOversize}}catch(err){if(err.code==="ENOENT")return{entries:[],coverage:"empty",droppedByCompaction:0,skippedMalformed:0};return log(`[trajectory-store] Failed to read trajectory: ${err}`),{entries:[],coverage:"empty",droppedByCompaction:0,skippedMalformed:0}}}async function readTrajectory(sessionId,directory,maxLines){return(await readTrajectoryWithCoverage(sessionId,directory,maxLines)).entries}async function getCurrentStep(sessionId,directory){try{let trajectoryPath=getTrajectoryPath(sessionId,directory),maxStep=(await readCheckpointByPath(getMetaPath2(trajectoryPath)))?.highestStep??0,tail=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.stepReadMaxBytes);if(tail!==null&&tail.totalBytes>0){let parsed=parseWindow(tail.content,tail.offset>0);if(parsed.maxStep>maxStep)maxStep=parsed.maxStep}return maxStep}catch(err){if(err.code==="ENOENT")return 0;return log(`[trajectory-store] Failed to get current step: ${err}`),0}}function scheduleTrajectoryCleanup(directory){let now=Date.now();if(now-lastCleanupScheduledAtMs<TRAJECTORY_LIMITS.cleanupDebounceMs)return;lastCleanupScheduledAtMs=now,cleanupOldTrajectoryFiles(directory).catch(()=>{})}async function cleanupOldTrajectoryFiles(directory,maxAgeDays=TRAJECTORY_LIMITS.defaultMaxAgeDays){let cutoffMs=maxAgeDays*24*60*60*1000,now=Date.now(),removed=0,retained=0;for(let subdir of["trajectories","replays"]){if(removed>=TRAJECTORY_LIMITS.maxDeletionsPerRun)break;try{let dirPath=validateSwarmPath(directory,subdir),entries=await fs49.readdir(dirPath,{withFileTypes:!0}),candidates=[];for(let entry of entries){if(!entry.isFile())continue;if(entry.name.endsWith(".lock"))continue;let filePath=path79.join(dirPath,entry.name);try{let stat9=await fs49.stat(filePath);candidates.push({name:entry.name,filePath,effectiveMtimeMs:Math.min(stat9.mtimeMs,now)})}catch{}}let deleted=new Set,removeCandidate2=async(candidate)=>{if(await fs49.unlink(candidate.filePath),deleted.add(candidate.name),removed+=1,candidate.name.endsWith(".jsonl")){let metaSibling=`${candidate.filePath}.meta.json`;await fs49.unlink(metaSibling).catch(()=>{})}};for(let candidate of candidates){if(removed>=TRAJECTORY_LIMITS.maxDeletionsPerRun)break;if(now-candidate.effectiveMtimeMs>cutoffMs)await removeCandidate2(candidate).catch(()=>{})}let remainingJsonl=candidates.filter((c)=>!deleted.has(c.name)&&c.name.endsWith(".jsonl")).sort((a,b)=>b.effectiveMtimeMs-a.effectiveMtimeMs);retained+=remainingJsonl.length;while(remainingJsonl.length>TRAJECTORY_LIMITS.maxFilesPerDir&&removed<TRAJECTORY_LIMITS.maxDeletionsPerRun){let oldest=remainingJsonl.pop();if(oldest===void 0)break;await removeCandidate2(oldest).catch(()=>{}),retained-=1}}catch{}}if(removed>0)emitTrajectoryHealth(directory,{trigger:"cleanup",retained_count:retained,dropped_count:removed,corrupt_count:0,bytes:0,limit_bytes:TRAJECTORY_LIMITS.maxFilesPerDir}),skippedLockAppends=0}var MAX_TRACKED_TRAJECTORY_SESSIONS=500,TRAJECTORY_LIMITS,_internals68,skippedLockAppends=0,lastAppendSkipEventAtMs=0,_inMemoryTrajectoryCache,appendChains2,appendCheckCounters,lastCleanupScheduledAtMs=0;var init_trajectory_store=__esm(()=>{init_learning_health();init_utils2();init_telemetry();init_atomic_write();init_canonical_root();init_logger();TRAJECTORY_LIMITS={checkIntervalAppends:25,readMaxBytes:1048576,stepReadMaxBytes:65536,compactMaxBytes:1048576,maxLineBytes:65536,estimatedLineBytes:512,minSessionMaxBytes:65536,lockRetries:20,lockRetryDelayMs:5,lockStaleMs:300000,maxFilesPerDir:200,maxDeletionsPerRun:256,defaultMaxAgeDays:7,cleanupDebounceMs:600000,appendSkipEventCooldownMs:60000};_internals68={telemetry};_inMemoryTrajectoryCache=new Map;appendChains2=new Map,appendCheckCounters=new Map});function resetPrmSessionState(session,sessionId){if(session.prmEscalationTracker=void 0,session.prmInitialized=!1,session.prmPatternCounts=new Map,session.prmEscalationLevel=0,session.prmLastPatternDetected=null,session.prmHardStopPending=!1,session.prmHardStopInjectPending=!1,session.prmTrajectoryStep=0,session.prmInjectedAdvisoryKeys=new Set,session.prmStruckEpisodes=new Map,session.prmLadderCounts=new Map,session.prmEpisodes=new Map,session.prmEpisodeGeneration=0,session.replayArtifactPath=null,sessionId)_internals69.clearTrajectoryCache(sessionId)}function resolvePrmPatternPersistenceOptions(learning){return{enabled:learning.prm_persistence.enabled,min_support:learning.prm_persistence.min_support,cooldown_ms:learning.prm_persistence.cooldown_ms,admission_enabled:learning.realtime_admission.enabled,max_queue_size:learning.realtime_admission.max_queue_size}}function createPrmHook(config3,directory,patternPersistence){async function toolAfter(context){if(!config3.enabled)return;let{sessionID}=context,session=_internals69.getAgentSession(sessionID);if(!session||!session.delegationActive)return;try{let sessionPrmState=session;if(!sessionPrmState.prmInitialized)sessionPrmState.prmInitialized=!0,_internals69.scheduleTrajectoryCleanup(directory);let cachedTrajectory=_internals69.getInMemoryTrajectory(sessionID,directory),trajectory=cachedTrajectory;if(cachedTrajectory.length===0){let coldRead=await _internals69.readTrajectoryWithCoverage(sessionID,directory,config3.max_trajectory_lines);if(trajectory=coldRead.entries,coldRead.coverage==="truncated")log(`[prm] session ${sessionID} trajectory window is partial: ${coldRead.droppedByCompaction} older entries were dropped by compaction (pattern detection runs on the newest retained window)`)}let detectionResult=_internals69.detectPatterns(trajectory,config3,session.prmTrajectoryStep);if(detectionResult.matches.length===0)return;session.prmStruckEpisodes??=new Map;let struckEpisodes=session.prmStruckEpisodes,strikeable=[],claimedThisTick=new Set;for(let match of[...detectionResult.matches].sort((a,b)=>a.stepRange[0]-b.stepRange[0])){if(claimedThisTick.has(match.pattern))continue;let episodeKey=`${match.pattern}|${match.stepRange[0]}`,struckAtCount=struckEpisodes.get(episodeKey);if(struckAtCount!==void 0){let threshold=resolvePatternThreshold(config3,match.pattern);if(match.occurrenceCount<struckAtCount+threshold)continue}claimedThisTick.add(match.pattern),strikeable.push(match)}if(strikeable.length===0){if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step;return}for(let match of strikeable){let episodeKey=`${match.pattern}|${match.stepRange[0]}`;struckEpisodes.delete(episodeKey),struckEpisodes.set(episodeKey,match.occurrenceCount)}while(struckEpisodes.size>MAX_TRACKED_EPISODES){let oldest=struckEpisodes.keys().next().value;if(oldest===void 0)break;struckEpisodes.delete(oldest)}if(patternPersistence?.enabled)for(let match of strikeable){let observation=_internals69.recordPatternObservation(sessionID,match,{minSupport:patternPersistence.min_support,cooldownMs:patternPersistence.cooldown_ms});if(observation.persistable&&observation.candidate){try{await _internals69.appendInsightCandidates(directory,[observation.candidate])}catch(err){warn(`[prm] insight-candidate append failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}if(patternPersistence.admission_enabled)_internals69.enqueueCandidate(sessionID,observation.candidate,{maxQueueSize:patternPersistence.max_queue_size})}}let escalationTracker=sessionPrmState.prmEscalationTracker;if(!sessionPrmState.replayArtifactPath)sessionPrmState.replayArtifactPath=await _internals69.startReplayRecording(sessionID,directory);let artifactPath=sessionPrmState.replayArtifactPath;if(!escalationTracker){let initialState=session.prmLastPatternDetected?{patternCounts:new Map(session.prmLadderCounts??[]),escalationLevel:session.prmEscalationLevel,lastPatternDetected:session.prmLastPatternDetected,hardStopPending:session.prmHardStopPending,episodes:new Map(session.prmEpisodes??[]),generation:session.prmEpisodeGeneration??0}:void 0;escalationTracker=new EscalationTracker(sessionID,initialState),sessionPrmState.prmEscalationTracker=escalationTracker}let previousEscalationLevel=session.prmEscalationLevel,tickHardStop=!1;for(let match of strikeable){let correction=_internals69.generateCourseCorrection(match,trajectory),formattedCorrection=_internals69.formatCourseCorrectionForInjection(correction),escalationLevel=0,hardStopPending=!1,hardStopTerminal=!1;if(config3.escalation_enabled!==!1){let escalationResult=escalationTracker.recordDetection(match);escalationLevel=escalationResult.level,hardStopPending=escalationResult.hardStop,hardStopTerminal=escalationResult.terminal}let prmDedupeKey=`prm:${resolveLadderKey(match)}:${escalationLevel}${hardStopTerminal?":terminal":""}:g${escalationTracker.getGeneration()}`;if(!session.prmInjectedAdvisoryKeys?.has(prmDedupeKey))pushAdvisory(session,`[${prmDedupeKey}] ${formattedCorrection}`,{dedupeKey:prmDedupeKey}),session.prmInjectedAdvisoryKeys??=new Set,session.prmInjectedAdvisoryKeys.add(prmDedupeKey);if(session.prmPatternCounts.set(match.pattern,(session.prmPatternCounts.get(match.pattern)??0)+1),session.prmLadderCounts=escalationTracker.getLadderCounts(),session.prmEpisodes=escalationTracker.getEpisodes(),session.prmEpisodeGeneration=escalationTracker.getGeneration(),session.prmEscalationLevel=escalationLevel,session.prmLastPatternDetected=match,tickHardStop=tickHardStop||hardStopPending,session.prmHardStopPending=tickHardStop,tickHardStop)session.prmHardStopInjectPending=!0;if(_internals69.telemetry.prmPatternDetected(sessionID,match.pattern,match.severity,match.category,match.stepRange),_internals69.telemetry.prmCourseCorrectionInjected(sessionID,match.pattern,escalationLevel),artifactPath)await _internals69.recordReplayEntry(artifactPath,sessionID,{type:"pattern_detected",data:{pattern:match.pattern,severity:match.severity,category:match.category,stepRange:match.stepRange,description:match.description,affectedAgents:match.affectedAgents,affectedTargets:match.affectedTargets,occurrenceCount:match.occurrenceCount}});if(artifactPath)await _internals69.recordReplayEntry(artifactPath,sessionID,{type:"course_correction",data:{pattern:correction.pattern,alert:correction.alert,category:correction.category,guidance:correction.guidance,action:correction.action,stepRange:correction.stepRange,escalationLevel}})}if(artifactPath&&session.prmEscalationLevel>previousEscalationLevel)await _internals69.recordReplayEntry(artifactPath,sessionID,{type:"escalation",data:{previousLevel:previousEscalationLevel,newLevel:session.prmEscalationLevel,hardStopPending:session.prmHardStopPending}});if(artifactPath&&session.prmHardStopPending&&previousEscalationLevel<3)await _internals69.recordReplayEntry(artifactPath,sessionID,{type:"hard_stop",data:{escalationLevel:session.prmEscalationLevel,triggeredAt:new Date().toISOString()}});if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step}catch(err){log(`[prm] toolAfter error for session ${sessionID}: ${err}`)}}return{toolAfter}}var _internals69,MAX_TRACKED_EPISODES=256;var init_prm=__esm(()=>{init_course_correction();init_escalation();init_pattern_detector();init_micro_reflector();init_candidate_queue();init_prm_pattern_support();init_state2();init_telemetry();init_logger();init_course_correction();init_escalation();init_pattern_detector();init_replay();init_trajectory_store();_internals69={getAgentSession,readTrajectoryWithCoverage,getInMemoryTrajectory,detectPatterns,generateCourseCorrection,formatCourseCorrectionForInjection,scheduleTrajectoryCleanup,clearTrajectoryCache,recordReplayEntry,startReplayRecording,telemetry,recordPatternObservation,enqueueCandidate,appendInsightCandidates}});import{createHash as createHash34,createHmac,randomBytes as randomBytes6,timingSafeEqual}from"node:crypto";import*as fs50 from"node:fs";import*as fsp3 from"node:fs/promises";import*as path80 from"node:path";function normalizedIdentity(value,label){let normalized=value.trim();if(!normalized||normalized.length>256)throw Error(`ROUTE_RECEIPT_INVALID_IDENTITY: ${label}`);return normalized}function uniqueIdentities(values,label){let result=values.map((value)=>normalizedIdentity(value,label));if(new Set(result).size!==result.length)throw Error(`ROUTE_RECEIPT_DUPLICATE: ${label}`);return[...result]}function slotsFor(role,identities,provided,taskId){let slots=provided?uniqueIdentities(provided,`${role} slots`):identities.map((_,index)=>`${taskId}:${role}:${index+1}`);if(slots.length!==identities.length)throw Error(`ROUTE_RECEIPT_SLOT_COUNT_MISMATCH: ${role}`);return slots}function buildReviewRouteReceipt(input){let sessionId=normalizedIdentity(input.sessionId,"sessionId"),taskId=normalizedIdentity(input.taskId,"taskId"),reviewers=uniqueIdentities(input.requiredReviewers,"reviewers"),testEngineers=uniqueIdentities(input.requiredTestEngineers,"test_engineers");return ReviewRouteReceiptSchema.parse({kind:"review_route_receipt",version:REVIEW_ROUTE_RECEIPT_VERSION,sessionId,taskId,complexity:input.complexity,semanticRisk:input.semanticRisk,required:{reviewers:reviewers.length,testEngineers:testEngineers.length},identities:{reviewers,testEngineers},slots:{reviewers:slotsFor("reviewer",reviewers,input.reviewerSlots,taskId),testEngineers:slotsFor("test_engineer",testEngineers,input.testEngineerSlots,taskId)},createdAt:input.createdAt??new Date().toISOString()})}function buildReviewRouteRouterError(input){return ReviewRouteRouterErrorReceiptSchema.parse({kind:"review_route_router_error",version:REVIEW_ROUTE_RECEIPT_VERSION,code:input.code,failOpen:!0,...input.sessionId?{sessionId:input.sessionId}:{},...input.taskId?{taskId:input.taskId}:{},...input.detail?{detail:input.detail.slice(0,512)}:{},createdAt:input.createdAt??new Date().toISOString()})}function buildReviewRoutePending(input){return ReviewRoutePendingReceiptSchema.parse({kind:"review_route_pending",version:REVIEW_ROUTE_RECEIPT_VERSION,sessionId:input.sessionId,taskId:input.taskId,createdAt:input.createdAt??new Date().toISOString()})}function routeReceiptRelativePath(sessionId,taskId){let normalizedSessionId=normalizedIdentity(sessionId,"sessionId"),normalizedTaskId=normalizedIdentity(taskId,"taskId"),encodeIdentity=(normalized)=>{let encoded=Buffer.from(normalized,"utf8").toString("base64url").replace(/-/g,"~");return encoded.length<=180?encoded:`sha256_${createHash34("sha256").update(normalized,"utf8").digest("hex")}`},safeSession=encodeIdentity(normalizedSessionId),safeTask=encodeIdentity(normalizedTaskId),basename14=`${safeSession}--${safeTask}.json`,boundedBasename=Buffer.byteLength(basename14,"utf8")<=255?basename14:`sha256_${createHash34("sha256").update(JSON.stringify([normalizedSessionId,normalizedTaskId]),"utf8").digest("hex")}.json`;return path80.join("pr-review","route-receipts",boundedBasename)}function routeReceiptPath(directory,sessionId,taskId){return validateSwarmPath(directory,routeReceiptRelativePath(sessionId,taskId))}async function ensureSafeParent(directory,filePath){assertProjectRoot(directory,void 0,"review route receipt");let swarmRoot=path80.resolve(directory,".swarm"),parent=path80.dirname(filePath),relative18=path80.relative(swarmRoot,parent);if(relative18===".."||relative18.startsWith(`..${path80.sep}`)||path80.isAbsolute(relative18))throw Error("ROUTE_RECEIPT_PATH_ESCAPE: route receipt is outside .swarm");await fsp3.mkdir(parent,{recursive:!0});for(let candidate of[swarmRoot,path80.join(swarmRoot,"pr-review"),parent]){let stat9=await fsp3.lstat(candidate);if(!stat9.isDirectory()||stat9.isSymbolicLink())throw Error("ROUTE_RECEIPT_PATH_UNSAFE: receipt parent is not a real directory")}}function routeReceiptSecretPath(projectRoot){let hiveDir=path80.resolve(resolveHiveDataDir());if(projectRoot){let root=path80.resolve(projectRoot),relative18=path80.relative(root,hiveDir);if(relative18===""||!path80.isAbsolute(relative18)&&!relative18.startsWith(`..${path80.sep}`))throw Error("ROUTE_RECEIPT_SECRET_UNSAFE_PATH: app-data key path is inside the project root")}return path80.join(hiveDir,ROUTE_RECEIPT_SECRET_FILE)}function parseRouteReceiptSecret(raw){let value=raw.trim();return/^[0-9a-f]{64}$/.test(value)?Buffer.from(value,"hex"):null}async function readRouteReceiptSecret(projectRoot){let secretPath=routeReceiptSecretPath(projectRoot);try{let stat9=await fsp3.lstat(secretPath);if(stat9.isSymbolicLink()||!stat9.isFile())throw Error("ROUTE_RECEIPT_SECRET_INVALID");let secret=parseRouteReceiptSecret(await fsp3.readFile(secretPath,"utf8"));if(!secret)throw Error("ROUTE_RECEIPT_SECRET_INVALID");return secret}catch(error93){if(error93.code!=="ENOENT")throw error93}await fsp3.mkdir(path80.dirname(secretPath),{recursive:!0});let generated=randomBytes6(32);try{await fsp3.writeFile(secretPath,generated.toString("hex"),{encoding:"utf8",flag:"wx",mode:384})}catch(error93){if(error93.code!=="EEXIST")throw error93;return readRouteReceiptSecret(projectRoot)}try{await fsp3.chmod(secretPath,384)}catch{}return generated}function readRouteReceiptSecretSync(projectRoot){try{let secretPath=routeReceiptSecretPath(projectRoot),stat9=fs50.lstatSync(secretPath);if(stat9.isSymbolicLink()||!stat9.isFile())return null;return parseRouteReceiptSecret(fs50.readFileSync(secretPath,"utf8"))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_SECRET_UNSAFE_PATH:"))throw error93;return null}}function canonicalRouteReceiptJson(value){if(value===null||typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((entry)=>canonicalRouteReceiptJson(entry)).join(",")}]`;return`{${Object.entries(value).filter(([,entry])=>entry!==void 0).sort(([left],[right])=>left.localeCompare(right)).map(([key,entry])=>`${JSON.stringify(key)}:${canonicalRouteReceiptJson(entry)}`).join(",")}}`}function routeReceiptMacPayload(receipt){let{mac:_mac2,...payload}=receipt;return`${ROUTE_RECEIPT_MAC_CONTEXT}${canonicalRouteReceiptJson(payload)}`}function computeRouteReceiptMac(receipt,secret){return createHmac("sha256",secret).update(routeReceiptMacPayload(receipt),"utf8").digest("hex")}function hasValidRouteReceiptMac(receipt,secret){if(!secret||!receipt.mac||!RouteReceiptMacSchema.safeParse(receipt.mac).success)return!1;let expected=Buffer.from(computeRouteReceiptMac(receipt,secret),"hex"),supplied=Buffer.from(receipt.mac,"hex");return supplied.length===expected.length&&timingSafeEqual(supplied,expected)}function authenticatePersistedRouteReceipt(receipt,secret){if(hasValidRouteReceiptMac(receipt,secret))return receipt;throw Error("ROUTE_RECEIPT_AUTH_INVALID: receipt MAC is missing or invalid")}async function persistReviewRouteReceipt(input){let parsed=input.receipt.kind==="review_route_receipt"?ReviewRouteReceiptSchema.parse(input.receipt):input.receipt.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.parse(input.receipt):ReviewRoutePendingReceiptSchema.parse(input.receipt),sessionId=parsed.kind==="review_route_receipt"?parsed.sessionId:parsed.sessionId??"router",taskId=parsed.kind==="review_route_receipt"?parsed.taskId:parsed.taskId??"unknown",filePath=routeReceiptPath(input.projectRoot,sessionId,taskId);await ensureSafeParent(input.projectRoot,filePath);let authenticated={...parsed,mac:computeRouteReceiptMac(parsed,await readRouteReceiptSecret(input.projectRoot))},encoded=JSON.stringify(authenticated,null,2);if(Buffer.byteLength(encoded,"utf8")>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_OVERSIZED: receipt exceeds size bound");return await atomicWriteFile(filePath,`${encoded}
1035
- `),{persisted:!0,path:filePath}}function readReviewRouteReceiptSync(input){let filePath=routeReceiptPath(input.projectRoot,input.sessionId,input.taskId),stat9;try{stat9=fs50.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}if(stat9.isSymbolicLink()||!stat9.isFile()||stat9.size>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_UNREADABLE: receipt is not a bounded regular file");let value;try{value=JSON.parse(fs50.readFileSync(filePath,"utf8"))}catch(error93){if(error93 instanceof SyntaxError)throw Error("ROUTE_RECEIPT_INVALID_JSON: receipt is not valid JSON");throw error93}let parsed=typeof value==="object"&&value!==null&&value.kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):value.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);if(!parsed.success)throw Error("ROUTE_RECEIPT_INVALID: receipt failed schema validation");let authenticated=authenticatePersistedRouteReceipt(parsed.data,readRouteReceiptSecretSync(input.projectRoot));if((authenticated.kind==="review_route_receipt"||authenticated.kind==="review_route_pending")&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");if(authenticated.kind==="review_route_router_error"&&authenticated.sessionId!==void 0&&authenticated.taskId!==void 0&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");return authenticated}function parseRouteReceipt(value){if(!value||typeof value!=="object")return null;let kind=value.kind,parsed=kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);return parsed.success?parsed.data:null}function fail(reason){return{canAdvance:!1,mode:"enforced",reason}}function enforceReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route=parseRouteReceipt(input.routeReceipt);if(!route)return fail("ROUTE_RECEIPT_MISSING");if(route.kind==="review_route_router_error"){if(input.sessionId&&(!route.sessionId||!route.taskId||route.sessionId!==input.sessionId||route.taskId!==input.taskId))return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");return{canAdvance:!0,mode:"fail_open",routerFailure:route.code}}if(route.kind==="review_route_pending")return fail("ROUTE_RECEIPT_PENDING");if(input.sessionId&&route.sessionId!==input.sessionId||input.taskId&&route.taskId!==input.taskId)return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");if(route.required.reviewers!==route.identities.reviewers.length||route.required.testEngineers!==route.identities.testEngineers.length)return fail("ROUTE_RECEIPT_COUNT_MISMATCH");let expected=new Map;for(let identity of route.identities.reviewers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"reviewer")}for(let identity of route.identities.testEngineers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"test_engineer")}if(input.requireEvidenceBindings&&input.requireCompleteEvidence===!1&&expected.size>0&&!input.expectedDispatch)return fail("ROUTE_RECEIPT_DISPATCH_REQUIRED");let seen=new Set,seenSlots=new Set;for(let evidence of input.receipts){if(input.requireEvidenceBindings&&(!evidence.sessionId||!evidence.taskId||!evidence.slotId||!evidence.callId||!evidence.childSessionId||typeof evidence.generation!=="number"))return fail("ROUTE_RECEIPT_BINDING_MISSING");let identity=evidence.identity.trim();if(!identity||identity.length>256)return fail("ROUTE_RECEIPT_INVALID_IDENTITY");let expectedRole=expected.get(identity);if(!expectedRole)return fail("ROUTE_RECEIPT_IDENTITY_UNLISTED");if(expectedRole!==evidence.role)return fail("ROUTE_RECEIPT_ROLE_MISMATCH");if(seen.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");if(evidence.sessionId&&evidence.sessionId!==route.sessionId)return fail("ROUTE_RECEIPT_SESSION_MISMATCH");if(evidence.taskId&&evidence.taskId!==route.taskId)return fail("ROUTE_RECEIPT_TASK_MISMATCH");if(evidence.slotId){if(seenSlots.has(evidence.slotId))return fail("ROUTE_RECEIPT_DUPLICATE");let slots=evidence.role==="reviewer"?route.slots?.reviewers:route.slots?.testEngineers;if(slots&&!slots.includes(evidence.slotId))return fail("ROUTE_RECEIPT_SLOT_UNLISTED");if(slots){let expectedIndex=evidence.role==="reviewer"?route.identities.reviewers.indexOf(identity):route.identities.testEngineers.indexOf(identity);if(expectedIndex<0||slots[expectedIndex]!==evidence.slotId)return fail("ROUTE_RECEIPT_SLOT_MISMATCH")}seenSlots.add(evidence.slotId)}seen.add(identity)}if(input.expectedDispatch){let expected2=input.expectedDispatch,matching=input.receipts.find((evidence)=>evidence.role===expected2.role&&evidence.identity===expected2.identity);if(!matching||matching.callId!==expected2.callId||matching.childSessionId!==expected2.childSessionId||matching.generation!==expected2.generation)return fail("ROUTE_RECEIPT_DISPATCH_MISMATCH")}if(input.requireCompleteEvidence!==!1&&seen.size!==expected.size)return fail("ROUTE_RECEIPT_INCOMPLETE");return{canAdvance:!0,mode:"enforced"}}function enforcePersistedReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route;try{route=readReviewRouteReceiptSync({projectRoot:input.projectRoot,sessionId:input.sessionId,taskId:input.taskId})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_AUTH_INVALID:"))return fail("ROUTE_RECEIPT_AUTH_INVALID");throw error93}if(!route&&input.legacyUnrouted)return{canAdvance:!0,mode:"legacy_unrouted",reason:"legacy_unrouted: route receipt predates version-1 enforcement"};return enforceReviewRouteReceipt({enforcementEnabled:!0,routeReceipt:route,receipts:input.receipts,sessionId:input.sessionId,taskId:input.taskId,requireEvidenceBindings:input.requireEvidenceBindings,expectedDispatch:input.expectedDispatch,requireCompleteEvidence:input.requireCompleteEvidence})}var REVIEW_ROUTE_RECEIPT_VERSION=1,IdentitySchema,RouteReceiptMacSchema,ReviewRouteReceiptSchema,ReviewRouteRouterErrorReceiptSchema,ReviewRoutePendingReceiptSchema,MAX_ROUTE_RECEIPT_BYTES=65536,ROUTE_RECEIPT_SECRET_FILE="review-route-receipts.key",ROUTE_RECEIPT_MAC_CONTEXT="opencode-swarm/review-route-receipt/v1\x00";var init_routing_enforcement=__esm(()=>{init_zod();init_task_file();init_utils2();init_hive_paths();init_project_boundary();IdentitySchema=exports_external.string().trim().min(1).max(256),RouteReceiptMacSchema=exports_external.string().regex(/^[0-9a-f]{64}$/,"route receipt MAC must be a SHA-256 HMAC"),ReviewRouteReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_receipt"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,complexity:exports_external.string().trim().min(1).max(80),semanticRisk:exports_external.string().trim().min(1).max(120),required:exports_external.object({reviewers:exports_external.number().int().nonnegative().max(16),testEngineers:exports_external.number().int().nonnegative().max(16)}),identities:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}),slots:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRouteRouterErrorReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_router_error"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),code:exports_external.enum(["NO_CHANGED_FILES","ROUTER_UNAVAILABLE","ROUTER_FAILED"]),failOpen:exports_external.literal(!0),sessionId:IdentitySchema.optional(),taskId:IdentitySchema.optional(),detail:exports_external.string().trim().max(512).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRoutePendingReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_pending"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict()});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),wal=await readWal(walPath,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal(walPath,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal(walPath,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function writeWal(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}async function ensureAuditEvent(directory,wal){if(hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))return;try{appendCoreEventSync(directory,{type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_REPAIR_AUDIT_LOCKED");throw error93}if(!hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}function workflowMatchesCommittedRepair(evidence,wal){let snapshot=getTaskWorkflowSnapshot(evidence);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence),existingWal=await readWal(walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence,existingWal))return await ensureAuditEvent(options.directory,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal(walPath,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal(walPath,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_core_events();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence,wal){let workflow=getTaskWorkflowSnapshot(evidence);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,readOnlyNoMutation:wal.readOnlyNoMutation,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath){try{return await _internals70.applyTerminalEvidence(transaction,wal)}catch(error93){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal2(walPath,{...wal,state:"ABORTED"}),null;if(wal.readOnlyNoMutation===!0&&!evidenceAlreadyTerminal){let replayed;try{replayed=await peekPlanFromLedger(directory)}catch(error93){throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: could not inspect the authoritative plan ledger: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}if(replayed.truncated||replayed.badSuffix!==null)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");if(!replayed.plan)throw Error("TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: authoritative plan ledger has no replayable plan");let authoritativeTask=replayed.plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!authoritativeTask)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);if(wal.version===2){let identity=await readPlanEpochIdentity(directory,replayed.plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}plan=replayed.plan,task=authoritativeTask;let currentFiles=authoritativeTask.files_touched;if(!(Array.isArray(currentFiles)&&currentFiles.length===0)){if(authoritativeTask.status!==wal.oldPlanStatus&&authoritativeTask.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${authoritativeTask.status}`);if(authoritativeTask.status===wal.newPlanStatus&&authoritativeTask.status!==wal.oldPlanStatus){let oldStatus=TaskStatusSchema.safeParse(wal.oldPlanStatus);if(!oldStatus.success)throw Error(`TASK_TERMINAL_OLD_STATUS_INVALID: ${wal.oldPlanStatus}`);let rolledBackPlan=await updateTaskStatus(directory,taskId,oldStatus.data,{planLockAlreadyHeld:!0,terminalReconciliation:!0}),rolledBackTask=rolledBackPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(rolledBackTask?.status!==oldStatus.data)throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_ROLLBACK_FAILED: expected ${oldStatus.data}, found ${rolledBackTask?.status??"missing task"}`);plan=rolledBackPlan}throw await writeWal2(walPath,{...wal,state:"ABORTED"}),Error(`TASK_TERMINAL_READ_ONLY_SCOPE_CHANGED: task ${taskId} no longer has a known empty declared scope; terminal evidence was not applied`)}}if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence:await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence);await options.validateEvidence?.(evidence);let terminal=options.resolveTerminal?.(evidence)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&existingWal.readOnlyNoMutation===!0===(terminal.readOnlyNoMutation===!0)&&evidenceMatchesTerminal(evidence,existingWal))return{plan:options.currentPlan,evidence,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath}); found ${evidence?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,...terminal.readOnlyNoMutation===!0?{readOnlyNoMutation:!0}:{},recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal2(walPath,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal2=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals70;var init_task_terminal=__esm(()=>{init_plan_schema();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals70={applyTerminalEvidence}});import*as fs51 from"node:fs";function storePath2(directory){return validateSwarmPath(directory,DEAD_LANE_RECLAIM_PATH)}function isDeadLaneReclaimEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return typeof candidate.lanePath==="string"&&candidate.lanePath.length>0&&typeof candidate.branchName==="string"&&typeof candidate.parentSessionId==="string"&&typeof candidate.taskId==="string"&&typeof candidate.reason==="string"&&typeof candidate.recordedAt==="number"}function readStore2(directory){try{let raw=fs51.readFileSync(storePath2(directory),"utf-8");if(raw.length>MAX_DEAD_LANE_RECLAIM_BYTES)return{schemaVersion:1,entries:[]};let parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{schemaVersion:1,entries:[]};return{schemaVersion:1,entries:parsed.entries.filter(isDeadLaneReclaimEntry)}}catch{return{schemaVersion:1,entries:[]}}}function writeStore2(directory,store){let entries=store.entries.slice(-MAX_DEAD_LANE_RECLAIMS);for(;;){let serialized2=JSON.stringify({schemaVersion:1,entries},null,2);if(serialized2.length<=MAX_DEAD_LANE_RECLAIM_BYTES||entries.length===0){if(entries.length<store.entries.length)log(`[dead-lane-reclaim] store bound dropped ${store.entries.length-entries.length} oldest entries (caps: ${MAX_DEAD_LANE_RECLAIMS} entries / ${MAX_DEAD_LANE_RECLAIM_BYTES} bytes)`);_internals71.atomicWriteSwarmFileSync(storePath2(directory),serialized2);return}entries=entries.slice(1)}}function recordDeadLaneReclaim(directory,entry){try{let filtered=readStore2(directory).entries.filter((existing)=>existing.lanePath!==entry.lanePath);filtered.push({...entry,recordedAt:Date.now()}),writeStore2(directory,{schemaVersion:1,entries:filtered})}catch(error93){log(`[dead-lane-reclaim] could not record stranded lane ${entry.lanePath}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function isLaneOwnedByActiveSession(lanePath,activeSessionIds,parentSessionId){if(activeSessionIds.has(parentSessionId??""))return!0;if(parentSessionId&&!lanePathIncludesSessionSegment(lanePath,parentSessionId))return!0;return!1}function lanePathIncludesSessionSegment(lanePath,sessionId){return lanePath.replace(/\\/g,"/").split("/").includes(sessionId)}async function isLaneDirty(lanePath){let proc;try{let options={cwd:lanePath,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:LANE_DIRTY_CHECK_TIMEOUT_MS,killProcessTree:!0};proc=_internals71.bunSpawn([_internals71.resolveGitExecutable(),"-C",lanePath,"status","--porcelain"],options);let stdout="";if(proc.stdout){let reader=proc.stdout.getReader();for(;;){let{done,value}=await reader.read();if(done||!value)break;if(stdout+=Buffer.from(value).toString("utf-8"),stdout.length>LANE_DIRTY_STDOUT_CAP_BYTES)break}}if(await proc.exited!==0)return!0;return stdout.trim().length>0}catch{return!0}finally{try{proc?.kill?.()}catch{}}}async function reclaimDeadLanes(directory,context={}){let result={reclaimed:[],retained:[]},store;try{store=readStore2(directory)}catch{return result}if(store.entries.length===0)return result;let activeSessionIds=new Set(context.activeSessionIds??[]),protectedPaths=new Set(context.protectedWorktreePaths??[]),retained=[];for(let entry of store.entries){let protectedLane=protectedPaths.has(entry.lanePath)||protectedPaths.has(_internals71.canonicalRootKeyFresh(entry.lanePath));if(_internals71.isLaneOwnedByActiveSession(entry.lanePath,activeSessionIds,entry.parentSessionId)||protectedLane){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"owned-by-active-session-or-protected"});continue}if(!await _internals71.pathExists(entry.lanePath))continue;if(await _internals71.isLaneDirty(entry.lanePath)){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"dirty-lane-preserved"});continue}_internals71.closeProjectDb(entry.lanePath);let removalError;try{let removal=await _internals71.removeWorktree(entry.lanePath,directory);if("error"in removal)removalError=removal.error}catch(error93){removalError=error93 instanceof Error?error93.message:String(error93)}if(removalError!==void 0){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:removalError});continue}result.reclaimed.push(entry.lanePath)}try{if(retained.length===0)fs51.rmSync(storePath2(directory),{force:!0});else writeStore2(directory,{schemaVersion:1,entries:retained})}catch(error93){log(`[dead-lane-reclaim] could not persist reclaim state: ${error93 instanceof Error?error93.message:String(error93)}`)}return result}async function pathExists2(target){try{return await fs51.promises.stat(target),!0}catch{return!1}}var DEAD_LANE_RECLAIM_PATH="dead-lane-reclaims.json",MAX_DEAD_LANE_RECLAIMS=512,MAX_DEAD_LANE_RECLAIM_BYTES=262144,LANE_DIRTY_CHECK_TIMEOUT_MS=5000,LANE_DIRTY_STDOUT_CAP_BYTES=4096,_internals71;var init_dead_lane_reclaim=__esm(()=>{init_project_db();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();init_utils2();_internals71={removeWorktree,closeProjectDb,isLaneOwnedByActiveSession,isLaneDirty,pathExists:pathExists2,bunSpawn,resolveGitExecutable,atomicWriteSwarmFileSync,canonicalRootKeyFresh}});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win329){return win329===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state2={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state2.prefix="./";return output};exports.wrapOutput=(input,state2={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state2.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path81,{windows}={})=>{let segs=path81.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state2={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state2.maxDepth=0,!isPathSeparator(code))tokens.push(token);state2.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state2.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state2.maxDepth+=tokens[tokens.length-1].depth}state2.slashes=slashes,state2.parts=parts}return state2};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants5=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants5,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants5.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse9=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants5.globChars(opts.windows),EXTGLOB_CHARS=constants5.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state2={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state2),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state2.index===len-1,peek=state2.peek=(n=1)=>input[state2.index+n],advance=state2.advance=()=>input[++state2.index]||"",remaining=()=>input.slice(state2.index+1),consume=(value2="",num=0)=>{state2.consumed+=value2,state2.index+=num},append=(token)=>{state2.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state2.start++,count++;if(count%2===0)return!1;return state2.negated=!0,state2.start++,!0},increment=(type)=>{state2[type]++,stack.push(type)},decrement=(type)=>{state2[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state2.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state2.output=state2.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state2.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state2.parens,token.output=state2.output,token.startIndex=state2.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state2.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal3=input.slice(token.startIndex,state2.index+1),body=input.slice(token.startIndex+2,state2.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open5=tokens[token.tokensIndex];open5.type="text",open5.value=literal3,open5.output=safeOutput||utils.escapeRegex(literal3);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state2.output=token.output+open5.output,state2.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse9(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state2.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc3,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc3)return esc3+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc3)return esc3+first+(rest?star:"");return star}return esc3?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state2.output=input,state2;return state2.output=utils.wrapOutput(output,state2,options),state2}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state2.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state2.brackets===0){push({type:"text",value});continue}}if(state2.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix11=POSIX_REGEX_SOURCE[rest2];if(posix11){if(prev.value=pre+posix11,state2.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state2.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state2.quotes=state2.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state2.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state2.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state2.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state2.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state2.output=state2.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state2.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state2.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open5={type:"brace",value,output:"(",outputIndex:state2.output.length,tokensIndex:state2.tokens.length};braces.push(open5),push(open5);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state2.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state2.output.slice(0,brace.outputIndex),toks=state2.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state2.output=out;for(let t of toks)state2.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state2.index===state2.start+1){state2.start=state2.index+1,state2.consumed="",state2.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state2.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state2.braces+state2.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state2.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state2.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state2.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state2.backtrack=!0,state2.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state2.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state2.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state2.output=prev.output,state2.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state2.globstar=!0,state2.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state2.output+=prior.output+prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state2.output=prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state2.output=state2.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state2.output+=prev.output,state2.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state2.index===state2.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state2.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state2.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state2.output+=nodot,prev.output+=nodot;if(peek()!=="*")state2.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state2.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state2.output=utils.escapeLast(state2.output,"["),decrement("brackets")}while(state2.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state2.output=utils.escapeLast(state2.output,"("),decrement("parens")}while(state2.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state2.output=utils.escapeLast(state2.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state2.backtrack===!0){state2.output="";for(let token of state2.tokens)if(state2.output+=token.output!=null?token.output:token.value,token.suffix)state2.output+=token.suffix}return state2};parse9.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants5.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state2={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state2),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse9});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse9=require_parse(),utils=require_utils(),constants5=require_constants(),isObject3=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state3=isMatch(str);if(state3)return state3}return!1}}let isState=isObject3(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix11=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state2=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix11}),result={glob,state:state2,regex,posix:posix11,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state2;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix11}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix11?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix11);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse9(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state2,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state2.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state2.output})${append}`;if(state2&&state2.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state2;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse9.fastpaths(input,options);if(!parsed.output)parsed=parse9(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants5;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count=1){let requested=Number(count);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import*as fsSync9 from"node:fs";import*as path81 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error93){return log("[Guardrails] hashArgs failed",{error:error93 instanceof Error?error93.message:String(error93)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached3=pathNormalizationCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let absolutePath=path81.isAbsolute(filePath)?filePath:path81.resolve(cwd,filePath),normalized=fsSync9.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path81.isAbsolute(filePath)?filePath:path81.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached3=globMatcherCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path81.resolve(cwd),normalizedTarget=path81.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path81.relative(normalizedCwd,current);if(rel===""||rel===".."||rel.startsWith(`..${path81.sep}`)||path81.isAbsolute(rel))break;ancestors.push(current);let parent=path81.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat9=null;try{stat9=fsSync9.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat9.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink/junction — writing through a symlink or junction could redirect the write outside the working directory`}return null}function matchesAuthorityDenyPrefix(candidate,prefix,cwd,flavor=getPathFlavor()){let pathImpl=flavor==="win32"?path81.win32:path81.posix,normalizeInput=(value)=>flavor==="win32"?value.replace(/\//g,"\\"):value,normalizedPrefixInput=normalizeInput(prefix),requiresComponentBoundary=normalizedPrefixInput.endsWith(pathImpl.sep),root=pathImpl.resolve(normalizeInput(cwd)),target=pathImpl.resolve(root,normalizeInput(candidate)),denied=pathImpl.resolve(root,normalizedPrefixInput);if(!isPathIdentityWithin(target,root,flavor)||!isPathIdentityWithin(denied,root,flavor))return!1;let identity=(value)=>flavor==="win32"?value.toLowerCase():value,targetIdentity=identity(target),deniedIdentity=identity(denied);return requiresComponentBoundary?targetIdentity===deniedIdentity||targetIdentity.startsWith(`${deniedIdentity}${pathImpl.sep}`):targetIdentity.startsWith(deniedIdentity)}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path81){let flavor=pathLib===path81.win32||pathLib.parse("C:\\probe").root!==""?"win32":"posix";return isOnDifferentPathRoot(targetAbsolute,cwdAbsolute,flavor)}function denyAuthority(agent,normalizedPath,input){let safeAgent=sanitizeDiagnosticText(agent,96),safePath=sanitizeDiagnosticText(normalizedPath,320),safeDetail=sanitizeDiagnosticText(input.detail,640);return{allowed:!1,code:input.code,layer:input.layer,rule:sanitizeDiagnosticText(input.rule,128),path:safePath,agent:safeAgent,reason:sanitizeDiagnosticText(`${input.code}: Path blocked: ${safeDetail} [agent=${safeAgent}; path=${safePath}]`,1024),recovery:input.recovery,zone:input.zone}}function formatAllowedHints(rules){let fmt=(items)=>{if(!items||items.length===0)return"(none)";if(items.length<=MAX_ALLOWED_HINT_ENTRIES)return items.join(", ");let omitted=items.length-MAX_ALLOWED_HINT_ENTRIES;return`${items.slice(0,MAX_ALLOWED_HINT_ENTRIES).join(", ")}, … (+${omitted} more)`},parts=[];if(rules.allowedExact&&rules.allowedExact.length>0)parts.push(`Allowed exact paths: ${fmt(rules.allowedExact)}`);if(parts.push(`Allowed prefixes: ${fmt(rules.allowedPrefix)}`),parts.push(`Allowed globs: ${fmt(rules.allowedGlobs)}`),rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0)parts.push(`Allowed case-sensitive globs: ${fmt(rules.allowedCaseSensitiveGlobs)}`);return parts.push("Block rules (blocked zones/prefixes/globs/exact) and universal deny paths still apply."),parts.join(" ")}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options={}){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),unsafePathReason=unsafePathTextReason(filePath);if(unsafePathReason)return denyAuthority(agentName,filePath,{code:"AUTHORITY_INVALID_PATH",layer:"path-validation",rule:"safe-path-text",detail:unsafePathReason});let normalizedPath,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path81.resolve(dir,normalizedWithSymlinks),normalizedPath=path81.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path81.resolve(dir,filePath),normalizedPath=path81.relative(dir,resolvedTarget).replace(/\\/g,"/")}if(isOnDifferentFilesystemRoot(resolvedTarget,dir))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"same-filesystem-root",detail:"target is on a different drive or filesystem root"});if(normalizedPath===".."||normalizedPath.startsWith("../"))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:"target resolves outside the working directory"});let rules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent];if(!rules)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNKNOWN_AGENT",layer:"role-capability",rule:"known-agent-role",detail:"Unknown agent: no authority classification exists"});let flavor=getPathFlavor(),matchesPathPrefix=(candidate,prefix)=>isPathIdentityWithin(path81.resolve(dir,candidate),path81.resolve(dir,prefix),flavor),matchesGlob=(glob)=>getGlobMatcher(glob)(normalizedPath);for(let prefix of options.universalDenyPrefixes??[])if(matchesAuthorityDenyPrefix(normalizedPath,prefix,dir,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNIVERSAL_DENY",layer:"universal-deny",rule:`universal:${prefix}`,detail:`target is under universal deny prefix ${prefix}`});let isCoderAgent=normalizedAgent==="coder"||strippedAgent==="coder";if(isCoderAgent&&isPolicyProtectedPath(normalizedPath,{includeDefaults:!1,additional:[".git",".swarm"]}))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"coder-control-state-protection",detail:"coder writes to repository control state (.git/.swarm) are always protected"});if(Object.hasOwn(AUTHORITY_ROLE_CAPABILITIES,strippedAgent)){let matchedVerifier=[...BUILT_IN_VERIFIER_CONFIG_GLOBS,...options.verifierConfigPaths??[]].find(matchesGlob);if(matchedVerifier)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_VERIFIER_CONFIG",layer:"protected-path",rule:`verifier-config:${matchedVerifier}`,detail:`Path blocked (glob ${matchedVerifier}): swarm roles cannot write verifier-owned configuration in the config zone`})}let canonicalCapability=AUTHORITY_ROLE_CAPABILITIES[strippedAgent];if(canonicalCapability==="read-only"||canonicalCapability==="dedicated-tool-only")return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:`role-capability:${canonicalCapability}`,detail:canonicalCapability==="dedicated-tool-only"?"role may mutate state only through dedicated tools":"agent role is read-only"});if(rules.readOnly)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:"role-policy:read-only",detail:"agent role is read-only"});if(isCoderAgent&&options.declaredScope!=null&&options.declaredScope.length>0&&isPathWithinDeclaredScope(normalizedPath,options.declaredScope,dir))return{allowed:!0,layer:"declared-scope",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(options.authorityEnabled===!1)return{allowed:!0,layer:"role-policy",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(pathIdentitiesEqual(normalizedPath,blocked,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedExact:${blocked}`,detail:`path is blocked by exact role policy ${blocked}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(matchesGlob(glob))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedGlob:${glob}`,detail:`Path blocked (glob ${glob}) by role policy`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>pathIdentitiesEqual(normalizedPath,allowed,flavor)))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath);if(rules.blockedZones.includes(zone))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedZone:${zone}`,detail:`path is in ${zone} zone`,recovery:isCoderAgent?"declare_scope":void 0,zone})}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some(matchesGlob))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath)}))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(matchesPathPrefix(normalizedPath,prefix))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedPrefix:${prefix}`,detail:`path is under blocked role prefix ${prefix}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>matchesPathPrefix(normalizedPath,prefix)))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix",detail:`path is not in allowed list for this role. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0})}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix:empty",detail:`path is not in allowed list because the role allowlist is empty. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0});return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options={}){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),{...options,authorityEnabled:authorityConfig?.enabled??options.authorityEnabled,universalDenyPrefixes:authorityConfig?.universal_deny_prefixes??options.universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths??options.verifierConfigPaths})}var import_picomatch,pathNormalizationCache,globMatcherCache,AUTHORITY_ROLE_CAPABILITIES,NON_WRITING_SWARM_RULES,DEFAULT_AGENT_AUTHORITY_RULES,BUILT_IN_VERIFIER_CONFIG_GLOBS,MAX_ALLOWED_HINT_ENTRIES=20;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_core_events();init_path_identity();init_protected_path_policy();init_utils();init_arg_hash();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200});AUTHORITY_ROLE_CAPABILITIES={architect:"direct-write",coder:"direct-write",reviewer:"direct-write",critic:"direct-write",critic_oversight:"dedicated-tool-only",critic_finding_validator:"dedicated-tool-only",explorer:"read-only",sme:"read-only",researcher:"read-only",test_engineer:"direct-write",docs:"direct-write",docs_design:"direct-write",designer:"direct-write",critic_sounding_board:"read-only",critic_drift_verifier:"read-only",critic_hallucination_verifier:"read-only",critic_architecture_supervisor:"read-only",curator_init:"dedicated-tool-only",curator_phase:"dedicated-tool-only",curator_postmortem:"dedicated-tool-only",curator_consolidation:"dedicated-tool-only",council_generalist:"read-only",council_skeptic:"read-only",council_domain_expert:"read-only",skill_improver:"dedicated-tool-only",spec_writer:"dedicated-tool-only"},NON_WRITING_SWARM_RULES=Object.fromEntries(Object.entries(AUTHORITY_ROLE_CAPABILITIES).filter(([,capability])=>capability==="read-only"||capability==="dedicated-tool-only").map(([agent])=>[agent,{readOnly:!0}])),DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},...NON_WRITING_SWARM_RULES,architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}};BUILT_IN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.json","**/biome.jsonc","**/tsconfig*.json","**/.secretscanignore","**/.golangci*"]});import{createHash as createHash35}from"node:crypto";import*as fs52 from"node:fs";import*as path82 from"node:path";function fingerprint(filePath,budget){try{let stat9=fs52.lstatSync(filePath);if(stat9.isSymbolicLink())return{kind:"unsafe"};if(!stat9.isFile())return{kind:"unsafe"};if(stat9.size>MAX_HASH_BYTES||stat9.size>budget.remaining)return{kind:"unsafe"};budget.remaining-=stat9.size;let result={kind:"file",size:stat9.size,mtimeMs:stat9.mtimeMs};return result.hash=createHash35("sha256").update(fs52.readFileSync(filePath)).digest("hex"),result}catch(error93){return error93.code==="ENOENT"?{kind:"missing"}:{kind:"unsafe"}}}function changed(before,after){if(before.kind==="unsafe"||after.kind==="unsafe")return!1;if(before.kind!==after.kind)return!0;if(before.kind==="missing")return!1;if(before.hash!==void 0||after.hash!==void 0)return before.hash!==after.hash;return before.size!==after.size||before.mtimeMs!==after.mtimeMs}function effectFor(tool3,args2,targetCount){if(targetCount!==1||!args2||typeof args2!=="object")return{};let record3=args2;if(tool3==="write"||tool3==="create_file"){for(let key of["content","file_text","text"])if(typeof record3[key]==="string")return{exactContent:record3[key]}}if(tool3==="edit"||tool3==="replace"){for(let key of["newString","new_string","replacement"])if(typeof record3[key]==="string"&&record3[key]!=="")return{containsText:record3[key]}}return{}}function matchesExpected(filePath,expected,budget){if(expected.exactContent===void 0&&expected.containsText===void 0)return!0;try{let stat9=fs52.statSync(filePath);if(!stat9.isFile()||stat9.size>MAX_HASH_BYTES||stat9.size>budget.remaining)return!1;budget.remaining-=stat9.size;let content=fs52.readFileSync(filePath,"utf8");if(expected.exactContent!==void 0)return content===expected.exactContent;return content.includes(expected.containsText??"")}catch{return!1}}function numericExitCodes(metadata){if(!metadata||typeof metadata!=="object")return[];let record3=metadata;return["exitCode","exit_code","exit"].map((key)=>record3[key]).filter((value)=>typeof value==="number")}function directSuccess(output){let text=typeof output.output==="string"?output.output.trim():"",metadata=output.metadata&&typeof output.metadata==="object"?output.metadata:null;if(numericExitCodes(output.metadata).some((code)=>code!==0))return!1;if(metadata?.success===!0)return!0;if(metadata&&typeof metadata.status==="string"&&["success","completed","ok","applied"].includes(metadata.status.toLowerCase()))return!0;try{let parsed=JSON.parse(text);if(parsed.success===!0&&parsed.dryRun!==!0)return!0}catch{}return/^(?:Wrote file successfully\.|Edit applied successfully\.|Done!|Patch applied successfully\.|File (?:created|updated) successfully\.)/i.test(text)}function successful(tool3,output){if(tool3==="bash"||tool3==="shell"){let exitCodes=numericExitCodes(output.metadata);return exitCodes.length>0&&exitCodes.every((code)=>code===0)}return directSuccess(output)}function createScopeLeaseRenewalTracker(refresh=refreshScopeBindingLease,now=Date.now){let candidates=new Map,candidateKey=(sessionID,callID)=>`${sessionID}\x00${callID}`,sweep=()=>{let cutoff=now()-CANDIDATE_TTL_MS;for(let[key,candidate]of candidates)if(candidate.createdAt<cutoff)candidates.delete(key);while(candidates.size>=MAX_CANDIDATES2){let oldest=candidates.keys().next().value;if(oldest===void 0)break;candidates.delete(oldest)}};return{remember(input){sweep();let binding=input.binding;if(binding.activation!=="active"||binding.lifecycleState!=="live"||binding.expiresAt<=now()||binding.ownerSessionId!==input.sessionID||input.targets.length===0||input.targets.length>MAX_TARGETS)return;let uniqueTargets=[...new Set(input.targets.map((target)=>path82.resolve(target)))];if(uniqueTargets.length===0||uniqueTargets.length>MAX_TARGETS)return;let expected=effectFor(input.tool,input.args,uniqueTargets.length),hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},targets=uniqueTargets.map((target)=>({path:target,before:fingerprint(target,hashBudget),expected}));if(targets.some((target)=>target.before.kind==="unsafe"))return;candidates.set(candidateKey(input.sessionID,input.callID),{createdAt:now(),callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:input.directory,bindingId:binding.bindingId,generationId:binding.generationId,expectedRevision:binding.revision,taskId:binding.taskId,targets})},async consume(input){let key=candidateKey(input.sessionID,input.callID),candidate=candidates.get(key);if(candidates.delete(key),!candidate||candidate.sessionID!==input.sessionID||candidate.tool!==input.tool||now()-candidate.createdAt>CANDIDATE_TTL_MS||!input.output||!successful(candidate.tool,input.output))return null;let hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},contentBudget={remaining:MAX_AGGREGATE_HASH_BYTES};for(let target of candidate.targets){let after=fingerprint(target.path,hashBudget);if(!changed(target.before,after)||!matchesExpected(target.path,target.expected,contentBudget))return null}return refresh({directory:candidate.directory,bindingId:candidate.bindingId,generationId:candidate.generationId,expectedRevision:candidate.expectedRevision,activeSessionId:candidate.sessionID,taskId:candidate.taskId})}}}var MAX_CANDIDATES2=256,MAX_TARGETS=256,MAX_HASH_BYTES=4194304,MAX_AGGREGATE_HASH_BYTES=8388608,CANDIDATE_TTL_MS=600000;var init_scope_lease_renewal=__esm(()=>{init_scope_persistence()});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;let rejections=input.rejectionCount??0,resolutionPath,taskId=input.taskId??"unknown",conflictDedupeKey=`conflict:${taskId}:${rejections}`;if(rejections>=3)resolutionPath="soundingboard",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT ESCALATION (rejections=${rejections}): ${input.sourceAgent} vs ${input.targetAgent} on task ${taskId}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`,{dedupeKey:conflictDedupeKey});else resolutionPath="self_resolve",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT DETECTED (rejections=${rejections}): ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${taskId}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`,{dedupeKey:conflictDedupeKey});let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state2();init_telemetry()});import{createHash as createHash36}from"node:crypto";import*as fs53 from"node:fs";import*as path83 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file3){if(file3.includes("\x00")||hasControlCharacter(file3))return null;let root=path83.resolve(directory),absolute=path83.resolve(root,file3),relative20=path83.relative(root,absolute).replaceAll("\\","/");if(!relative20||relative20===".."||relative20.startsWith("../")||path83.isAbsolute(relative20))return null;return relative20}function isWithinRoot2(root,candidate){let relative20=path83.relative(root,candidate);return relative20===""||relative20!==".."&&!relative20.startsWith(`..${path83.sep}`)&&!path83.isAbsolute(relative20)}function deletedPathIsContained(canonicalRoot,absolute){let current=path83.dirname(absolute);for(;;){try{let canonical=_internals72.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}let parent=path83.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file3,options={}){if(typeof directory!=="string"||typeof file3!=="string")return{kind:"capture_failed",file:typeof file3==="string"?file3:"",code:"invalid_request",retryable:!1};if(file3.includes("\x00")||hasControlCharacter(file3))return{kind:"capture_failed",file:file3,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file3);if(!normalized)return{kind:"capture_failed",file:file3,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path83.resolve(directory,normalized);try{canonicalRoot=_internals72.realpathSync(path83.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals72.realpathSync(path83.dirname(absolute))}catch(error93){if(error93.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals72.realpathSync(path83.dirname(absolute))}catch(secondError){if(secondError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:secondError.code};secondFailed=!0}if(!secondFailed)canonicalParent=secondObservation;else{try{return _internals72.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error93.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals72.lstat(absolute)}catch(error93){if(error93.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error93.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals72.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path83.dirname(canonicalTarget)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}catch{return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1}}if(!before.isFile()||!Number.isSafeInteger(before.size)||before.size<0)return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};let openFlags=fs53.constants.O_RDONLY|(process.platform==="win32"?0:fs53.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals72.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals72.open(absolute,openFlags)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals72.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash4=createHash36("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals72.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals72.read(fd,chunk,0,chunk.byteLength,null)}catch(error93){let code=error93.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash4.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals72.fstat(fd,{bigint:!0});if(!sameSnapshot(openedBefore,openedAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};if(totalBytes!==Number(openedBefore.size))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let pathAfter;try{pathAfter=_internals72.stat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!pathAfter.isFile()||!sameSnapshot(openedBefore,pathAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let canonicalAfterRead;try{canonicalAfterRead=_internals72.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path83.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash4.digest("hex")}}finally{if(fd!==void 0)try{_internals72.close(fd)}catch{}}}function reviewerScopeCaptureToFingerprint(result){if(result.kind==="captured_file")return{file:result.file,kind:"file",size:result.size,hash:result.hash};if(result.kind==="captured_deleted")return{file:result.file,kind:"deleted"};return null}function reviewerScopeFileFingerprintsEqual(left,right){return left.file===right.file&&left.kind===right.kind&&(left.kind==="deleted"||right.kind==="file"&&left.size===right.size&&left.hash===right.hash)}var REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES=262144,REVIEWER_SCOPE_CAPTURE_ATTEMPTS=3,REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS=1e4,_internals72;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals72={open:fs53.openSync,fstat:(fd,options)=>fs53.fstatSync(fd,options),read:fs53.readSync,close:fs53.closeSync,lstat:fs53.lstatSync,stat:(path84,options)=>fs53.statSync(path84,options),realpathSync:fs53.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record3=output,nestedRecords=[record3.metadata,record3.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record3,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state2)=>NON_SUCCESS_STATES.has(state2)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state2)=>!knownStates.has(state2)))return"non_success";let metadata=nestedRecords[0];if(states.some((state2)=>RUNNING_STATES.has(state2))||metadata?.background===!0)return"running";if(states.some((state2)=>SUCCESS_STATES.has(state2)))return"success";if(typeof record3.output==="string")return"success";return Object.keys(record3).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state2()});import*as fs54 from"node:fs";import*as path84 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state2=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state2);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state2}function clearStreak(state2){state2.nonProgressCalls=0,state2.warnIssued=!1,state2.denyTelemetryIssued=!1,state2.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state2){state2.armed=!1,state2.workspaceBaseline=null,state2.needsWorkspaceBaseline=!1,clearStreak(state2),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state2){if(!state2.armed)state2.armed=!0,state2.needsWorkspaceBaseline=!0,clearStreak(state2);_internals73.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool3,args2){if(!isTaskToolId(tool3??""))return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs54.readFileSync(path84.join(directory,".swarm","plan.json"),"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan?.phases))return"unknown";for(let phase of plan.phases){if(!Array.isArray(phase?.tasks))continue;for(let task of phase.tasks)if(task?.status==="in_progress")return"open"}return"none"}catch{return"unknown"}}function isWriteToolName(normalizedTool){return WRITE_TOOL_NAMES.includes(normalizedTool)}function positiveInt(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function executionStallAdvisoryText(count){return`EXECUTION STALL: ${count} tool calls with no delegation completion, no file changes, and no status update. STOP investigating; delegate the work or report BLOCKED to the user.`}function executionStallDenialText(count,normalizedTool){return`EXECUTION_STALL: ${count} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool:tool3,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals73.now(),state2=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state2.armed&&now-state2.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state2);state2.lastToolCallAt=now;let role=canonicalDispatchRole(tool3,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state2)}if(!state2.armed)return;state2.nonProgressCalls+=1,state2.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state2.nonProgressCalls>=warnCalls&&!state2.warnIssued){state2.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state2.nonProgressCalls));telemetry.executionStallWarning(sessionID,state2.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool:tool3,options}=params,denial=null;try{if(options?.enabled===!1)return;let state2=stallStates.get(sessionID);if(!state2?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state2.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state2.denyTelemetryIssued){state2.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state2.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state2.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals73.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals73.captureWorkspaceSnapshotAsync(directory);if(!baseline)return{progress:!1,next:current};if(authoritative!==null)return{progress:authoritative.length>0,next:current};if(baseline.gitHead&&current?.gitHead&&baseline.gitHead!==current.gitHead)return{progress:!0,next:current};let before=new Set(baseline.changedFiles??[]);return{progress:(current?.changedFiles??[]).some((entry)=>!before.has(entry)),next:current}}catch{return{progress:!1,next:baseline}}}async function recordExecutionStallToolAfter(params){let{sessionID,tool:tool3,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool3??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals73.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state2=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state2);if(!state2.armed)return;if(taskSettled&&_internals73.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}if(progress){clearStreak(state2),state2.needsWorkspaceBaseline=!0;return}if(state2.needsWorkspaceBaseline){state2.needsWorkspaceBaseline=!1,state2.callsSinceWorkspaceProbe=0;try{state2.workspaceBaseline=await _internals73.captureWorkspaceSnapshotAsync(directory)}catch{state2.workspaceBaseline=null}return}if(state2.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state2.callsSinceWorkspaceProbe=0,_internals73.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}let probe2=await probeWorkspaceProgress(directory,state2.workspaceBaseline);if(state2.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state2)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals73;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state2();init_telemetry();init_normalize_tool_name();init_task_result_classifier();init_execution_episode();MUTATING_DELEGATION_ROLES=new Set(["coder","reviewer","test_engineer","security_reviewer"]),EXECUTION_STALL_DENIED_TOOLS=new Set(["read","glob","grep","bash","shell"]),stallStates=new Map,pendingDispatchRoles=new Map;_internals73={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path85 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path85.relative(path85.resolve(cwd),path85.resolve(cwd,filePath)).replace(/\\/g,"/"),{zone}=classifyFile(normalized);if(zone==="config")return!0;let allGlobs=extraGlobs&&extraGlobs.length>0?[...KNOWN_VERIFIER_CONFIG_GLOBS,...extraGlobs]:KNOWN_VERIFIER_CONFIG_GLOBS;for(let glob of allGlobs)if(getGlobMatcher(glob)(normalized))return!0;return!1}function isWriteTool(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isOutsideSwarmDir(filePath,directory){if(!filePath)return!1;let swarmDir=path85.resolve(directory,".swarm"),resolved=path85.resolve(directory,filePath),relative21=path85.relative(swarmDir,resolved);return relative21.startsWith("..")||path85.isAbsolute(relative21)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config3){let budget=config3.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function makeInjectionBudgetReceipt(data){let receipt=Object.freeze({});return injectionBudgetReceipts.set(receipt,{...data,state:"pending"}),receipt}function settleInjectionBudgetReceipt(receipt,action){let data=injectionBudgetReceipts.get(receipt);if(!data||data.state!=="pending")return!1;let ledger=turnLedgers.get(data.sessionID);if(!ledger||ledger.generation!==data.generation)return data.state="stale",!1;let accounting=ledger.producers.get(data.producer);if(!accounting||accounting!==data.accounting||accounting.surface!==data.surface)return data.state="stale",!1;if(action==="commit")return data.state="committed",!0;if(accounting.requested=Math.max(0,accounting.requested-data.requestedTokens),accounting.granted=Math.max(0,accounting.granted-data.grantedTokens),data.retractEmissionOnRefund){let retracted=Math.min(accounting.emitted,data.emittedTokensOnRefund);accounting.emitted-=retracted,accounting.truncated+=retracted}if(accounting.requested===0&&accounting.granted===0&&accounting.emitted===0&&accounting.truncated===0)ledger.producers.delete(data.producer);return ledger.used=Math.max(0,ledger.used-data.chargedTokens),data.state="refunded",!0}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{result:{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1}};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted,charged=0;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),charged=granted,ledger.used+=charged}return accounting.granted+=granted,{result:{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive},receiptData:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function claimTurnBudget(sessionID,producer,requestedTokens,opts){return applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts).result}function claimTurnBudgetWithReceipt(sessionID,producer,requestedTokens,opts){let mutation=applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts);return{...mutation.result,receipt:mutation.receiptData?makeInjectionBudgetReceipt(mutation.receiptData):void 0}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface)}function applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),requested=Math.max(0,requestedTokens);accounting.requested+=requested;let granted=Math.max(0,grantedTokens);accounting.granted+=granted;let charged=0;if(ledger.ceilingActive)charged=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used)),ledger.used+=charged;return{data:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function recordProducerGrantWithReceipt(sessionID,producer,requestedTokens,grantedTokens,surface,options={}){let mutation=applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,options.expectedGeneration);if(!mutation)return;return makeInjectionBudgetReceipt({...mutation.data,retractEmissionOnRefund:options.retractEmissionOnRefund===!0,emittedTokensOnRefund:Math.max(0,options.emittedTokensOnRefund??0)})}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options){applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options?.expectedGeneration)}function applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),emitted=Math.max(0,emittedTokens);return accounting.emitted+=emitted,accounting.truncated+=Math.max(0,truncatedTokens),{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:0,grantedTokens:0,chargedTokens:0,emittedTokensOnRefund:emitted,retractEmissionOnRefund:!0}}function recordProducerEmissionWithReceipt(sessionID,producer,emittedTokens,surface,options){let receiptData=applyProducerEmission(sessionID,producer,emittedTokens,0,surface,options?.expectedGeneration);return receiptData?makeInjectionBudgetReceipt(receiptData):void 0}function deductProducerEmission(sessionID,producer,removedTokens,options){let ledger=turnLedgers.get(sessionID);if(!ledger||options?.expectedGeneration!==void 0&&ledger.generation!==options.expectedGeneration)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,accounting])=>({producer,requested:accounting.requested,granted:accounting.granted,emitted:accounting.emitted,truncated:accounting.truncated,surface:accounting.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function commitInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"commit")}function refundInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"refund")}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var injectionBudgetReceipts,turnLedgers,MAX_TRACKED_SESSIONS=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();injectionBudgetReceipts=new WeakMap,turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&&QUOTA_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN,REQUEST_SHAPE_REJECTION_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,REQUEST_SHAPE_REJECTION_PATTERN=/\b(?:single|one|only|exactly)[^.]{0,48}?\bsystem\s+messages?\b|\bmultiple\s+system\s+messages?\b|\bsystem\s+messages?\s+(?:are\s+)?not\s+supported\b/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set3,key){if(set3.has(key))return!1;while(set3.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set3.values().next().value;if(oldest===void 0)break;set3.delete(oldest)}return set3.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals74.observeResolution({modelID,providerID,directory,resolution:resolution.source,aliasKeyClass:resolution.source==="user_provider_model"?"compound":resolution.source==="user_model"?"model":resolution.source==="user_default"?"default":void 0,invalidOverride}),{limit:resolution.tokens,source:classifyModelLimitSource(resolution.source),resolution:resolution.source}}function recordInvalidOverrides(modelID,providerID,configOverrides){if(!configOverrides||typeof configOverrides!=="object")return!1;let normalizedModel=modelID?.trim().toLowerCase(),normalizedCompound=`${providerID??""}/${modelID??""}`.trim().toLowerCase(),relevantInvalid=!1;for(let[key,value]of Object.entries(configOverrides)){if(isUsableConfiguredWindow(value))continue;let keyClass=key==="default"?"default":key.includes("/")?"compound":"model",normalizedKey=key.trim().toLowerCase();if(keyClass==="default"||keyClass==="model"&&normalizedModel!==void 0&&normalizedKey===normalizedModel||keyClass==="compound"&&normalizedKey===normalizedCompound)relevantInvalid=!0;let identity=`${modelID||"unknown"}::${providerID||"unknown"}::${keyClass}::${String(value)}`;if(rememberBoundedModelIdentity(invalidOverrideReports,identity))warn(`[model-limits] context_budget.model_limits.${key}=${String(value)} for ${modelID||"(no model)"}@${providerID||"(no provider)"} is not a usable limit (finite number ≥ 1); skipping it — not coercing.`,{modelID,providerID,keyClass,value})}return relevantInvalid}function warnNormalizedKeyCollisions(configOverrides){let byNormalized=new Map;for(let key of Object.keys(configOverrides)){let normalized=key.trim().toLowerCase();byNormalized.set(normalized,[...byNormalized.get(normalized)??[],key])}for(let[normalized,keys]of byNormalized){if(keys.length<2)continue;let identity=`collision::${normalized}`;if(!rememberBoundedModelIdentity(invalidOverrideReports,identity))continue;warn(`[model-limits] context_budget.model_limits has ${keys.length} keys that normalize identically (${keys.join(", ")}); only the last one in config order takes effect under normalized matching.`,{keys})}}function findNativeLimit(modelID){if(NATIVE_MODEL_LIMITS[modelID]!==void 0)return NATIVE_MODEL_LIMITS[modelID];let bestMatch;for(let key of Object.keys(NATIVE_MODEL_LIMITS))if(modelID.startsWith(key)){if(!bestMatch||key.length>bestMatch.length)bestMatch=key}return bestMatch?NATIVE_MODEL_LIMITS[bestMatch]:void 0}function logFirstCall(modelID,providerID,source,limit){let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(rememberBoundedModelIdentity(loggedFirstCalls,key))log(`[model-limits] Resolved limit for ${modelID||"(no model)"}@${providerID||"(no provider)"}: ${limit} (source: ${source})`)}function maybeWarnUndersizedDefault(modelID,providerID,source,resolvedTokens,liveContextLimit){if(source!=="user_default")return;if(!isUsableContextWindow(liveContextLimit))return;let liveTokens=Math.floor(liveContextLimit);if(liveTokens<=resolvedTokens)return;let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(!rememberBoundedModelIdentity(warnedUndersizedDefaults,key))return;warn(`[model-limits] context_budget.model_limits.default=${resolvedTokens} is below live model window ${liveTokens} for ${modelID||"(no model)"}@${providerID||"(no provider)"}; keeping the configured default.`,{modelID,providerID,resolvedTokens,liveTokens,source})}var NATIVE_MODEL_LIMITS,PROVIDER_CAPS,MAX_TRACKED_MODEL_IDENTITIES=256,loggedFirstCalls,warnedUndersizedDefaults,SOURCE_CLASS_BY_RESOLUTION,_internals74,invalidOverrideReports;var init_model_limits=__esm(()=>{init_learning_health();init_utils();NATIVE_MODEL_LIMITS={"claude-sonnet-4":200000,"claude-opus-4":200000,"claude-haiku-4":200000,"gpt-5":400000,"gpt-5.1-codex":400000,"gpt-5.1":264000,"gpt-4.1":1047576,"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,o3:200000,"o4-mini":200000,"deepseek-r1":163840,"deepseek-chat":163840,"qwen3.5":131072,"MiniMax-M3":1e6,"MiniMax-M2.7":204800},PROVIDER_CAPS={copilot:128000,"github-copilot":128000};loggedFirstCalls=new Set,warnedUndersizedDefaults=new Set;SOURCE_CLASS_BY_RESOLUTION={user_provider_model:"override",user_model:"override",user_default:"override",live_model_limit:"host",static_provider_cap:"provider_cap",static_native:"native",static_default:"fallback"};_internals74={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map3,sessionId,messageId){map3.delete(sessionId),map3.set(sessionId,messageId);while(map3.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map3.keys().next().value;if(stalest===void 0)break;map3.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
1035
+ `),{persisted:!0,path:filePath}}function readReviewRouteReceiptSync(input){let filePath=routeReceiptPath(input.projectRoot,input.sessionId,input.taskId),stat9;try{stat9=fs50.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}if(stat9.isSymbolicLink()||!stat9.isFile()||stat9.size>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_UNREADABLE: receipt is not a bounded regular file");let value;try{value=JSON.parse(fs50.readFileSync(filePath,"utf8"))}catch(error93){if(error93 instanceof SyntaxError)throw Error("ROUTE_RECEIPT_INVALID_JSON: receipt is not valid JSON");throw error93}let parsed=typeof value==="object"&&value!==null&&value.kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):value.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);if(!parsed.success)throw Error("ROUTE_RECEIPT_INVALID: receipt failed schema validation");let authenticated=authenticatePersistedRouteReceipt(parsed.data,readRouteReceiptSecretSync(input.projectRoot));if((authenticated.kind==="review_route_receipt"||authenticated.kind==="review_route_pending")&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");if(authenticated.kind==="review_route_router_error"&&authenticated.sessionId!==void 0&&authenticated.taskId!==void 0&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");return authenticated}function parseRouteReceipt(value){if(!value||typeof value!=="object")return null;let kind=value.kind,parsed=kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);return parsed.success?parsed.data:null}function fail(reason){return{canAdvance:!1,mode:"enforced",reason}}function enforceReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route=parseRouteReceipt(input.routeReceipt);if(!route)return fail("ROUTE_RECEIPT_MISSING");if(route.kind==="review_route_router_error"){if(input.sessionId&&(!route.sessionId||!route.taskId||route.sessionId!==input.sessionId||route.taskId!==input.taskId))return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");return{canAdvance:!0,mode:"fail_open",routerFailure:route.code}}if(route.kind==="review_route_pending")return fail("ROUTE_RECEIPT_PENDING");if(input.sessionId&&route.sessionId!==input.sessionId||input.taskId&&route.taskId!==input.taskId)return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");if(route.required.reviewers!==route.identities.reviewers.length||route.required.testEngineers!==route.identities.testEngineers.length)return fail("ROUTE_RECEIPT_COUNT_MISMATCH");let expected=new Map;for(let identity of route.identities.reviewers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"reviewer")}for(let identity of route.identities.testEngineers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"test_engineer")}if(input.requireEvidenceBindings&&input.requireCompleteEvidence===!1&&expected.size>0&&!input.expectedDispatch)return fail("ROUTE_RECEIPT_DISPATCH_REQUIRED");let seen=new Set,seenSlots=new Set;for(let evidence of input.receipts){if(input.requireEvidenceBindings&&(!evidence.sessionId||!evidence.taskId||!evidence.slotId||!evidence.callId||!evidence.childSessionId||typeof evidence.generation!=="number"))return fail("ROUTE_RECEIPT_BINDING_MISSING");let identity=evidence.identity.trim();if(!identity||identity.length>256)return fail("ROUTE_RECEIPT_INVALID_IDENTITY");let expectedRole=expected.get(identity);if(!expectedRole)return fail("ROUTE_RECEIPT_IDENTITY_UNLISTED");if(expectedRole!==evidence.role)return fail("ROUTE_RECEIPT_ROLE_MISMATCH");if(seen.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");if(evidence.sessionId&&evidence.sessionId!==route.sessionId)return fail("ROUTE_RECEIPT_SESSION_MISMATCH");if(evidence.taskId&&evidence.taskId!==route.taskId)return fail("ROUTE_RECEIPT_TASK_MISMATCH");if(evidence.slotId){if(seenSlots.has(evidence.slotId))return fail("ROUTE_RECEIPT_DUPLICATE");let slots=evidence.role==="reviewer"?route.slots?.reviewers:route.slots?.testEngineers;if(slots&&!slots.includes(evidence.slotId))return fail("ROUTE_RECEIPT_SLOT_UNLISTED");if(slots){let expectedIndex=evidence.role==="reviewer"?route.identities.reviewers.indexOf(identity):route.identities.testEngineers.indexOf(identity);if(expectedIndex<0||slots[expectedIndex]!==evidence.slotId)return fail("ROUTE_RECEIPT_SLOT_MISMATCH")}seenSlots.add(evidence.slotId)}seen.add(identity)}if(input.expectedDispatch){let expected2=input.expectedDispatch,matching=input.receipts.find((evidence)=>evidence.role===expected2.role&&evidence.identity===expected2.identity);if(!matching||matching.callId!==expected2.callId||matching.childSessionId!==expected2.childSessionId||matching.generation!==expected2.generation)return fail("ROUTE_RECEIPT_DISPATCH_MISMATCH")}if(input.requireCompleteEvidence!==!1&&seen.size!==expected.size)return fail("ROUTE_RECEIPT_INCOMPLETE");return{canAdvance:!0,mode:"enforced"}}function enforcePersistedReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route;try{route=readReviewRouteReceiptSync({projectRoot:input.projectRoot,sessionId:input.sessionId,taskId:input.taskId})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_AUTH_INVALID:"))return fail("ROUTE_RECEIPT_AUTH_INVALID");throw error93}if(!route&&input.legacyUnrouted)return{canAdvance:!0,mode:"legacy_unrouted",reason:"legacy_unrouted: route receipt predates version-1 enforcement"};return enforceReviewRouteReceipt({enforcementEnabled:!0,routeReceipt:route,receipts:input.receipts,sessionId:input.sessionId,taskId:input.taskId,requireEvidenceBindings:input.requireEvidenceBindings,expectedDispatch:input.expectedDispatch,requireCompleteEvidence:input.requireCompleteEvidence})}var REVIEW_ROUTE_RECEIPT_VERSION=1,IdentitySchema,RouteReceiptMacSchema,ReviewRouteReceiptSchema,ReviewRouteRouterErrorReceiptSchema,ReviewRoutePendingReceiptSchema,MAX_ROUTE_RECEIPT_BYTES=65536,ROUTE_RECEIPT_SECRET_FILE="review-route-receipts.key",ROUTE_RECEIPT_MAC_CONTEXT="opencode-swarm/review-route-receipt/v1\x00";var init_routing_enforcement=__esm(()=>{init_zod();init_task_file();init_utils2();init_hive_paths();init_project_boundary();IdentitySchema=exports_external.string().trim().min(1).max(256),RouteReceiptMacSchema=exports_external.string().regex(/^[0-9a-f]{64}$/,"route receipt MAC must be a SHA-256 HMAC"),ReviewRouteReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_receipt"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,complexity:exports_external.string().trim().min(1).max(80),semanticRisk:exports_external.string().trim().min(1).max(120),required:exports_external.object({reviewers:exports_external.number().int().nonnegative().max(16),testEngineers:exports_external.number().int().nonnegative().max(16)}),identities:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}),slots:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRouteRouterErrorReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_router_error"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),code:exports_external.enum(["NO_CHANGED_FILES","ROUTER_UNAVAILABLE","ROUTER_FAILED"]),failOpen:exports_external.literal(!0),sessionId:IdentitySchema.optional(),taskId:IdentitySchema.optional(),detail:exports_external.string().trim().max(512).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRoutePendingReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_pending"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict()});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),wal=await readWal(walPath,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal(walPath,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal(walPath,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function writeWal(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}async function ensureAuditEvent(directory,wal){if(hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))return;try{appendCoreEventSync(directory,{type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_REPAIR_AUDIT_LOCKED");throw error93}if(!hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}function workflowMatchesCommittedRepair(evidence,wal){let snapshot=getTaskWorkflowSnapshot(evidence);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence),existingWal=await readWal(walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence,existingWal))return await ensureAuditEvent(options.directory,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal(walPath,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal(walPath,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_core_events();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence,wal){let workflow=getTaskWorkflowSnapshot(evidence);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,readOnlyNoMutation:wal.readOnlyNoMutation,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath){try{return await _internals70.applyTerminalEvidence(transaction,wal)}catch(error93){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal2(walPath,{...wal,state:"ABORTED"}),null;if(wal.readOnlyNoMutation===!0&&!evidenceAlreadyTerminal){let replayed;try{replayed=await peekPlanFromLedger(directory)}catch(error93){throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: could not inspect the authoritative plan ledger: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}if(replayed.truncated||replayed.badSuffix!==null)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");if(!replayed.plan)throw Error("TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: authoritative plan ledger has no replayable plan");let authoritativeTask=replayed.plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!authoritativeTask)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);if(wal.version===2){let identity=await readPlanEpochIdentity(directory,replayed.plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}plan=replayed.plan,task=authoritativeTask;let currentFiles=authoritativeTask.files_touched;if(!(Array.isArray(currentFiles)&&currentFiles.length===0)){if(authoritativeTask.status!==wal.oldPlanStatus&&authoritativeTask.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${authoritativeTask.status}`);if(authoritativeTask.status===wal.newPlanStatus&&authoritativeTask.status!==wal.oldPlanStatus){let oldStatus=TaskStatusSchema.safeParse(wal.oldPlanStatus);if(!oldStatus.success)throw Error(`TASK_TERMINAL_OLD_STATUS_INVALID: ${wal.oldPlanStatus}`);let rolledBackPlan=await updateTaskStatus(directory,taskId,oldStatus.data,{planLockAlreadyHeld:!0,terminalReconciliation:!0}),rolledBackTask=rolledBackPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(rolledBackTask?.status!==oldStatus.data)throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_ROLLBACK_FAILED: expected ${oldStatus.data}, found ${rolledBackTask?.status??"missing task"}`);plan=rolledBackPlan}throw await writeWal2(walPath,{...wal,state:"ABORTED"}),Error(`TASK_TERMINAL_READ_ONLY_SCOPE_CHANGED: task ${taskId} no longer has a known empty declared scope; terminal evidence was not applied`)}}if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence:await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence);await options.validateEvidence?.(evidence);let terminal=options.resolveTerminal?.(evidence)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&existingWal.readOnlyNoMutation===!0===(terminal.readOnlyNoMutation===!0)&&evidenceMatchesTerminal(evidence,existingWal))return{plan:options.currentPlan,evidence,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath}); found ${evidence?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,...terminal.readOnlyNoMutation===!0?{readOnlyNoMutation:!0}:{},recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal2(walPath,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal2=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals70;var init_task_terminal=__esm(()=>{init_plan_schema();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals70={applyTerminalEvidence}});import*as fs51 from"node:fs";function storePath2(directory){return validateSwarmPath(directory,DEAD_LANE_RECLAIM_PATH)}function isDeadLaneReclaimEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return typeof candidate.lanePath==="string"&&candidate.lanePath.length>0&&typeof candidate.branchName==="string"&&typeof candidate.parentSessionId==="string"&&typeof candidate.taskId==="string"&&typeof candidate.reason==="string"&&typeof candidate.recordedAt==="number"}function readStore2(directory){try{let raw=fs51.readFileSync(storePath2(directory),"utf-8");if(raw.length>MAX_DEAD_LANE_RECLAIM_BYTES)return{schemaVersion:1,entries:[]};let parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{schemaVersion:1,entries:[]};return{schemaVersion:1,entries:parsed.entries.filter(isDeadLaneReclaimEntry)}}catch{return{schemaVersion:1,entries:[]}}}function writeStore2(directory,store){let entries=store.entries.slice(-MAX_DEAD_LANE_RECLAIMS);for(;;){let serialized2=JSON.stringify({schemaVersion:1,entries},null,2);if(serialized2.length<=MAX_DEAD_LANE_RECLAIM_BYTES||entries.length===0){if(entries.length<store.entries.length)log(`[dead-lane-reclaim] store bound dropped ${store.entries.length-entries.length} oldest entries (caps: ${MAX_DEAD_LANE_RECLAIMS} entries / ${MAX_DEAD_LANE_RECLAIM_BYTES} bytes)`);_internals71.atomicWriteSwarmFileSync(storePath2(directory),serialized2);return}entries=entries.slice(1)}}function recordDeadLaneReclaim(directory,entry){try{let filtered=readStore2(directory).entries.filter((existing)=>existing.lanePath!==entry.lanePath);filtered.push({...entry,recordedAt:Date.now()}),writeStore2(directory,{schemaVersion:1,entries:filtered})}catch(error93){log(`[dead-lane-reclaim] could not record stranded lane ${entry.lanePath}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function isLaneOwnedByActiveSession(lanePath,activeSessionIds,parentSessionId){if(activeSessionIds.has(parentSessionId??""))return!0;if(parentSessionId&&!lanePathIncludesSessionSegment(lanePath,parentSessionId))return!0;return!1}function lanePathIncludesSessionSegment(lanePath,sessionId){return lanePath.replace(/\\/g,"/").split("/").includes(sessionId)}async function isLaneDirty(lanePath){let proc;try{let options={cwd:lanePath,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:LANE_DIRTY_CHECK_TIMEOUT_MS,killProcessTree:!0};proc=_internals71.bunSpawn([_internals71.resolveGitExecutable(),"-C",lanePath,"status","--porcelain"],options);let stdout="";if(proc.stdout){let reader=proc.stdout.getReader();for(;;){let{done,value}=await reader.read();if(done||!value)break;if(stdout+=Buffer.from(value).toString("utf-8"),stdout.length>LANE_DIRTY_STDOUT_CAP_BYTES)break}}if(await proc.exited!==0)return!0;return stdout.trim().length>0}catch{return!0}finally{try{proc?.kill?.()}catch{}}}async function reclaimDeadLanes(directory,context={}){let result={reclaimed:[],retained:[]},store;try{store=readStore2(directory)}catch{return result}if(store.entries.length===0)return result;let activeSessionIds=new Set(context.activeSessionIds??[]),protectedPaths=new Set(context.protectedWorktreePaths??[]),retained=[];for(let entry of store.entries){let protectedLane=protectedPaths.has(entry.lanePath)||protectedPaths.has(_internals71.canonicalRootKeyFresh(entry.lanePath));if(_internals71.isLaneOwnedByActiveSession(entry.lanePath,activeSessionIds,entry.parentSessionId)||protectedLane){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"owned-by-active-session-or-protected"});continue}if(!await _internals71.pathExists(entry.lanePath))continue;if(await _internals71.isLaneDirty(entry.lanePath)){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"dirty-lane-preserved"});continue}_internals71.closeProjectDb(entry.lanePath);let removalError;try{let removal=await _internals71.removeWorktree(entry.lanePath,directory);if("error"in removal)removalError=removal.error}catch(error93){removalError=error93 instanceof Error?error93.message:String(error93)}if(removalError!==void 0){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:removalError});continue}result.reclaimed.push(entry.lanePath)}try{if(retained.length===0)fs51.rmSync(storePath2(directory),{force:!0});else writeStore2(directory,{schemaVersion:1,entries:retained})}catch(error93){log(`[dead-lane-reclaim] could not persist reclaim state: ${error93 instanceof Error?error93.message:String(error93)}`)}return result}async function pathExists2(target){try{return await fs51.promises.stat(target),!0}catch{return!1}}var DEAD_LANE_RECLAIM_PATH="dead-lane-reclaims.json",MAX_DEAD_LANE_RECLAIMS=512,MAX_DEAD_LANE_RECLAIM_BYTES=262144,LANE_DIRTY_CHECK_TIMEOUT_MS=5000,LANE_DIRTY_STDOUT_CAP_BYTES=4096,_internals71;var init_dead_lane_reclaim=__esm(()=>{init_project_db();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();init_utils2();_internals71={removeWorktree,closeProjectDb,isLaneOwnedByActiveSession,isLaneDirty,pathExists:pathExists2,bunSpawn,resolveGitExecutable,atomicWriteSwarmFileSync,canonicalRootKeyFresh}});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win329){return win329===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state2={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state2.prefix="./";return output};exports.wrapOutput=(input,state2={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state2.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path81,{windows}={})=>{let segs=path81.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state2={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state2.maxDepth=0,!isPathSeparator(code))tokens.push(token);state2.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state2.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state2.maxDepth+=tokens[tokens.length-1].depth}state2.slashes=slashes,state2.parts=parts}return state2};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants5=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants5,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants5.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse9=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants5.globChars(opts.windows),EXTGLOB_CHARS=constants5.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state2={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state2),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state2.index===len-1,peek=state2.peek=(n=1)=>input[state2.index+n],advance=state2.advance=()=>input[++state2.index]||"",remaining=()=>input.slice(state2.index+1),consume=(value2="",num=0)=>{state2.consumed+=value2,state2.index+=num},append=(token)=>{state2.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state2.start++,count++;if(count%2===0)return!1;return state2.negated=!0,state2.start++,!0},increment=(type)=>{state2[type]++,stack.push(type)},decrement=(type)=>{state2[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state2.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state2.output=state2.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state2.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state2.parens,token.output=state2.output,token.startIndex=state2.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state2.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal3=input.slice(token.startIndex,state2.index+1),body=input.slice(token.startIndex+2,state2.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open5=tokens[token.tokensIndex];open5.type="text",open5.value=literal3,open5.output=safeOutput||utils.escapeRegex(literal3);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state2.output=token.output+open5.output,state2.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse9(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state2.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc3,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc3)return esc3+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc3)return esc3+first+(rest?star:"");return star}return esc3?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state2.output=input,state2;return state2.output=utils.wrapOutput(output,state2,options),state2}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state2.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state2.brackets===0){push({type:"text",value});continue}}if(state2.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix11=POSIX_REGEX_SOURCE[rest2];if(posix11){if(prev.value=pre+posix11,state2.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state2.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state2.quotes=state2.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state2.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state2.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state2.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state2.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state2.output=state2.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state2.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state2.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open5={type:"brace",value,output:"(",outputIndex:state2.output.length,tokensIndex:state2.tokens.length};braces.push(open5),push(open5);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state2.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state2.output.slice(0,brace.outputIndex),toks=state2.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state2.output=out;for(let t of toks)state2.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state2.index===state2.start+1){state2.start=state2.index+1,state2.consumed="",state2.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state2.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state2.braces+state2.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state2.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state2.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state2.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state2.backtrack=!0,state2.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state2.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state2.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state2.output=prev.output,state2.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state2.globstar=!0,state2.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state2.output+=prior.output+prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state2.output=prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state2.output=state2.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state2.output+=prev.output,state2.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state2.index===state2.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state2.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state2.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state2.output+=nodot,prev.output+=nodot;if(peek()!=="*")state2.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state2.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state2.output=utils.escapeLast(state2.output,"["),decrement("brackets")}while(state2.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state2.output=utils.escapeLast(state2.output,"("),decrement("parens")}while(state2.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state2.output=utils.escapeLast(state2.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state2.backtrack===!0){state2.output="";for(let token of state2.tokens)if(state2.output+=token.output!=null?token.output:token.value,token.suffix)state2.output+=token.suffix}return state2};parse9.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants5.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state2={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state2),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse9});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse9=require_parse(),utils=require_utils(),constants5=require_constants(),isObject3=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state3=isMatch(str);if(state3)return state3}return!1}}let isState=isObject3(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix11=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state2=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix11}),result={glob,state:state2,regex,posix:posix11,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state2;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix11}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix11?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix11);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse9(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state2,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state2.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state2.output})${append}`;if(state2&&state2.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state2;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse9.fastpaths(input,options);if(!parsed.output)parsed=parse9(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants5;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count=1){let requested=Number(count);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import*as fsSync9 from"node:fs";import*as path81 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error93){return log("[Guardrails] hashArgs failed",{error:error93 instanceof Error?error93.message:String(error93)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached3=pathNormalizationCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let absolutePath=path81.isAbsolute(filePath)?filePath:path81.resolve(cwd,filePath),normalized=fsSync9.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path81.isAbsolute(filePath)?filePath:path81.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached3=globMatcherCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path81.resolve(cwd),normalizedTarget=path81.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path81.relative(normalizedCwd,current);if(rel===""||rel===".."||rel.startsWith(`..${path81.sep}`)||path81.isAbsolute(rel))break;ancestors.push(current);let parent=path81.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat9=null;try{stat9=fsSync9.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat9.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink/junction — writing through a symlink or junction could redirect the write outside the working directory`}return null}function matchesAuthorityDenyPrefix(candidate,prefix,cwd,flavor=getPathFlavor()){let pathImpl=flavor==="win32"?path81.win32:path81.posix,normalizeInput=(value)=>flavor==="win32"?value.replace(/\//g,"\\"):value,normalizedPrefixInput=normalizeInput(prefix),requiresComponentBoundary=normalizedPrefixInput.endsWith(pathImpl.sep),root=pathImpl.resolve(normalizeInput(cwd)),target=pathImpl.resolve(root,normalizeInput(candidate)),denied=pathImpl.resolve(root,normalizedPrefixInput);if(!isPathIdentityWithin(target,root,flavor)||!isPathIdentityWithin(denied,root,flavor))return!1;let identity=(value)=>flavor==="win32"?value.toLowerCase():value,targetIdentity=identity(target),deniedIdentity=identity(denied);return requiresComponentBoundary?targetIdentity===deniedIdentity||targetIdentity.startsWith(`${deniedIdentity}${pathImpl.sep}`):targetIdentity.startsWith(deniedIdentity)}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path81){let flavor=pathLib===path81.win32||pathLib.parse("C:\\probe").root!==""?"win32":"posix";return isOnDifferentPathRoot(targetAbsolute,cwdAbsolute,flavor)}function denyAuthority(agent,normalizedPath,input){let safeAgent=sanitizeDiagnosticText(agent,96),safePath=sanitizeDiagnosticText(normalizedPath,320),safeDetail=sanitizeDiagnosticText(input.detail,640);return{allowed:!1,code:input.code,layer:input.layer,rule:sanitizeDiagnosticText(input.rule,128),path:safePath,agent:safeAgent,reason:sanitizeDiagnosticText(`${input.code}: Path blocked: ${safeDetail} [agent=${safeAgent}; path=${safePath}]`,1024),recovery:input.recovery,zone:input.zone}}function formatAllowedHints(rules){let fmt=(items)=>{if(!items||items.length===0)return"(none)";if(items.length<=MAX_ALLOWED_HINT_ENTRIES)return items.join(", ");let omitted=items.length-MAX_ALLOWED_HINT_ENTRIES;return`${items.slice(0,MAX_ALLOWED_HINT_ENTRIES).join(", ")}, … (+${omitted} more)`},parts=[];if(rules.allowedExact&&rules.allowedExact.length>0)parts.push(`Allowed exact paths: ${fmt(rules.allowedExact)}`);if(parts.push(`Allowed prefixes: ${fmt(rules.allowedPrefix)}`),parts.push(`Allowed globs: ${fmt(rules.allowedGlobs)}`),rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0)parts.push(`Allowed case-sensitive globs: ${fmt(rules.allowedCaseSensitiveGlobs)}`);return parts.push("Block rules (blocked zones/prefixes/globs/exact) and universal deny paths still apply."),parts.join(" ")}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options={}){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),unsafePathReason=unsafePathTextReason(filePath);if(unsafePathReason)return denyAuthority(agentName,filePath,{code:"AUTHORITY_INVALID_PATH",layer:"path-validation",rule:"safe-path-text",detail:unsafePathReason});let normalizedPath,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path81.resolve(dir,normalizedWithSymlinks),normalizedPath=path81.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path81.resolve(dir,filePath),normalizedPath=path81.relative(dir,resolvedTarget).replace(/\\/g,"/")}if(isOnDifferentFilesystemRoot(resolvedTarget,dir))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"same-filesystem-root",detail:"target is on a different drive or filesystem root"});if(normalizedPath===".."||normalizedPath.startsWith("../"))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:"target resolves outside the working directory"});let rules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent];if(!rules)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNKNOWN_AGENT",layer:"role-capability",rule:"known-agent-role",detail:"Unknown agent: no authority classification exists"});let flavor=getPathFlavor(),matchesPathPrefix=(candidate,prefix)=>isPathIdentityWithin(path81.resolve(dir,candidate),path81.resolve(dir,prefix),flavor),matchesGlob=(glob)=>getGlobMatcher(glob)(normalizedPath);for(let prefix of options.universalDenyPrefixes??[])if(matchesAuthorityDenyPrefix(normalizedPath,prefix,dir,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNIVERSAL_DENY",layer:"universal-deny",rule:`universal:${prefix}`,detail:`target is under universal deny prefix ${prefix}`});let isCoderAgent=normalizedAgent==="coder"||strippedAgent==="coder";if(isCoderAgent&&isPolicyProtectedPath(normalizedPath,{includeDefaults:!1,additional:[".git",".swarm"]}))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"coder-control-state-protection",detail:"coder writes to repository control state (.git/.swarm) are always protected"});if(Object.hasOwn(AUTHORITY_ROLE_CAPABILITIES,strippedAgent)){let matchedVerifier=[...BUILT_IN_VERIFIER_CONFIG_GLOBS,...options.verifierConfigPaths??[]].find(matchesGlob);if(matchedVerifier)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_VERIFIER_CONFIG",layer:"protected-path",rule:`verifier-config:${matchedVerifier}`,detail:`Path blocked (glob ${matchedVerifier}): swarm roles cannot write verifier-owned configuration in the config zone`})}let canonicalCapability=AUTHORITY_ROLE_CAPABILITIES[strippedAgent];if(canonicalCapability==="read-only"||canonicalCapability==="dedicated-tool-only")return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:`role-capability:${canonicalCapability}`,detail:canonicalCapability==="dedicated-tool-only"?"role may mutate state only through dedicated tools":"agent role is read-only"});if(rules.readOnly)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:"role-policy:read-only",detail:"agent role is read-only"});if(isCoderAgent&&options.declaredScope!=null&&options.declaredScope.length>0&&isPathWithinDeclaredScope(normalizedPath,options.declaredScope,dir))return{allowed:!0,layer:"declared-scope",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(options.authorityEnabled===!1)return{allowed:!0,layer:"role-policy",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(pathIdentitiesEqual(normalizedPath,blocked,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedExact:${blocked}`,detail:`path is blocked by exact role policy ${blocked}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(matchesGlob(glob))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedGlob:${glob}`,detail:`Path blocked (glob ${glob}) by role policy`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>pathIdentitiesEqual(normalizedPath,allowed,flavor)))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath);if(rules.blockedZones.includes(zone))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedZone:${zone}`,detail:`path is in ${zone} zone`,recovery:isCoderAgent?"declare_scope":void 0,zone})}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some(matchesGlob))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath)}))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(matchesPathPrefix(normalizedPath,prefix))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedPrefix:${prefix}`,detail:`path is under blocked role prefix ${prefix}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>matchesPathPrefix(normalizedPath,prefix)))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix",detail:`path is not in allowed list for this role. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0})}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix:empty",detail:`path is not in allowed list because the role allowlist is empty. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0});return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options={}){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),{...options,authorityEnabled:authorityConfig?.enabled??options.authorityEnabled,universalDenyPrefixes:authorityConfig?.universal_deny_prefixes??options.universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths??options.verifierConfigPaths})}var import_picomatch,pathNormalizationCache,globMatcherCache,AUTHORITY_ROLE_CAPABILITIES,NON_WRITING_SWARM_RULES,DEFAULT_AGENT_AUTHORITY_RULES,BUILT_IN_VERIFIER_CONFIG_GLOBS,MAX_ALLOWED_HINT_ENTRIES=20;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_core_events();init_path_identity();init_protected_path_policy();init_utils();init_arg_hash();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200});AUTHORITY_ROLE_CAPABILITIES={architect:"direct-write",coder:"direct-write",reviewer:"direct-write",critic:"direct-write",critic_oversight:"dedicated-tool-only",critic_finding_validator:"dedicated-tool-only",explorer:"read-only",sme:"read-only",researcher:"read-only",test_engineer:"direct-write",docs:"direct-write",docs_design:"direct-write",designer:"direct-write",critic_sounding_board:"read-only",critic_drift_verifier:"read-only",critic_hallucination_verifier:"read-only",critic_architecture_supervisor:"read-only",curator_init:"dedicated-tool-only",curator_phase:"dedicated-tool-only",curator_postmortem:"dedicated-tool-only",curator_consolidation:"dedicated-tool-only",council_generalist:"read-only",council_skeptic:"read-only",council_domain_expert:"read-only",skill_improver:"dedicated-tool-only",spec_writer:"dedicated-tool-only"},NON_WRITING_SWARM_RULES=Object.fromEntries(Object.entries(AUTHORITY_ROLE_CAPABILITIES).filter(([,capability])=>capability==="read-only"||capability==="dedicated-tool-only").map(([agent])=>[agent,{readOnly:!0}])),DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},...NON_WRITING_SWARM_RULES,architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}};BUILT_IN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.json","**/biome.jsonc","**/tsconfig*.json","**/.secretscanignore","**/.golangci*"]});import{createHash as createHash35}from"node:crypto";import*as fs52 from"node:fs";import*as path82 from"node:path";function fingerprint(filePath,budget){try{let stat9=fs52.lstatSync(filePath);if(stat9.isSymbolicLink())return{kind:"unsafe"};if(!stat9.isFile())return{kind:"unsafe"};if(stat9.size>MAX_HASH_BYTES||stat9.size>budget.remaining)return{kind:"unsafe"};budget.remaining-=stat9.size;let result={kind:"file",size:stat9.size,mtimeMs:stat9.mtimeMs};return result.hash=createHash35("sha256").update(fs52.readFileSync(filePath)).digest("hex"),result}catch(error93){return error93.code==="ENOENT"?{kind:"missing"}:{kind:"unsafe"}}}function changed(before,after){if(before.kind==="unsafe"||after.kind==="unsafe")return!1;if(before.kind!==after.kind)return!0;if(before.kind==="missing")return!1;if(before.hash!==void 0||after.hash!==void 0)return before.hash!==after.hash;return before.size!==after.size||before.mtimeMs!==after.mtimeMs}function effectFor(tool3,args2,targetCount){if(targetCount!==1||!args2||typeof args2!=="object")return{};let record3=args2;if(tool3==="write"||tool3==="create_file"){for(let key of["content","file_text","text"])if(typeof record3[key]==="string")return{exactContent:record3[key]}}if(tool3==="edit"||tool3==="replace"){for(let key of["newString","new_string","replacement"])if(typeof record3[key]==="string"&&record3[key]!=="")return{containsText:record3[key]}}return{}}function matchesExpected(filePath,expected,budget){if(expected.exactContent===void 0&&expected.containsText===void 0)return!0;try{let stat9=fs52.statSync(filePath);if(!stat9.isFile()||stat9.size>MAX_HASH_BYTES||stat9.size>budget.remaining)return!1;budget.remaining-=stat9.size;let content=fs52.readFileSync(filePath,"utf8");if(expected.exactContent!==void 0)return content===expected.exactContent;return content.includes(expected.containsText??"")}catch{return!1}}function numericExitCodes(metadata){if(!metadata||typeof metadata!=="object")return[];let record3=metadata;return["exitCode","exit_code","exit"].map((key)=>record3[key]).filter((value)=>typeof value==="number")}function directSuccess(output){let text=typeof output.output==="string"?output.output.trim():"",metadata=output.metadata&&typeof output.metadata==="object"?output.metadata:null;if(numericExitCodes(output.metadata).some((code)=>code!==0))return!1;if(metadata?.success===!0)return!0;if(metadata&&typeof metadata.status==="string"&&["success","completed","ok","applied"].includes(metadata.status.toLowerCase()))return!0;try{let parsed=JSON.parse(text);if(parsed.success===!0&&parsed.dryRun!==!0)return!0}catch{}return/^(?:Wrote file successfully\.|Edit applied successfully\.|Done!|Patch applied successfully\.|File (?:created|updated) successfully\.)/i.test(text)}function successful(tool3,output){if(tool3==="bash"||tool3==="shell"){let exitCodes=numericExitCodes(output.metadata);return exitCodes.length>0&&exitCodes.every((code)=>code===0)}return directSuccess(output)}function createScopeLeaseRenewalTracker(refresh=refreshScopeBindingLease,now=Date.now){let candidates=new Map,candidateKey=(sessionID,callID)=>`${sessionID}\x00${callID}`,sweep=()=>{let cutoff=now()-CANDIDATE_TTL_MS;for(let[key,candidate]of candidates)if(candidate.createdAt<cutoff)candidates.delete(key);while(candidates.size>=MAX_CANDIDATES2){let oldest=candidates.keys().next().value;if(oldest===void 0)break;candidates.delete(oldest)}};return{remember(input){sweep();let binding=input.binding;if(binding.activation!=="active"||binding.lifecycleState!=="live"||binding.expiresAt<=now()||binding.ownerSessionId!==input.sessionID||input.targets.length===0||input.targets.length>MAX_TARGETS)return;let uniqueTargets=[...new Set(input.targets.map((target)=>path82.resolve(target)))];if(uniqueTargets.length===0||uniqueTargets.length>MAX_TARGETS)return;let expected=effectFor(input.tool,input.args,uniqueTargets.length),hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},targets=uniqueTargets.map((target)=>({path:target,before:fingerprint(target,hashBudget),expected}));if(targets.some((target)=>target.before.kind==="unsafe"))return;candidates.set(candidateKey(input.sessionID,input.callID),{createdAt:now(),callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:input.directory,bindingId:binding.bindingId,generationId:binding.generationId,expectedRevision:binding.revision,taskId:binding.taskId,targets})},async consume(input){let key=candidateKey(input.sessionID,input.callID),candidate=candidates.get(key);if(candidates.delete(key),!candidate||candidate.sessionID!==input.sessionID||candidate.tool!==input.tool||now()-candidate.createdAt>CANDIDATE_TTL_MS||!input.output||!successful(candidate.tool,input.output))return null;let hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},contentBudget={remaining:MAX_AGGREGATE_HASH_BYTES};for(let target of candidate.targets){let after=fingerprint(target.path,hashBudget);if(!changed(target.before,after)||!matchesExpected(target.path,target.expected,contentBudget))return null}return refresh({directory:candidate.directory,bindingId:candidate.bindingId,generationId:candidate.generationId,expectedRevision:candidate.expectedRevision,activeSessionId:candidate.sessionID,taskId:candidate.taskId})}}}var MAX_CANDIDATES2=256,MAX_TARGETS=256,MAX_HASH_BYTES=4194304,MAX_AGGREGATE_HASH_BYTES=8388608,CANDIDATE_TTL_MS=600000;var init_scope_lease_renewal=__esm(()=>{init_scope_persistence()});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;let rejections=input.rejectionCount??0,resolutionPath,taskId=input.taskId??"unknown",conflictDedupeKey=`conflict:${taskId}:${rejections}`;if(rejections>=3)resolutionPath="soundingboard",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT ESCALATION (rejections=${rejections}): ${input.sourceAgent} vs ${input.targetAgent} on task ${taskId}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`,{dedupeKey:conflictDedupeKey});else resolutionPath="self_resolve",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT DETECTED (rejections=${rejections}): ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${taskId}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`,{dedupeKey:conflictDedupeKey});let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state2();init_telemetry()});import{createHash as createHash36}from"node:crypto";import*as fs53 from"node:fs";import*as path83 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file3){if(file3.includes("\x00")||hasControlCharacter(file3))return null;let root=path83.resolve(directory),absolute=path83.resolve(root,file3),relative20=path83.relative(root,absolute).replaceAll("\\","/");if(!relative20||relative20===".."||relative20.startsWith("../")||path83.isAbsolute(relative20))return null;return relative20}function isWithinRoot2(root,candidate){let relative20=path83.relative(root,candidate);return relative20===""||relative20!==".."&&!relative20.startsWith(`..${path83.sep}`)&&!path83.isAbsolute(relative20)}function deletedPathIsContained(canonicalRoot,absolute){let current=path83.dirname(absolute);for(;;){try{let canonical=_internals72.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}let parent=path83.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file3,options={}){if(typeof directory!=="string"||typeof file3!=="string")return{kind:"capture_failed",file:typeof file3==="string"?file3:"",code:"invalid_request",retryable:!1};if(file3.includes("\x00")||hasControlCharacter(file3))return{kind:"capture_failed",file:file3,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file3);if(!normalized)return{kind:"capture_failed",file:file3,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path83.resolve(directory,normalized);try{canonicalRoot=_internals72.realpathSync(path83.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals72.realpathSync(path83.dirname(absolute))}catch(error93){if(error93.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals72.realpathSync(path83.dirname(absolute))}catch(secondError){if(secondError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:secondError.code};secondFailed=!0}if(!secondFailed)canonicalParent=secondObservation;else{try{return _internals72.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error93.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals72.lstat(absolute)}catch(error93){if(error93.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error93.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals72.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path83.dirname(canonicalTarget)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}catch{return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1}}if(!before.isFile()||!Number.isSafeInteger(before.size)||before.size<0)return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};let openFlags=fs53.constants.O_RDONLY|(process.platform==="win32"?0:fs53.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals72.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals72.open(absolute,openFlags)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals72.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash4=createHash36("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals72.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals72.read(fd,chunk,0,chunk.byteLength,null)}catch(error93){let code=error93.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash4.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals72.fstat(fd,{bigint:!0});if(!sameSnapshot(openedBefore,openedAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};if(totalBytes!==Number(openedBefore.size))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let pathAfter;try{pathAfter=_internals72.stat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!pathAfter.isFile()||!sameSnapshot(openedBefore,pathAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let canonicalAfterRead;try{canonicalAfterRead=_internals72.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path83.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash4.digest("hex")}}finally{if(fd!==void 0)try{_internals72.close(fd)}catch{}}}function reviewerScopeCaptureToFingerprint(result){if(result.kind==="captured_file")return{file:result.file,kind:"file",size:result.size,hash:result.hash};if(result.kind==="captured_deleted")return{file:result.file,kind:"deleted"};return null}function reviewerScopeFileFingerprintsEqual(left,right){return left.file===right.file&&left.kind===right.kind&&(left.kind==="deleted"||right.kind==="file"&&left.size===right.size&&left.hash===right.hash)}var REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES=262144,REVIEWER_SCOPE_CAPTURE_ATTEMPTS=3,REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS=1e4,_internals72;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals72={open:fs53.openSync,fstat:(fd,options)=>fs53.fstatSync(fd,options),read:fs53.readSync,close:fs53.closeSync,lstat:fs53.lstatSync,stat:(path84,options)=>fs53.statSync(path84,options),realpathSync:fs53.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record3=output,nestedRecords=[record3.metadata,record3.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record3,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state2)=>NON_SUCCESS_STATES.has(state2)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state2)=>!knownStates.has(state2)))return"non_success";let metadata=nestedRecords[0];if(states.some((state2)=>RUNNING_STATES.has(state2))||metadata?.background===!0)return"running";if(states.some((state2)=>SUCCESS_STATES.has(state2)))return"success";if(typeof record3.output==="string")return"success";return Object.keys(record3).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state2()});import*as fs54 from"node:fs";import*as path84 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state2=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state2);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state2}function clearStreak(state2){state2.nonProgressCalls=0,state2.warnIssued=!1,state2.denyTelemetryIssued=!1,state2.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state2){state2.armed=!1,state2.workspaceBaseline=null,state2.needsWorkspaceBaseline=!1,clearStreak(state2),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state2){if(!state2.armed)state2.armed=!0,state2.needsWorkspaceBaseline=!0,clearStreak(state2);_internals73.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool3,args2){if(!isTaskToolId(tool3??""))return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs54.readFileSync(path84.join(directory,".swarm","plan.json"),"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan?.phases))return"unknown";for(let phase of plan.phases){if(!Array.isArray(phase?.tasks))continue;for(let task of phase.tasks)if(task?.status==="in_progress")return"open"}return"none"}catch{return"unknown"}}function isWriteToolName(normalizedTool){return WRITE_TOOL_NAMES.includes(normalizedTool)}function positiveInt(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function executionStallAdvisoryText(count){return`EXECUTION STALL: ${count} tool calls with no delegation completion, no file changes, and no status update. STOP investigating; delegate the work or report BLOCKED to the user.`}function executionStallDenialText(count,normalizedTool){return`EXECUTION_STALL: ${count} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool:tool3,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals73.now(),state2=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state2.armed&&now-state2.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state2);state2.lastToolCallAt=now;let role=canonicalDispatchRole(tool3,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state2)}if(!state2.armed)return;state2.nonProgressCalls+=1,state2.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state2.nonProgressCalls>=warnCalls&&!state2.warnIssued){state2.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state2.nonProgressCalls));telemetry.executionStallWarning(sessionID,state2.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool:tool3,options}=params,denial=null;try{if(options?.enabled===!1)return;let state2=stallStates.get(sessionID);if(!state2?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state2.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state2.denyTelemetryIssued){state2.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state2.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state2.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals73.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals73.captureWorkspaceSnapshotAsync(directory);if(!baseline)return{progress:!1,next:current};if(authoritative!==null)return{progress:authoritative.length>0,next:current};if(baseline.gitHead&&current?.gitHead&&baseline.gitHead!==current.gitHead)return{progress:!0,next:current};let before=new Set(baseline.changedFiles??[]);return{progress:(current?.changedFiles??[]).some((entry)=>!before.has(entry)),next:current}}catch{return{progress:!1,next:baseline}}}async function recordExecutionStallToolAfter(params){let{sessionID,tool:tool3,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool3??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals73.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state2=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state2);if(!state2.armed)return;if(taskSettled&&_internals73.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}if(progress){clearStreak(state2),state2.needsWorkspaceBaseline=!0;return}if(state2.needsWorkspaceBaseline){state2.needsWorkspaceBaseline=!1,state2.callsSinceWorkspaceProbe=0;try{state2.workspaceBaseline=await _internals73.captureWorkspaceSnapshotAsync(directory)}catch{state2.workspaceBaseline=null}return}if(state2.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state2.callsSinceWorkspaceProbe=0,_internals73.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}let probe2=await probeWorkspaceProgress(directory,state2.workspaceBaseline);if(state2.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state2)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals73;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state2();init_telemetry();init_normalize_tool_name();init_task_result_classifier();init_execution_episode();MUTATING_DELEGATION_ROLES=new Set(["coder","reviewer","test_engineer","security_reviewer"]),EXECUTION_STALL_DENIED_TOOLS=new Set(["read","glob","grep","bash","shell"]),stallStates=new Map,pendingDispatchRoles=new Map;_internals73={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path85 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path85.relative(path85.resolve(cwd),path85.resolve(cwd,filePath)).replace(/\\/g,"/"),{zone}=classifyFile(normalized);if(zone==="config")return!0;let allGlobs=extraGlobs&&extraGlobs.length>0?[...KNOWN_VERIFIER_CONFIG_GLOBS,...extraGlobs]:KNOWN_VERIFIER_CONFIG_GLOBS;for(let glob of allGlobs)if(getGlobMatcher(glob)(normalized))return!0;return!1}function isWriteTool(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isOutsideSwarmDir(filePath,directory){if(!filePath)return!1;let swarmDir=path85.resolve(directory,".swarm"),resolved=path85.resolve(directory,filePath),relative21=path85.relative(swarmDir,resolved);return relative21.startsWith("..")||path85.isAbsolute(relative21)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config3){let budget=config3.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function makeInjectionBudgetReceipt(data){let receipt=Object.freeze({});return injectionBudgetReceipts.set(receipt,{...data,state:"pending"}),receipt}function settleInjectionBudgetReceipt(receipt,action){let data=injectionBudgetReceipts.get(receipt);if(!data||data.state!=="pending")return!1;let ledger=turnLedgers.get(data.sessionID);if(!ledger||ledger.generation!==data.generation)return data.state="stale",!1;let accounting=ledger.producers.get(data.producer);if(!accounting||accounting!==data.accounting||accounting.surface!==data.surface)return data.state="stale",!1;if(action==="commit")return data.state="committed",!0;if(accounting.requested=Math.max(0,accounting.requested-data.requestedTokens),accounting.granted=Math.max(0,accounting.granted-data.grantedTokens),data.retractEmissionOnRefund){let retracted=Math.min(accounting.emitted,data.emittedTokensOnRefund);accounting.emitted-=retracted,accounting.truncated+=retracted}if(accounting.requested===0&&accounting.granted===0&&accounting.emitted===0&&accounting.truncated===0)ledger.producers.delete(data.producer);return ledger.used=Math.max(0,ledger.used-data.chargedTokens),data.state="refunded",!0}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{result:{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1}};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted,charged=0;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),charged=granted,ledger.used+=charged}return accounting.granted+=granted,{result:{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive},receiptData:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function claimTurnBudget(sessionID,producer,requestedTokens,opts){return applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts).result}function claimTurnBudgetWithReceipt(sessionID,producer,requestedTokens,opts){let mutation=applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts);return{...mutation.result,receipt:mutation.receiptData?makeInjectionBudgetReceipt(mutation.receiptData):void 0}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface)}function applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),requested=Math.max(0,requestedTokens);accounting.requested+=requested;let granted=Math.max(0,grantedTokens);accounting.granted+=granted;let charged=0;if(ledger.ceilingActive)charged=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used)),ledger.used+=charged;return{data:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function recordProducerGrantWithReceipt(sessionID,producer,requestedTokens,grantedTokens,surface,options={}){let mutation=applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,options.expectedGeneration);if(!mutation)return;return makeInjectionBudgetReceipt({...mutation.data,retractEmissionOnRefund:options.retractEmissionOnRefund===!0,emittedTokensOnRefund:Math.max(0,options.emittedTokensOnRefund??0)})}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options){applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options?.expectedGeneration)}function applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),emitted=Math.max(0,emittedTokens);return accounting.emitted+=emitted,accounting.truncated+=Math.max(0,truncatedTokens),{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:0,grantedTokens:0,chargedTokens:0,emittedTokensOnRefund:emitted,retractEmissionOnRefund:!0}}function recordProducerEmissionWithReceipt(sessionID,producer,emittedTokens,surface,options){let receiptData=applyProducerEmission(sessionID,producer,emittedTokens,0,surface,options?.expectedGeneration);return receiptData?makeInjectionBudgetReceipt(receiptData):void 0}function deductProducerEmission(sessionID,producer,removedTokens,options){let ledger=turnLedgers.get(sessionID);if(!ledger||options?.expectedGeneration!==void 0&&ledger.generation!==options.expectedGeneration)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,accounting])=>({producer,requested:accounting.requested,granted:accounting.granted,emitted:accounting.emitted,truncated:accounting.truncated,surface:accounting.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function commitInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"commit")}function refundInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"refund")}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var injectionBudgetReceipts,turnLedgers,MAX_TRACKED_SESSIONS=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();injectionBudgetReceipts=new WeakMap,turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&&QUOTA_ERROR_PATTERN.test(signal)}function isStickyModelError(signal){return MODEL_UNAVAILABLE_PATTERN.test(signal)||isQuotaError(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,MODEL_UNAVAILABLE_PATTERN,QUOTA_ERROR_PATTERN,REQUEST_SHAPE_REJECTION_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|model.?unavailable|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,MODEL_UNAVAILABLE_PATTERN=/model.?unavailable/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,REQUEST_SHAPE_REJECTION_PATTERN=/\b(?:single|one|only|exactly)[^.]{0,48}?\bsystem\s+messages?\b|\bmultiple\s+system\s+messages?\b|\bsystem\s+messages?\s+(?:are\s+)?not\s+supported\b/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set3,key){if(set3.has(key))return!1;while(set3.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set3.values().next().value;if(oldest===void 0)break;set3.delete(oldest)}return set3.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals74.observeResolution({modelID,providerID,directory,resolution:resolution.source,aliasKeyClass:resolution.source==="user_provider_model"?"compound":resolution.source==="user_model"?"model":resolution.source==="user_default"?"default":void 0,invalidOverride}),{limit:resolution.tokens,source:classifyModelLimitSource(resolution.source),resolution:resolution.source}}function recordInvalidOverrides(modelID,providerID,configOverrides){if(!configOverrides||typeof configOverrides!=="object")return!1;let normalizedModel=modelID?.trim().toLowerCase(),normalizedCompound=`${providerID??""}/${modelID??""}`.trim().toLowerCase(),relevantInvalid=!1;for(let[key,value]of Object.entries(configOverrides)){if(isUsableConfiguredWindow(value))continue;let keyClass=key==="default"?"default":key.includes("/")?"compound":"model",normalizedKey=key.trim().toLowerCase();if(keyClass==="default"||keyClass==="model"&&normalizedModel!==void 0&&normalizedKey===normalizedModel||keyClass==="compound"&&normalizedKey===normalizedCompound)relevantInvalid=!0;let identity=`${modelID||"unknown"}::${providerID||"unknown"}::${keyClass}::${String(value)}`;if(rememberBoundedModelIdentity(invalidOverrideReports,identity))warn(`[model-limits] context_budget.model_limits.${key}=${String(value)} for ${modelID||"(no model)"}@${providerID||"(no provider)"} is not a usable limit (finite number ≥ 1); skipping it — not coercing.`,{modelID,providerID,keyClass,value})}return relevantInvalid}function warnNormalizedKeyCollisions(configOverrides){let byNormalized=new Map;for(let key of Object.keys(configOverrides)){let normalized=key.trim().toLowerCase();byNormalized.set(normalized,[...byNormalized.get(normalized)??[],key])}for(let[normalized,keys]of byNormalized){if(keys.length<2)continue;let identity=`collision::${normalized}`;if(!rememberBoundedModelIdentity(invalidOverrideReports,identity))continue;warn(`[model-limits] context_budget.model_limits has ${keys.length} keys that normalize identically (${keys.join(", ")}); only the last one in config order takes effect under normalized matching.`,{keys})}}function findNativeLimit(modelID){if(NATIVE_MODEL_LIMITS[modelID]!==void 0)return NATIVE_MODEL_LIMITS[modelID];let bestMatch;for(let key of Object.keys(NATIVE_MODEL_LIMITS))if(modelID.startsWith(key)){if(!bestMatch||key.length>bestMatch.length)bestMatch=key}return bestMatch?NATIVE_MODEL_LIMITS[bestMatch]:void 0}function logFirstCall(modelID,providerID,source,limit){let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(rememberBoundedModelIdentity(loggedFirstCalls,key))log(`[model-limits] Resolved limit for ${modelID||"(no model)"}@${providerID||"(no provider)"}: ${limit} (source: ${source})`)}function maybeWarnUndersizedDefault(modelID,providerID,source,resolvedTokens,liveContextLimit){if(source!=="user_default")return;if(!isUsableContextWindow(liveContextLimit))return;let liveTokens=Math.floor(liveContextLimit);if(liveTokens<=resolvedTokens)return;let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(!rememberBoundedModelIdentity(warnedUndersizedDefaults,key))return;warn(`[model-limits] context_budget.model_limits.default=${resolvedTokens} is below live model window ${liveTokens} for ${modelID||"(no model)"}@${providerID||"(no provider)"}; keeping the configured default.`,{modelID,providerID,resolvedTokens,liveTokens,source})}var NATIVE_MODEL_LIMITS,PROVIDER_CAPS,MAX_TRACKED_MODEL_IDENTITIES=256,loggedFirstCalls,warnedUndersizedDefaults,SOURCE_CLASS_BY_RESOLUTION,_internals74,invalidOverrideReports;var init_model_limits=__esm(()=>{init_learning_health();init_utils();NATIVE_MODEL_LIMITS={"claude-sonnet-4":200000,"claude-opus-4":200000,"claude-haiku-4":200000,"gpt-5":400000,"gpt-5.1-codex":400000,"gpt-5.1":264000,"gpt-4.1":1047576,"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,o3:200000,"o4-mini":200000,"deepseek-r1":163840,"deepseek-chat":163840,"qwen3.5":131072,"MiniMax-M3":1e6,"MiniMax-M2.7":204800},PROVIDER_CAPS={copilot:128000,"github-copilot":128000};loggedFirstCalls=new Set,warnedUndersizedDefaults=new Set;SOURCE_CLASS_BY_RESOLUTION={user_provider_model:"override",user_model:"override",user_default:"override",live_model_limit:"host",static_provider_cap:"provider_cap",static_native:"native",static_default:"fallback"};_internals74={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map3,sessionId,messageId){map3.delete(sessionId),map3.set(sessionId,messageId);while(map3.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map3.keys().next().value;if(stalest===void 0)break;map3.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
1036
1036
  `)}function getMostRecentAssistantText(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="assistant")return getMessageText(messages[i]);return""}function isTransientProviderFailureText(text){if(!text.trim())return!1;if(!/provider[_\s-]?unavailable|network\s+connection\s+lost|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN|connection\s+reset|connection\s+refused/i.test(text))return!1;let status=extractStatusCode(text);return status!==null&&TRANSIENT_STATUS_CODES.has(status)||TRANSIENT_MODEL_ERROR_PATTERN.test(text)}function getProviderFailureFingerprint(text){return String(hashArgs({providerFailure:text.slice(-4000)}))}function createMessagesTransformHandler(ctx){let{effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId}=ctx;return async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastMessage=messages[messages.length-1],sessionId=lastMessage.info?.sessionID;if(!sessionId)return;let session=swarmState.agentSessions.get(sessionId),activeAgent=swarmState.activeAgent.get(sessionId)??session?.agentName,targetAgent=[...messages].reverse().find((message)=>message.info?.role==="user"&&typeof message.info.agent==="string"&&message.info.agent.length>0)?.info.agent;{let configuredModel=targetAgent?ctx.resolveAgentModel?.(targetAgent):void 0,targetModel=configuredModel?parseAgentModel(configuredModel):void 0,{modelID}=targetModel??extractModelInfo(messages);if(modelID&&isLowCapabilityModel(modelID))for(let msg of messages){if(msg.info?.role!=="system")continue;for(let part of msg.parts)try{if(part==null)continue;if(part.type!=="text"||typeof part.text!=="string")continue;if(!part.text.includes("<!-- BEHAVIORAL_GUIDANCE_START -->"))continue;part.text=part.text.replace(/<!--\s*BEHAVIORAL_GUIDANCE_START\s*-->[\s\S]*?<!--\s*BEHAVIORAL_GUIDANCE_END\s*-->/g,"[Enforcement: programmatic gates active]")}catch(error93){log("[Guardrails] behavioral guidance replacement failed",{error:error93 instanceof Error?error93.message:String(error93)})}}}let isArchitectSession=activeAgent?stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME:session?stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME:!1;if(isArchitectSession&&session){let{modelID,providerID}=extractModelInfo(messages);if(modelID){let observedFull=providerID?`${providerID}/${modelID}`:modelID,previousObserved=session.lastObservedModel;if(session.sessionRehydratedAt>0&&session.model_fallback_index===0&&previousObserved&&previousObserved!==observedFull&&!session.resumeModelAdvisoryDone)pushAdvisory(session,`MODEL CHANGED ACROSS RESUME: this run previously observed model "${previousObserved}"; the active model is now "${observedFull}". If this switch was unintended, re-select the intended model (or use /swarm handoff) before continuing.`),session.resumeModelAdvisoryDone=!0;if(!session.configModelAdvisoryDone&&session.model_fallback_index===0){let configuredArchitect=getSwarmAgents()?.architect?.model;if(configuredArchitect&&configuredArchitect!==observedFull&&configuredArchitect!==modelID)pushAdvisory(session,`MODEL CONFIG NOTE: your config pins the architect to "${configuredArchitect}", but the UI has "${observedFull}" active. The UI selection wins for the primary/architect role (its configured model is intentionally not applied), so this difference is expected — switch the UI model if you meant to run "${configuredArchitect}".`),session.configModelAdvisoryDone=!0}session.lastObservedModel=observedFull,session.lastObservedProviderID=providerID}}let guidanceCarriers=findGuidanceCarriers(messages);if(isArchitectSession&&session){let lastAssistantText=getMostRecentAssistantText(messages);if(isTransientProviderFailureText(lastAssistantText)){let fingerprint2=getProviderFailureFingerprint(lastAssistantText),alreadyPending=session.pendingAdvisoryMessages?.some((message)=>message.startsWith(TRANSIENT_PROVIDER_RECOVERY_TAG)),alreadyInjected=guidanceCarriers.some((message)=>getMessageText(message).includes(TRANSIENT_PROVIDER_RECOVERY_TAG));if(session.lastProviderRecoveryFingerprint!==fingerprint2&&!alreadyPending&&!alreadyInjected)pushAdvisory(session,`${TRANSIENT_PROVIDER_RECOVERY_TAG}: The previous Architect response appears to have been interrupted by a transient provider/network error. On this turn, continue from the last stable step, inspect current repo or plan state if needed, and keep working instead of treating the interrupted response as task completion.`),session.lastProviderRecoveryFingerprint=fingerprint2}else session.lastProviderRecoveryFingerprint=void 0}if(isArchitectSession){let countedMsgId=lastCountedAssistantMsgId.get(sessionId);if(countedMsgId!==void 0){let countedIdx=messages.findIndex((m)=>m.info?.id===countedMsgId);if(countedIdx<0)lastCountedAssistantMsgId.delete(sessionId);else if(messages.slice(countedIdx+1).some((m)=>m.info?.role==="user"))consecutiveNoToolTurns.set(sessionId,0),lastCountedAssistantMsgId.delete(sessionId)}let lastAssistantMsg;for(let i=messages.length-1;i>=0;i--)if(messages[i].info?.role==="assistant"){lastAssistantMsg=messages[i];break}if(lastAssistantMsg)if(lastAssistantMsg.parts?.some((part)=>part.type==="tool_use"))consecutiveNoToolTurns.set(sessionId,0);else{let textLen=lastAssistantMsg.parts?.filter((p)=>p.type==="text"&&typeof p.text==="string").reduce((sum,p)=>sum+p.text.length,0)??0,lastAssistantMsgId=lastAssistantMsg.info?.id,countsAsMedium=textLen>=RUNAWAY_MEDIUM_MIN&&textLen<=4000&&typeof lastAssistantMsgId==="string"&&lastAssistantMsgId.length>0&&isExecutionEpisodeArmed(sessionId);if(countsAsMedium&&lastAssistantMsgId)rememberCountedAssistantMsg(lastCountedAssistantMsgId,sessionId,lastAssistantMsgId);if(textLen>4000||countsAsMedium){let count=(consecutiveNoToolTurns.get(sessionId)??0)+1;consecutiveNoToolTurns.set(sessionId,count);let maxTurns=cfg.runaway_output_max_turns;if(count>=maxTurns){let stopCarrier=ensureGuidanceCarrier(messages,"guardrails");if(!messageTextOf(stopCarrier).includes("RUNAWAY OUTPUT STOP"))prependGuidanceText(stopCarrier,"guardrails",`[RUNAWAY OUTPUT STOP]
1037
1037
  You have produced ${count} consecutive responses without using any tools. You MUST call a tool in your next response.
1038
1038
  [/RUNAWAY OUTPUT STOP]
@@ -1087,7 +1087,7 @@ Do not acknowledge or reference this guidance in your response.
1087
1087
 
1088
1088
  `+textPart.text;else if(targetWindow.warningIssued){let reasonSuffix=targetWindow.warningReason?` (${targetWindow.warningReason})`:"";textPart.text=`[⚠️ APPROACHING LIMITS${reasonSuffix}: You still have capacity to finish your current step. Complete what you're working on, then return your results.]
1089
1089
 
1090
- `+textPart.text}}}function extractPhaseNumber(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function getCurrentTaskId2(sessionId){return swarmState.agentSessions.get(sessionId)?.currentTaskId??`${sessionId}:unknown`}var TRANSIENT_PROVIDER_RECOVERY_TAG="TRANSIENT PROVIDER RECOVERY",RUNAWAY_OUTPUT_ADVISORY_MARKER="Model is generating analysis without taking action",RUNAWAY_MEDIUM_MIN=200,MAX_TRACKED_COUNTED_ASSISTANT_MSGS=200,PRM_ADVISORY_FORWARD_PREFIX="[prm:",MAX_ADVISORY_BLOCK_BYTES=6000,ADVISORY_TRUNCATION_NOTE="[advisory block truncated to keep highest-value recent items]";var init_messages_transform=__esm(()=>{init_agents2();init_agent_model();init_constants();init_schema();init_manager();init_injection_budget();init_state2();init_telemetry();init_utils();init_provider_error_classification();init_extractors();init_model_limits();init_system_guidance_carrier();init_utils2();init_execution_episode();init_file_authority()});import{createHash as createHash37}from"node:crypto";function normalizeToolName2(tool3){return tool3.trim().toLowerCase()||"unknown-tool"}function hashString2(value){return createHash37("sha256").update(value).digest("hex")}function readRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:void 0}function fieldDigest(value){return value===null?null:hashString2(value).slice(0,DIGEST_PREFIX_LENGTH)}function readIdentityField(record3,keys){if(!record3)return{marker:"missing",value:null};for(let key of keys){if(!Object.hasOwn(record3,key))continue;let value=record3[key];if(value===void 0||value===null)return{marker:"empty",value:null};if(typeof value==="string"){let trimmed=value.trim();if(trimmed.length===0)return{marker:"empty",value:null};if(trimmed.length>MAX_PUBLIC_FIELD_LENGTH)return{marker:"value",value:`oversized:${hashString2(trimmed.slice(0,MAX_STRING_INPUT))}`};return{marker:"value",value:trimmed}}if(typeof value==="number"){if(!Number.isFinite(value))return{marker:"value",value:"invalid:number"};return{marker:"value",value:String(value)}}if(typeof value==="boolean")return{marker:"value",value:value?"true":"false"};return{marker:"value",value:`invalid:${Array.isArray(value)?"array":typeof value}`}}return{marker:"missing",value:null}}function readBackgroundField(record3){if(!record3)return{marker:"missing",value:null};for(let key of BACKGROUND_KEYS){if(!Object.hasOwn(record3,key))continue;let value=record3[key];if(value===void 0||value===null)return{marker:"empty",value:null};if(typeof value==="boolean")return{marker:"value",value};if(typeof value==="string"){let normalized=value.trim().toLowerCase();if(normalized.length===0)return{marker:"empty",value:null};if(normalized==="true")return{marker:"value",value:!0};if(normalized==="false")return{marker:"value",value:!1}}return{marker:"invalid",value:null}}return{marker:"missing",value:null}}function canonicalRole(raw){if(typeof raw!=="string"||raw.trim().length===0)return{role:"unknown-role",swarm:null};let trimmed=raw.trim(),role=stripKnownSwarmPrefix(trimmed).trim().toLowerCase()||"unknown-role";if(role===trimmed.toLowerCase())return{role,swarm:null};let suffix=`_${role}`;if(!trimmed.toLowerCase().endsWith(suffix))return{role,swarm:null};let swarm=trimmed.slice(0,trimmed.length-suffix.length).trim().toLowerCase();return{role,swarm:swarm.length>0?swarm:null}}function normalizeLeaf(value){if(value===void 0)return["undefined"];if(value===null)return["null"];if(typeof value==="string")return["string",hashString2(value.slice(0,MAX_STRING_INPUT))];if(typeof value==="number")return Number.isFinite(value)?["number",String(value)]:["number","non-finite"];if(typeof value==="boolean")return["boolean",value?"1":"0"];if(typeof value==="bigint")return["bigint",hashString2(String(value).slice(0,MAX_STRING_INPUT))];return["type",typeof value]}function canonicalizeAdditional(value,depth=0){if(value===void 0||value===null||typeof value==="string"||typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return normalizeLeaf(value);if(depth>=MAX_NORMALIZE_DEPTH)return["sentinel","depth-capped",hashString2(String(value).slice(0,MAX_STRING_INPUT))];if(Array.isArray(value)){let entries2=value.slice(0,MAX_COLLECTION_ITEMS).map((entry)=>canonicalizeAdditional(entry,depth+1));if(value.length>MAX_COLLECTION_ITEMS)entries2.push(["sentinel","array-capped",String(value.length)]);return["array",...entries2]}let record3=readRecord(value);if(!record3)return["type",typeof value,hashString2(String(value).slice(0,MAX_STRING_INPUT))];let keys=Object.keys(record3).sort(),entries=keys.slice(0,MAX_OBJECT_KEYS).map((key)=>[key,canonicalizeAdditional(record3[key],depth+1)]);if(keys.length>MAX_OBJECT_KEYS)entries.push(["__truncated_keys__",["sentinel","keys-capped",String(keys.length)]]);return["object",...entries]}function omitKnownKeys(record3,knownKeys){if(!record3)return null;let entries=Object.entries(record3).filter(([key])=>!knownKeys.has(key));return entries.length>0?Object.fromEntries(entries):null}function extractScopeIdentity(record3){if(!record3)return{marker:"missing",digest:null};let present=SCOPE_KEYS.filter((key)=>Object.hasOwn(record3,key));if(present.length===0)return{marker:"missing",digest:null};let subset=Object.fromEntries(present.map((key)=>[key,record3[key]]));if(present.every((key)=>{let value=record3[key];return value===void 0||value===null||typeof value==="string"&&value.trim().length===0}))return{marker:"empty",digest:null};return{marker:"value",digest:hashString2(JSON.stringify(canonicalizeAdditional(subset)))}}function buildPatternSegment(label,marker,digest3){return digest3?`${label}-${marker}-${digest3}`:`${label}-${marker}`}function createActionIdentity(input){let args2=readRecord(input.args),{role,swarm}=canonicalRole(readIdentityField(args2,ROLE_KEYS).value??args2?.subagent_type??args2?.agent??args2?.role),task=readIdentityField(args2,TASK_KEYS),phase=readIdentityField(args2,PHASE_KEYS),parentSession=readIdentityField(args2,PARENT_SESSION_KEYS),parentInvocation=readIdentityField(args2,PARENT_INVOCATION_KEYS),dispatchGeneration=readIdentityField(args2,DISPATCH_GENERATION_KEYS),mode=readIdentityField(args2,MODE_KEYS),background=readBackgroundField(args2),scope=extractScopeIdentity(args2),knownKeys=new Set([...ROLE_KEYS,...TASK_KEYS,...PHASE_KEYS,...PARENT_SESSION_KEYS,...PARENT_INVOCATION_KEYS,...DISPATCH_GENERATION_KEYS,...MODE_KEYS,...BACKGROUND_KEYS,...SCOPE_KEYS]),additionalDigest=hashString2(JSON.stringify(canonicalizeAdditional(omitKnownKeys(args2,knownKeys)))),normalized={tool:normalizeToolName2(input.tool),role,swarm,task,phase,parentSession:{marker:parentSession.marker,digest:parentSession.value===null?null:hashString2(parentSession.value)},parentInvocation,dispatchGeneration,mode,background,scope,additionalDigest},digest3=hashString2(JSON.stringify(normalized)),pattern=[normalized.tool,role,buildPatternSegment("task",task.marker,fieldDigest(task.value)),buildPatternSegment("phase",phase.marker,fieldDigest(phase.value)),buildPatternSegment("gen",dispatchGeneration.marker,fieldDigest(dispatchGeneration.value)),buildPatternSegment("bg",background.marker,background.value===null?null:hashString2(background.value?"true":"false").slice(0,DIGEST_PREFIX_LENGTH)),digest3.slice(0,DIGEST_PREFIX_LENGTH)].join(":");return{version:1,tool:normalized.tool,role,swarm,taskId:task.value,taskMarker:task.marker,phase:phase.value,phaseMarker:phase.marker,parentSessionDigest:parentSession.value===null?null:hashString2(parentSession.value),parentSessionMarker:parentSession.marker,parentInvocation:parentInvocation.value,parentInvocationMarker:parentInvocation.marker,dispatchGeneration:dispatchGeneration.value,dispatchGenerationMarker:dispatchGeneration.marker,mode:mode.value,modeMarker:mode.marker,background:background.value,backgroundMarker:background.marker,scopeDigest:scope.digest,scopeMarker:scope.marker,additionalDigest,digest:digest3,pattern}}var MAX_STRING_INPUT=512,MAX_PUBLIC_FIELD_LENGTH=128,MAX_COLLECTION_ITEMS=64,MAX_OBJECT_KEYS=64,MAX_NORMALIZE_DEPTH=6,DIGEST_PREFIX_LENGTH=12,ROLE_KEYS,TASK_KEYS,PHASE_KEYS,PARENT_SESSION_KEYS,PARENT_INVOCATION_KEYS,DISPATCH_GENERATION_KEYS,MODE_KEYS,BACKGROUND_KEYS,SCOPE_KEYS;var init_action_identity=__esm(()=>{init_schema();ROLE_KEYS=["subagent_type","agent","role"],TASK_KEYS=["taskId","task_id","id"],PHASE_KEYS=["phase","phase_number"],PARENT_SESSION_KEYS=["parentSessionID","parentSessionId","parent_session_id","parent_session"],PARENT_INVOCATION_KEYS=["parentInvocationID","parentInvocationId","parent_invocation_id","parent_invocation","invocationID","invocationId","invocation_id"],DISPATCH_GENERATION_KEYS=["dispatchGeneration","dispatch_generation","generationId","generation_id","generation"],MODE_KEYS=["mode","execution_mode"],BACKGROUND_KEYS=["background","run_in_background","runInBackground"],SCOPE_KEYS=["working_directory","workingDirectory","scope","scope_id","scopeId","files","file","filePath","path","paths"]});import{createHash as createHash38}from"node:crypto";function hasOwn(source,key){return typeof source==="object"&&source!==null&&Object.hasOwn(source,key)}function readOwn(source,key){return hasOwn(source,key)?source[key]:void 0}function boundedString(value){if(typeof value!=="string")return;let trimmed=value.trim();if(trimmed.length===0)return;return trimmed.slice(0,MAX_STRUCTURED_STRING)}function boundedUtf8(value,maxBytes=MAX_DISPLAY_BYTES){let buffer=Buffer.from(value,"utf8");if(buffer.byteLength<=maxBytes)return value;return buffer.subarray(0,maxBytes).toString("utf8").replace(/\uFFFD+$/g,"")}function hashValue(value){return createHash38("sha256").update(value).digest("hex")}function redactUrl(match){try{let parsed=new URL(match),digestSource=parsed.origin+parsed.pathname+(parsed.search?"?<redacted>":"");return`<url:${hashValue(digestSource).slice(0,12)}>`}catch{return`<url:${hashValue(match).slice(0,12)}>`}}function tolerantKeyword(word){return word.split("").join(FILL)}function screamingKeyContainsSuffix(key){let stripped=key.replace(CONTROL_CHAR_RUN,"").replace(/\s+/g,"");return SCREAMING_SUFFIXES.some((suffix)=>stripped.includes(suffix))}function sanitizeFailureEvidenceDisplay(value){let redacted=value.slice(0,MAX_SANITIZE_INPUT_CHARS).replace(CSI_SEQUENCE," ").replace(/\bhttps?:\/\/[^\s'"<>]+/gi,(match)=>redactUrl(match)).replace(CREDENTIAL_KV_PATTERN,(_,key)=>`${key.replace(CONTROL_CHAR_RUN,"")}=<redacted>`).replace(SCREAMING_KV_CANDIDATE_PATTERN,(match,key)=>{if(!screamingKeyContainsSuffix(key))return match;return`${key.replace(CONTROL_CHAR_RUN,"").replace(/\s+/g,"")}=<redacted>`}).replace(CONTROL_CHAR_RUN," ").replace(BARE_SGR_PARAMETER_RUN," ");return boundedUtf8(redacted.trim())}function signalFrom(value){if(typeof value==="string")return value;if(value instanceof Error)return`${value.name}: ${value.message}`;if(typeof value==="number"||typeof value==="boolean")return String(value);if(typeof value!=="object"||value===null)return"";return["name","message","code","status","statusCode"].map((key)=>signalFrom(readOwn(value,key))).filter(Boolean).join(" ")}function actionIdentity(action){return action?createActionIdentity(action):null}function buildRecord(input){return{version:1,source:input.source,category:input.category,retryClass:input.retryClass,risk:input.risk,action:actionIdentity(input.action),evidence:{display:sanitizeFailureEvidenceDisplay(input.display),...input.statusCode!==void 0&&{statusCode:input.statusCode},...input.exitCode!==void 0&&{exitCode:input.exitCode},...input.code&&{code:input.code.slice(0,MAX_STRUCTURED_STRING)},...input.signal&&{signal:sanitizeFailureEvidenceDisplay(input.signal).slice(0,MAX_STRUCTURED_STRING)}},occurredAt:new Date().toISOString()}}function isShellTool(tool3){let normalized=tool3.trim().toLowerCase();return normalized==="bash"||normalized==="shell"}function isAbortLike(value){if(value instanceof Error&&value.name==="AbortError")return!0;let signal=signalFrom(value);return/\bAbortError\b/i.test(signal)||/\baborted\b/i.test(signal)}function isSimpleCommand(command){return command.length>0&&!/[;&|<>\r\n]/.test(command)}function isNeutralExitOne(command){let trimmed=command.trim();if(!isSimpleCommand(trimmed))return!1;let tokens=trimmed.match(/"[^"]*"|'[^']*'|\S+/g)?.map((token)=>token.replace(/^(["'])(.*)\1$/,"$2"))??[],executable=tokens[0]?.toLowerCase();if(executable==="rg"||executable==="rg.exe")return!0;if(executable!=="git"&&executable!=="git.exe")return!1;let subcommandIndex=1;while(tokens[subcommandIndex]==="-C"&&tokens[subcommandIndex+1])subcommandIndex+=2;return tokens[subcommandIndex]?.toLowerCase()==="diff"&&tokens.slice(subcommandIndex+1).includes("--quiet")}function readExitCode(metadata){let exit=hasOwn(metadata,"exit")?readOwn(metadata,"exit"):readOwn(metadata,"exitCode");return typeof exit==="number"&&Number.isFinite(exit)?exit:void 0}function readStatusCode(error93){let direct=readOwn(error93,"status");if(typeof direct==="number"&&Number.isFinite(direct))return direct;let alternate=readOwn(error93,"statusCode");if(typeof alternate==="number"&&Number.isFinite(alternate))return alternate;let signal=signalFrom(error93),parsed=extractStatusCode(signal);return parsed===null?void 0:parsed}function providerSignal(error93){return signalFrom(error93).trim()}function classifyProviderFailure(error93,action){let signal=providerSignal(error93),lowered=signal.toLowerCase(),statusCode=readStatusCode(error93),code=boundedString(readOwn(error93,"code"));if(isAbortLike(error93))return buildRecord({source:"provider",category:"provider.cancelled",retryClass:"do_not_retry",risk:"low",action,display:signal||"AbortError",code,statusCode});if(statusCode===401||statusCode===403||/\b(?:unauthorized|invalid api key|forbidden|authentication|credentials?)\b/i.test(signal))return buildRecord({source:"provider",category:"provider.authentication_configuration",retryClass:"operator_action",risk:"high",action,display:signal,code,statusCode});if(QUOTA_ERROR_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.quota_billing",retryClass:"retry_fallback",risk:"medium",action,display:signal,code,statusCode});if(statusCode===429||/\brate.?limit\b/i.test(signal))return buildRecord({source:"provider",category:"provider.rate_limit",retryClass:"retry_same",risk:"medium",action,display:signal,code,statusCode});if(statusCode!==void 0&&TRANSIENT_STATUS_CODES.has(statusCode)||TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.unavailable",retryClass:"retry_same",risk:"medium",action,display:signal,code,statusCode});if(/\b(?:context length|maximum context|too many tokens)\b/i.test(signal))return buildRecord({source:"provider",category:"provider.context_window",retryClass:"do_not_retry",risk:"low",action,display:signal,code,statusCode});if(/\b(?:content policy|content filter|safety system|policy violation|moderation)\b/i.test(signal))return buildRecord({source:"provider",category:"provider.content_policy",retryClass:"do_not_retry",risk:"medium",action,display:signal,code,statusCode});if(REQUEST_SHAPE_REJECTION_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.request_shape",retryClass:"do_not_retry",risk:"low",action,display:signal,code,statusCode});return buildRecord({source:"provider",category:lowered.length>0?"provider.unknown":"provider.cancelled",retryClass:"do_not_retry",risk:"medium",action,display:signal||"unknown provider error",code,statusCode})}function isRetryableProviderFailure(record3){return record3.source==="provider"&&(record3.retryClass==="retry_same"||record3.retryClass==="retry_fallback")}function classifyToolInvocationFailure(input){let shell=isShellTool(input.tool),explicitError=signalFrom(input.error),outputSignal=typeof input.output==="string"?input.output:"",signal=[explicitError,outputSignal].filter(Boolean).join(`
1090
+ `+textPart.text}}}function extractPhaseNumber(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function getCurrentTaskId2(sessionId){return swarmState.agentSessions.get(sessionId)?.currentTaskId??`${sessionId}:unknown`}var TRANSIENT_PROVIDER_RECOVERY_TAG="TRANSIENT PROVIDER RECOVERY",RUNAWAY_OUTPUT_ADVISORY_MARKER="Model is generating analysis without taking action",RUNAWAY_MEDIUM_MIN=200,MAX_TRACKED_COUNTED_ASSISTANT_MSGS=200,PRM_ADVISORY_FORWARD_PREFIX="[prm:",MAX_ADVISORY_BLOCK_BYTES=6000,ADVISORY_TRUNCATION_NOTE="[advisory block truncated to keep highest-value recent items]";var init_messages_transform=__esm(()=>{init_agents2();init_agent_model();init_constants();init_schema();init_manager();init_injection_budget();init_state2();init_telemetry();init_utils();init_provider_error_classification();init_extractors();init_model_limits();init_system_guidance_carrier();init_utils2();init_execution_episode();init_file_authority()});import{createHash as createHash37}from"node:crypto";function normalizeToolName2(tool3){return tool3.trim().toLowerCase()||"unknown-tool"}function hashString2(value){return createHash37("sha256").update(value).digest("hex")}function readRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:void 0}function fieldDigest(value){return value===null?null:hashString2(value).slice(0,DIGEST_PREFIX_LENGTH)}function readIdentityField(record3,keys){if(!record3)return{marker:"missing",value:null};for(let key of keys){if(!Object.hasOwn(record3,key))continue;let value=record3[key];if(value===void 0||value===null)return{marker:"empty",value:null};if(typeof value==="string"){let trimmed=value.trim();if(trimmed.length===0)return{marker:"empty",value:null};if(trimmed.length>MAX_PUBLIC_FIELD_LENGTH)return{marker:"value",value:`oversized:${hashString2(trimmed.slice(0,MAX_STRING_INPUT))}`};return{marker:"value",value:trimmed}}if(typeof value==="number"){if(!Number.isFinite(value))return{marker:"value",value:"invalid:number"};return{marker:"value",value:String(value)}}if(typeof value==="boolean")return{marker:"value",value:value?"true":"false"};return{marker:"value",value:`invalid:${Array.isArray(value)?"array":typeof value}`}}return{marker:"missing",value:null}}function readBackgroundField(record3){if(!record3)return{marker:"missing",value:null};for(let key of BACKGROUND_KEYS){if(!Object.hasOwn(record3,key))continue;let value=record3[key];if(value===void 0||value===null)return{marker:"empty",value:null};if(typeof value==="boolean")return{marker:"value",value};if(typeof value==="string"){let normalized=value.trim().toLowerCase();if(normalized.length===0)return{marker:"empty",value:null};if(normalized==="true")return{marker:"value",value:!0};if(normalized==="false")return{marker:"value",value:!1}}return{marker:"invalid",value:null}}return{marker:"missing",value:null}}function canonicalRole(raw){if(typeof raw!=="string"||raw.trim().length===0)return{role:"unknown-role",swarm:null};let trimmed=raw.trim(),role=stripKnownSwarmPrefix(trimmed).trim().toLowerCase()||"unknown-role";if(role===trimmed.toLowerCase())return{role,swarm:null};let suffix=`_${role}`;if(!trimmed.toLowerCase().endsWith(suffix))return{role,swarm:null};let swarm=trimmed.slice(0,trimmed.length-suffix.length).trim().toLowerCase();return{role,swarm:swarm.length>0?swarm:null}}function normalizeLeaf(value){if(value===void 0)return["undefined"];if(value===null)return["null"];if(typeof value==="string")return["string",hashString2(value.slice(0,MAX_STRING_INPUT))];if(typeof value==="number")return Number.isFinite(value)?["number",String(value)]:["number","non-finite"];if(typeof value==="boolean")return["boolean",value?"1":"0"];if(typeof value==="bigint")return["bigint",hashString2(String(value).slice(0,MAX_STRING_INPUT))];return["type",typeof value]}function canonicalizeAdditional(value,depth=0){if(value===void 0||value===null||typeof value==="string"||typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return normalizeLeaf(value);if(depth>=MAX_NORMALIZE_DEPTH)return["sentinel","depth-capped",hashString2(String(value).slice(0,MAX_STRING_INPUT))];if(Array.isArray(value)){let entries2=value.slice(0,MAX_COLLECTION_ITEMS).map((entry)=>canonicalizeAdditional(entry,depth+1));if(value.length>MAX_COLLECTION_ITEMS)entries2.push(["sentinel","array-capped",String(value.length)]);return["array",...entries2]}let record3=readRecord(value);if(!record3)return["type",typeof value,hashString2(String(value).slice(0,MAX_STRING_INPUT))];let keys=Object.keys(record3).sort(),entries=keys.slice(0,MAX_OBJECT_KEYS).map((key)=>[key,canonicalizeAdditional(record3[key],depth+1)]);if(keys.length>MAX_OBJECT_KEYS)entries.push(["__truncated_keys__",["sentinel","keys-capped",String(keys.length)]]);return["object",...entries]}function omitKnownKeys(record3,knownKeys){if(!record3)return null;let entries=Object.entries(record3).filter(([key])=>!knownKeys.has(key));return entries.length>0?Object.fromEntries(entries):null}function extractScopeIdentity(record3){if(!record3)return{marker:"missing",digest:null};let present=SCOPE_KEYS.filter((key)=>Object.hasOwn(record3,key));if(present.length===0)return{marker:"missing",digest:null};let subset=Object.fromEntries(present.map((key)=>[key,record3[key]]));if(present.every((key)=>{let value=record3[key];return value===void 0||value===null||typeof value==="string"&&value.trim().length===0}))return{marker:"empty",digest:null};return{marker:"value",digest:hashString2(JSON.stringify(canonicalizeAdditional(subset)))}}function buildPatternSegment(label,marker,digest3){return digest3?`${label}-${marker}-${digest3}`:`${label}-${marker}`}function createActionIdentity(input){let args2=readRecord(input.args),{role,swarm}=canonicalRole(readIdentityField(args2,ROLE_KEYS).value??args2?.subagent_type??args2?.agent??args2?.role),task=readIdentityField(args2,TASK_KEYS),phase=readIdentityField(args2,PHASE_KEYS),parentSession=readIdentityField(args2,PARENT_SESSION_KEYS),parentInvocation=readIdentityField(args2,PARENT_INVOCATION_KEYS),dispatchGeneration=readIdentityField(args2,DISPATCH_GENERATION_KEYS),mode=readIdentityField(args2,MODE_KEYS),background=readBackgroundField(args2),scope=extractScopeIdentity(args2),knownKeys=new Set([...ROLE_KEYS,...TASK_KEYS,...PHASE_KEYS,...PARENT_SESSION_KEYS,...PARENT_INVOCATION_KEYS,...DISPATCH_GENERATION_KEYS,...MODE_KEYS,...BACKGROUND_KEYS,...SCOPE_KEYS]),additionalDigest=hashString2(JSON.stringify(canonicalizeAdditional(omitKnownKeys(args2,knownKeys)))),normalized={tool:normalizeToolName2(input.tool),role,swarm,task,phase,parentSession:{marker:parentSession.marker,digest:parentSession.value===null?null:hashString2(parentSession.value)},parentInvocation,dispatchGeneration,mode,background,scope,additionalDigest},digest3=hashString2(JSON.stringify(normalized)),pattern=[normalized.tool,role,buildPatternSegment("task",task.marker,fieldDigest(task.value)),buildPatternSegment("phase",phase.marker,fieldDigest(phase.value)),buildPatternSegment("gen",dispatchGeneration.marker,fieldDigest(dispatchGeneration.value)),buildPatternSegment("bg",background.marker,background.value===null?null:hashString2(background.value?"true":"false").slice(0,DIGEST_PREFIX_LENGTH)),digest3.slice(0,DIGEST_PREFIX_LENGTH)].join(":");return{version:1,tool:normalized.tool,role,swarm,taskId:task.value,taskMarker:task.marker,phase:phase.value,phaseMarker:phase.marker,parentSessionDigest:parentSession.value===null?null:hashString2(parentSession.value),parentSessionMarker:parentSession.marker,parentInvocation:parentInvocation.value,parentInvocationMarker:parentInvocation.marker,dispatchGeneration:dispatchGeneration.value,dispatchGenerationMarker:dispatchGeneration.marker,mode:mode.value,modeMarker:mode.marker,background:background.value,backgroundMarker:background.marker,scopeDigest:scope.digest,scopeMarker:scope.marker,additionalDigest,digest:digest3,pattern}}var MAX_STRING_INPUT=512,MAX_PUBLIC_FIELD_LENGTH=128,MAX_COLLECTION_ITEMS=64,MAX_OBJECT_KEYS=64,MAX_NORMALIZE_DEPTH=6,DIGEST_PREFIX_LENGTH=12,ROLE_KEYS,TASK_KEYS,PHASE_KEYS,PARENT_SESSION_KEYS,PARENT_INVOCATION_KEYS,DISPATCH_GENERATION_KEYS,MODE_KEYS,BACKGROUND_KEYS,SCOPE_KEYS;var init_action_identity=__esm(()=>{init_schema();ROLE_KEYS=["subagent_type","agent","role"],TASK_KEYS=["taskId","task_id","id"],PHASE_KEYS=["phase","phase_number"],PARENT_SESSION_KEYS=["parentSessionID","parentSessionId","parent_session_id","parent_session"],PARENT_INVOCATION_KEYS=["parentInvocationID","parentInvocationId","parent_invocation_id","parent_invocation","invocationID","invocationId","invocation_id"],DISPATCH_GENERATION_KEYS=["dispatchGeneration","dispatch_generation","generationId","generation_id","generation"],MODE_KEYS=["mode","execution_mode"],BACKGROUND_KEYS=["background","run_in_background","runInBackground"],SCOPE_KEYS=["working_directory","workingDirectory","scope","scope_id","scopeId","files","file","filePath","path","paths"]});import{createHash as createHash38}from"node:crypto";function hasOwn(source,key){return typeof source==="object"&&source!==null&&Object.hasOwn(source,key)}function readOwn(source,key){return hasOwn(source,key)?source[key]:void 0}function boundedString(value){if(typeof value!=="string")return;let trimmed=value.trim();if(trimmed.length===0)return;return trimmed.slice(0,MAX_STRUCTURED_STRING)}function boundedUtf8(value,maxBytes=MAX_DISPLAY_BYTES){let buffer=Buffer.from(value,"utf8");if(buffer.byteLength<=maxBytes)return value;return buffer.subarray(0,maxBytes).toString("utf8").replace(/\uFFFD+$/g,"")}function hashValue(value){return createHash38("sha256").update(value).digest("hex")}function redactUrl(match){try{let parsed=new URL(match),digestSource=parsed.origin+parsed.pathname+(parsed.search?"?<redacted>":"");return`<url:${hashValue(digestSource).slice(0,12)}>`}catch{return`<url:${hashValue(match).slice(0,12)}>`}}function tolerantKeyword(word){return word.split("").join(FILL)}function screamingKeyContainsSuffix(key){let stripped=key.replace(CONTROL_CHAR_RUN,"").replace(/\s+/g,"");return SCREAMING_SUFFIXES.some((suffix)=>stripped.includes(suffix))}function sanitizeFailureEvidenceDisplay(value){let redacted=value.slice(0,MAX_SANITIZE_INPUT_CHARS).replace(CSI_SEQUENCE," ").replace(/\bhttps?:\/\/[^\s'"<>]+/gi,(match)=>redactUrl(match)).replace(CREDENTIAL_KV_PATTERN,(_,key)=>`${key.replace(CONTROL_CHAR_RUN,"")}=<redacted>`).replace(SCREAMING_KV_CANDIDATE_PATTERN,(match,key)=>{if(!screamingKeyContainsSuffix(key))return match;return`${key.replace(CONTROL_CHAR_RUN,"").replace(/\s+/g,"")}=<redacted>`}).replace(CONTROL_CHAR_RUN," ").replace(BARE_SGR_PARAMETER_RUN," ");return boundedUtf8(redacted.trim())}function signalFrom(value){if(typeof value==="string")return value;if(value instanceof Error)return`${value.name}: ${value.message}`;if(typeof value==="number"||typeof value==="boolean")return String(value);if(typeof value!=="object"||value===null)return"";return["name","message","code","status","statusCode"].map((key)=>signalFrom(readOwn(value,key))).filter(Boolean).join(" ")}function actionIdentity(action){return action?createActionIdentity(action):null}function buildRecord(input){return{version:1,source:input.source,category:input.category,retryClass:input.retryClass,risk:input.risk,action:actionIdentity(input.action),evidence:{display:sanitizeFailureEvidenceDisplay(input.display),...input.statusCode!==void 0&&{statusCode:input.statusCode},...input.exitCode!==void 0&&{exitCode:input.exitCode},...input.code&&{code:input.code.slice(0,MAX_STRUCTURED_STRING)},...input.signal&&{signal:sanitizeFailureEvidenceDisplay(input.signal).slice(0,MAX_STRUCTURED_STRING)}},occurredAt:new Date().toISOString()}}function isShellTool(tool3){let normalized=tool3.trim().toLowerCase();return normalized==="bash"||normalized==="shell"}function isAbortLike(value){if(value instanceof Error&&value.name==="AbortError")return!0;let signal=signalFrom(value);return/\bAbortError\b/i.test(signal)||/\baborted\b/i.test(signal)}function isSimpleCommand(command){return command.length>0&&!/[;&|<>\r\n]/.test(command)}function isNeutralExitOne(command){let trimmed=command.trim();if(!isSimpleCommand(trimmed))return!1;let tokens=trimmed.match(/"[^"]*"|'[^']*'|\S+/g)?.map((token)=>token.replace(/^(["'])(.*)\1$/,"$2"))??[],executable=tokens[0]?.toLowerCase();if(executable==="rg"||executable==="rg.exe")return!0;if(executable!=="git"&&executable!=="git.exe")return!1;let subcommandIndex=1;while(tokens[subcommandIndex]==="-C"&&tokens[subcommandIndex+1])subcommandIndex+=2;return tokens[subcommandIndex]?.toLowerCase()==="diff"&&tokens.slice(subcommandIndex+1).includes("--quiet")}function readExitCode(metadata){let exit=hasOwn(metadata,"exit")?readOwn(metadata,"exit"):readOwn(metadata,"exitCode");return typeof exit==="number"&&Number.isFinite(exit)?exit:void 0}function readStatusCode(error93){let direct=readOwn(error93,"status");if(typeof direct==="number"&&Number.isFinite(direct))return direct;let alternate=readOwn(error93,"statusCode");if(typeof alternate==="number"&&Number.isFinite(alternate))return alternate;let signal=signalFrom(error93),parsed=extractStatusCode(signal);return parsed===null?void 0:parsed}function providerSignal(error93){return signalFrom(error93).trim()}function classifyProviderFailure(error93,action){let signal=providerSignal(error93),lowered=signal.toLowerCase(),statusCode=readStatusCode(error93),code=boundedString(readOwn(error93,"code"));if(isAbortLike(error93))return buildRecord({source:"provider",category:"provider.cancelled",retryClass:"do_not_retry",risk:"low",action,display:signal||"AbortError",code,statusCode});if(statusCode===401||statusCode===403||/\b(?:unauthorized|invalid api key|forbidden|authentication|credentials?)\b/i.test(signal))return buildRecord({source:"provider",category:"provider.authentication_configuration",retryClass:"operator_action",risk:"high",action,display:signal,code,statusCode});if(QUOTA_ERROR_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.quota_billing",retryClass:"retry_fallback",risk:"medium",action,display:signal,code,statusCode});if(statusCode===429||/\brate.?limit\b/i.test(signal))return buildRecord({source:"provider",category:"provider.rate_limit",retryClass:"retry_same",risk:"medium",action,display:signal,code,statusCode});if(MODEL_UNAVAILABLE_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.unavailable",retryClass:"retry_fallback",risk:"medium",action,display:signal,code,statusCode});if(statusCode!==void 0&&TRANSIENT_STATUS_CODES.has(statusCode)||TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.unavailable",retryClass:"retry_same",risk:"medium",action,display:signal,code,statusCode});if(/\b(?:context length|maximum context|too many tokens)\b/i.test(signal))return buildRecord({source:"provider",category:"provider.context_window",retryClass:"do_not_retry",risk:"low",action,display:signal,code,statusCode});if(/\b(?:content policy|content filter|safety system|policy violation|moderation)\b/i.test(signal))return buildRecord({source:"provider",category:"provider.content_policy",retryClass:"do_not_retry",risk:"medium",action,display:signal,code,statusCode});if(REQUEST_SHAPE_REJECTION_PATTERN.test(signal))return buildRecord({source:"provider",category:"provider.request_shape",retryClass:"do_not_retry",risk:"low",action,display:signal,code,statusCode});return buildRecord({source:"provider",category:lowered.length>0?"provider.unknown":"provider.cancelled",retryClass:"do_not_retry",risk:"medium",action,display:signal||"unknown provider error",code,statusCode})}function isRetryableProviderFailure(record3){return record3.source==="provider"&&(record3.retryClass==="retry_same"||record3.retryClass==="retry_fallback")}function classifyToolInvocationFailure(input){let shell=isShellTool(input.tool),explicitError=signalFrom(input.error),outputSignal=typeof input.output==="string"?input.output:"",signal=[explicitError,outputSignal].filter(Boolean).join(`
1091
1091
  `).trim(),exitCode=readExitCode(input.metadata),metadataCode=boundedString(readOwn(input.metadata,"code")),originalCommand=input.correlation?.originalCommand??"";if(!signal&&exitCode===void 0)return null;if(shell&&(metadataCode==="SANDBOX_WRAPPER_FAILURE"||input.correlation?.sandboxWrapped===!0&&/\[sandbox\]\s+BLOCKED:/i.test(signal)))return buildRecord({source:"shell",category:"shell.sandbox_wrapper",retryClass:"operator_action",risk:"high",action:{tool:input.tool,args:input.args},display:"sandbox wrapper failed closed",exitCode,code:metadataCode});if(shell&&(metadataCode==="ParserError"||/\b(?:MissingEndCurlyBrace|ParserError|ParseError|IncompleteParseException)\b/i.test(signal)))return buildRecord({source:"shell",category:input.correlation?.sandboxWrapped?"shell.sandbox_wrapper":"shell.parser",retryClass:input.correlation?.sandboxWrapped?"operator_action":"repair_then_retry",risk:"high",action:{tool:input.tool,args:input.args},display:"shell parser rejected the command",exitCode,code:metadataCode});let structuredCommandUnavailable=/\bCommandNotFoundException\b/i.test(explicitError)||metadataCode==="ENOENT"||/\b(?:spawn|execFile)\s+\S+\s+ENOENT\b/i.test(explicitError)||exitCode===127&&/(?:^|\n)(?:\/bin\/)?(?:ba|da|z|k)?sh(?:\.exe)?:\s+(?:(?:line\s+)?\d+:\s+)?[^:\r\n]+:\s+not found\b/im.test(outputSignal)||exitCode===127&&/(?:^|\n)[^:\r\n]+:\s+command not found\b/im.test(outputSignal);if(shell&&structuredCommandUnavailable)return buildRecord({source:"shell",category:"shell.command_unavailable",retryClass:"repair_then_retry",risk:"medium",action:{tool:input.tool,args:input.args},display:`command unavailable${exitCode!==void 0?` (exit ${exitCode})`:""}`,exitCode,code:metadataCode??(/\bENOENT\b/.test(signal)?"ENOENT":void 0)});if(shell&&exitCode===1&&isNeutralExitOne(originalCommand))return null;if(shell&&exitCode!==void 0&&exitCode!==0)return buildRecord({source:"shell",category:"shell.exit",retryClass:"do_not_retry",risk:"medium",action:{tool:input.tool,args:input.args},display:`shell exited with code ${exitCode}`,exitCode,code:metadataCode});if(!shell&&(explicitError.length>0||exitCode!==void 0))return buildRecord({source:"validation",category:"validation.agent_result",retryClass:"repair_then_retry",risk:"medium",action:{tool:input.tool,args:input.args},display:signal||"tool failure",exitCode,code:metadataCode});return null}var MAX_DISPLAY_BYTES=512,MAX_STRUCTURED_STRING=128,FILL_MAX_RUN=8,FILL,CONTROL_CHAR_RUN,MAX_SANITIZE_INPUT_CHARS,SCREAMING_SUFFIXES,TOLERANT_BEARER_PREFIX,TOLERANT_AUTH_SCHEME_PREFIX,CREDENTIAL_MORPHEMES,CREDENTIAL_KEY_SUFFIX_CHARS="\\p{L}\\p{N}_\\-\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\p{Default_Ignorable_Code_Point}",CREDENTIAL_KEY_IDENTIFIER,CREDENTIAL_KV_PATTERN,CSI_SEQUENCE,BARE_SGR_PARAMETER_RUN,SCREAMING_KEY_HORIZONTAL_FILL_CHARS="\\x00-\\x09\\x0e-\\x1f\\x7f-\\x9f\\p{Zs}\\p{Cf}\\p{Default_Ignorable_Code_Point}",SCREAMING_KV_CANDIDATE_PATTERN;var init_invocation_failure=__esm(()=>{init_provider_error_classification();init_action_identity();FILL=`[\\s"'\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}]{0,${FILL_MAX_RUN}}`,CONTROL_CHAR_RUN=/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]+/gu,MAX_SANITIZE_INPUT_CHARS=MAX_DISPLAY_BYTES*8;SCREAMING_SUFFIXES=["TOKEN","KEY","SECRET","PASSWORD","AUTH"],TOLERANT_BEARER_PREFIX=tolerantKeyword("Bearer"),TOLERANT_AUTH_SCHEME_PREFIX=`(?:${["Bearer","Basic","Digest","Negotiate","HOBA","Mutual","ApiKey"].map(tolerantKeyword).join("|")})`,CREDENTIAL_MORPHEMES=["token","secret","password","authorization","credential","bearer","key"].map(tolerantKeyword),CREDENTIAL_KEY_IDENTIFIER=`[\\p{L}\\p{N}_-]{0,24}(?:${CREDENTIAL_MORPHEMES.join("|")})[${CREDENTIAL_KEY_SUFFIX_CHARS}]{0,24}`,CREDENTIAL_KV_PATTERN=new RegExp(`(${CREDENTIAL_KEY_IDENTIFIER})${FILL}[:=]${FILL}(?:${TOLERANT_AUTH_SCHEME_PREFIX}${FILL})?(?:${TOLERANT_BEARER_PREFIX}${FILL})?[^\\s,;]+`,"giu"),CSI_SEQUENCE=/\x1b\[[0-9;:;<=>?]{0,32}[ !-/]{0,4}[@-~]/gu,BARE_SGR_PARAMETER_RUN=/\[[0-9;:]{17,64}m/gu,SCREAMING_KV_CANDIDATE_PATTERN=new RegExp(`\\b([A-Z0-9_${SCREAMING_KEY_HORIZONTAL_FILL_CHARS}]{1,80})${FILL}=${FILL}([^\\s]+)`,"gu")});function hasOwn2(source,key){return typeof source==="object"&&source!==null&&Object.hasOwn(source,key)}function readOwn2(source,key){if(!hasOwn2(source,key))return;try{return source[key]}catch{return}}function signalFrom2(value){if(typeof value==="string")return value;if(value instanceof Error)return`${value.name}: ${value.message}`;if(typeof value==="number"||typeof value==="boolean")return String(value);if(typeof value!=="object"||value===null)return"";let source=value;return["name","message","code","status","statusCode"].map((key)=>signalFrom2(readOwn2(source,key))).filter(Boolean).join(" ")}function getOriginalCommand(input,correlation){if(correlation)return correlation.originalCommand;return typeof input.args?.command==="string"?input.args.command:""}function isShellTool2(tool3){let normalized=tool3.toLowerCase();return normalized==="bash"||normalized==="shell"}function isSimpleCommand2(command){return command.length>0&&!/[;&|<>\r\n]/.test(command)}function isNeutralExitOne2(command){let trimmed=command.trim();if(!isSimpleCommand2(trimmed))return!1;let tokens=trimmed.match(/"[^"]*"|'[^']*'|\S+/g)?.map((token)=>token.replace(/^(["'])(.*)\1$/,"$2"))??[],executable=tokens[0]?.toLowerCase();if(executable==="rg"||executable==="rg.exe")return!0;if(executable!=="git"&&executable!=="git.exe")return!1;let subcommandIndex=1;while(tokens[subcommandIndex]==="-C"&&tokens[subcommandIndex+1])subcommandIndex+=2;return tokens[subcommandIndex]?.toLowerCase()==="diff"&&tokens.slice(subcommandIndex+1).includes("--quiet")}function mapFailureRecordToFatalCategory(record3){switch(record3?.category){case"shell.sandbox_wrapper":return"sandbox_wrapper_failure";case"shell.parser":return"shell_parse_error";case"shell.command_unavailable":return"command_not_found";default:return null}}function classifyToolOutcome(input,output,correlation){let explicitError=signalFrom2(readOwn2(output,"error")),explicitFailure=explicitError.length>0||readOwn2(output,"success")===!1||output.output===null||output.output===void 0,shell=isShellTool2(input.tool),metadata=output.metadata,exitPresent=shell&&(hasOwn2(metadata,"exit")||hasOwn2(metadata,"exitCode")),exit=hasOwn2(metadata,"exit")?readOwn2(metadata,"exit"):readOwn2(metadata,"exitCode"),originalCommand=getOriginalCommand(input,correlation),correlatedWrappedCommand=correlation!==void 0&&typeof input.args?.command==="string"&&input.args.command!==correlation.originalCommand,neutralExitOne=exit===1&&isNeutralExitOne2(originalCommand),outputSignal=typeof output.output==="string"?output.output:"",signal=[explicitError,outputSignal].filter(Boolean).join(`
1092
1092
  `),rawShellFailure=exitPresent&&(exit===null||typeof exit!=="number"||!Number.isFinite(exit)||exit!==0),record3=explicitFailure||rawShellFailure?classifyToolInvocationFailure({tool:input.tool,args:input.args,output:outputSignal,error:explicitError,metadata,correlation:correlation?{sandboxWrapped:correlation.sandboxWrapped===!0||correlatedWrappedCommand,originalCommand}:{originalCommand}}):null;if((explicitFailure||rawShellFailure)&&shell){let category=mapFailureRecordToFatalCategory(record3);if(category)return{kind:"fatal",category,signal}}if(explicitFailure||rawShellFailure&&!neutralExitOne)return{kind:"failure",signal:record3?.evidence.display??signal};if(neutralExitOne)return{kind:"neutral",signal};if(shell&&exitPresent&&exit===0)return{kind:"success",signal};if(!shell)return{kind:"success",signal};return{kind:"unknown",signal}}function currentOwner(sessionID){let session=getAgentSession(sessionID);if(!session)return null;return{agent:stripKnownSwarmPrefix(session.agentName),invocationId:session.activeInvocationId??0}}function parseSwarmCommandVerb(args2){let record3=typeof args2==="object"&&args2!==null&&!Array.isArray(args2)?args2:void 0;return(typeof record3?.command==="string"?record3.command:typeof record3?.subcommand==="string"?record3.subcommand:"").trim().toLowerCase().split(/\s+/).filter(Boolean).slice(0,3)}function isAllowedRecoverySwarmCommand(args2){let parts=parseSwarmCommandVerb(args2);if(parts.length===0)return!1;if(parts[0]==="diagnose"||parts[0]==="diagnosis")return!0;if(parts[0]==="handoff")return!0;if(parts[0]==="guardrail"&&parts[1]==="reset")return!0;if(parts[0]!=="full-auto"||parts.length<2)return!1;return new Set(["status","retry-oversight","abort","resume","on","off","exit"]).has(parts[1])}function isRecoveryAllowedTool(tool3,args2){let normalized=normalizeToolNameLowerCase(tool3);if(RECOVERY_READ_ONLY_TOOLS.has(normalized))return!0;if(normalized==="swarm"||normalized==="swarm_command"||normalized==="swarm-command")return isAllowedRecoverySwarmCommand(args2);return!1}function resolveActionIdentity(sessionID,context){let owner=currentOwner(sessionID);if(!owner)return null;let action=createActionIdentity({tool:context?.tool??"unknown-tool",args:context?.args});return{ownerAgent:owner.agent,ownerInvocationId:owner.invocationId,actionDigest:action.digest,actionPattern:action.pattern}}function freshCircuit(ownerAgent,ownerInvocationId){return{ownerAgent,ownerInvocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function ensureCircuit(sessionID){let owner=currentOwner(sessionID);if(!owner)return null;let session=getAgentSession(sessionID);if(!session)return null;let circuit=session.nonTransientCircuit;if(!circuit||circuit.ownerAgent!==owner.agent||circuit.ownerInvocationId!==owner.invocationId)session.nonTransientCircuit=freshCircuit(owner.agent,owner.invocationId);return session.nonTransientCircuit??null}function ensureCircuitSession(sessionID){if(getAgentSession(sessionID))return;let agent=swarmState.activeAgent.get(sessionID)??"architect";ensureAgentSession(sessionID,agent)}function recordNonTransientFailure(sessionID,category,signal,context){let safeSignal=sanitizeFailureEvidenceDisplay(signal);ensureCircuitSession(sessionID);let actionIdentity2=resolveActionIdentity(sessionID,context),circuit=ensureCircuit(sessionID),session=getAgentSession(sessionID);if(!circuit||!session||!actionIdentity2)return null;let threshold=IMMEDIATE_HARD_STOP_CATEGORIES.has(category)?1:SAME_CATEGORY_HARD_STOP_THRESHOLD;if(context?.armAttempt===!0)armActionCircuitAttempt(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest);let{entry,enteredHardStop,ignoredLateEvent}=noteActionCircuitFailure({sessionID,invocationID:actionIdentity2.ownerInvocationId,actionDigest:actionIdentity2.actionDigest,circuitKind:category,signal:safeSignal,hardStopThreshold:threshold});if(!entry||ignoredLateEvent)return circuit;if(circuit.category=category,circuit.sameCategoryCount=entry.count,circuit.hardStop=entry.hardStop,circuit.lastSignal=safeSignal.slice(0,1000),enteredHardStop)telemetry.loopDetected(sessionID,circuit.ownerAgent,`nontransient:${category}:${actionIdentity2.actionPattern}`),pushAdvisory(session,"NON-TRANSIENT STOP ("+category+", "+circuit.sameCategoryCount+"/"+threshold+"): STOP. Do not retry this failure with another command or tool. Report the blocker and wait for corrected input, environment, or scope.");return circuit}function clearNonTransientCircuit(sessionID,context){let circuit=ensureCircuit(sessionID),actionIdentity2=resolveActionIdentity(sessionID,context);if(!circuit||!actionIdentity2)return;clearActionCircuit(sessionID,actionIdentity2.ownerInvocationId,actionIdentity2.actionDigest,{reason:"success"}),circuit.category=null,circuit.sameCategoryCount=0,circuit.hardStop=!1,circuit.lastSignal=null}function nonTransientRemediation(category){switch(category){case"sandbox_wrapper_failure":return'This is a SANDBOX PROVISIONING failure — the command wrapper itself failed to sandbox the command (see "Last signal" for the wrapper error and mechanism). It is NOT the sub-agent refusing to act. '+"Run /swarm diagnose to check the sandbox mechanism and its availability. "+'A UI "session reset" alone may NOT clear this: the circuit is keyed to the current agent invocation, so only a fresh agent invocation (re-delegation) or a full plugin restart resets it — clearing the .opencode cache does not, because the circuit is in-memory. '+"When the sandbox mechanism is genuinely unavailable the shell runs UNSANDBOXED instead of hard-stopping, so a repeatable hard-stop here means the wrapper is actively failing — repair the sandbox environment before re-dispatching.";case"command_not_found":return'A command/executable was not found (see "Last signal"). Ensure the binary is installed and on PATH, then start a fresh invocation.';case"shell_parse_error":return'The shell could not parse the command (see "Last signal"). Fix the command syntax (quoting/escaping), then start a fresh invocation.';default:return"Start a verified new invocation or reset the session before continuing."}}function nonTransientHardStopMessage(circuit){let category=circuit.category??"fatal",signal=circuit.lastSignal??"(no signal captured)";return"NON-TRANSIENT CIRCUIT BREAKER: "+circuit.sameCategoryCount+" consecutive "+category+` failure(s). STOP tool calls and report the blocker.
1093
1093
  Last signal: `+signal+`
@@ -1236,10 +1236,10 @@ Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:""
1236
1236
  `+diffInfo.diff+`
1237
1237
  [End spec diff]`}else message+=`
1238
1238
 
1239
- (no recorded snapshot to diff against)`;throw Error(message)}}function isPlainObject4(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function readSignalField(source,key2){try{return source[key2]}catch{return}}function pushSignalValue(parts,value){if(typeof value==="string"){parts.push(value);return}if(typeof value==="number"||typeof value==="boolean")parts.push(String(value))}function appendSelectedFields(parts,source,keys){for(let key2 of keys)pushSignalValue(parts,readSignalField(source,key2))}function appendNestedErrorSignal(parts,value){if(typeof value==="string"){parts.push(value);return}if(value instanceof Error){parts.push(value.name,value.message),appendSelectedFields(parts,value,["code","status","statusCode"]);return}if(!isPlainObject4(value))return;appendSelectedFields(parts,value,["code","status","statusCode","message","error_type"])}function extractErrorSignal(errorContent){if(typeof errorContent==="string")return errorContent;if(errorContent==null)return"";let parts=[];try{if(errorContent instanceof Error)return parts.push(errorContent.name,errorContent.message),appendSelectedFields(parts,errorContent,["code","status","statusCode"]),parts.join(" ");if(!isPlainObject4(errorContent))return"";appendSelectedFields(parts,errorContent,["code","status","statusCode","message","error_type"]),appendNestedErrorSignal(parts,readSignalField(errorContent,"error"));let metadata=readSignalField(errorContent,"metadata");if(isPlainObject4(metadata))appendSelectedFields(parts,metadata,["code","status","statusCode","error_type"]);appendNestedErrorSignal(parts,readSignalField(errorContent,"cause"))}catch{return parts.join(" ")}return parts.join(" ")}function touchNoOpSession(sessionID,count){toolCallsSinceLastWrite.delete(sessionID),toolCallsSinceLastWrite.set(sessionID,count),evictNoOpStateIfOverBound()}function evictNoOpStateIfOverBound(){while(toolCallsSinceLastWrite.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=toolCallsSinceLastWrite.keys().next().value;if(stalestKey===void 0)break;toolCallsSinceLastWrite.delete(stalestKey),noOpWarningIssued.delete(stalestKey),noOpStrongWarningIssued.delete(stalestKey)}while(noOpWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpWarningIssued.delete(stalestKey)}while(noOpStrongWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpStrongWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpStrongWarningIssued.delete(stalestKey)}}function extractPhaseNumber2(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function isWriteTool2(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isGateTool(toolName){let normalized=normalizeToolName(toolName);return["diff","syntax_check","placeholder_scan","imports","lint","build_check","pre_check_batch","secretscan","sast_scan","quality_budget"].includes(normalized)}function isAgentDelegation(toolName,args2){if(!isTaskToolId(toolName))return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function createGuardrailsHooks(directory,directoryOrConfig,config3,authorityConfig,worktreeBaseDirOverrides,resolveAgentModel){let guardrailsConfig;if(directory&&typeof directory==="object"&&"enabled"in directory)warn("[guardrails] Legacy call without directory, falling back to process.cwd()"),guardrailsConfig=directory;else if(directoryOrConfig&&typeof directoryOrConfig==="object"&&"enabled"in directoryOrConfig)guardrailsConfig=directoryOrConfig;else guardrailsConfig=config3;let effectiveDirectory=(()=>{if(typeof directory==="string")return directory;let cwd=process.cwd();return warn(`[guardrails] effectiveDirectory resolved to process.cwd() "${cwd}" — `+"pass an explicit directory string to createGuardrailsHooks to avoid .swarm artifacts in wrong locations"),cwd})(),enforcementEnabled=guardrailsConfig?.enabled!==!1,precomputedAuthorityRules=buildEffectiveRules(authorityConfig),verifierPaths=authorityConfig?.verifier_config_paths;if(verifierPaths&&verifierPaths.length>0){let existingArchitect=precomputedAuthorityRules.architect??{};precomputedAuthorityRules.architect={...existingArchitect,blockedGlobs:[...existingArchitect.blockedGlobs??[],...verifierPaths]}}let universalDenyPrefixes=authorityConfig?.universal_deny_prefixes??[];if(guardrailsConfig===void 0||guardrailsConfig===null)throw TypeError("createGuardrailsHooks: guardrailsConfig is required — pass the resolved GuardrailsConfig object");let cfg=guardrailsConfig,requiredQaGates=cfg.qa_gates?.required_tools??["diff","syntax_check","placeholder_scan","lint","pre_check_batch"],requireReviewerAndTestEngineer=cfg.qa_gates?.require_reviewer_test_engineer??!0,interpreterAllowedAgents=cfg.interpreter_allowed_agents,shellAuditEnabled=cfg.shell_audit_log??!0,consecutiveNoToolTurns=new Map,lastCountedAssistantMsgId=new Map,pendingReviewerScopeWrites=new Map,pendingGateTasksBySession=new Map,takePendingGateTask=(sessionID,callID)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID),pending=sessionTasks?.get(callID);if(sessionTasks){if(sessionTasks.delete(callID),sessionTasks.size===0)pendingGateTasksBySession.delete(sessionID)}return pending},rememberPendingGateTask=(sessionID,callID,taskId,generation)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID);if(!sessionTasks){if(pendingGateTasksBySession.size>=MAX_PENDING_GATE_RECEIPT_SESSIONS)throw Error("GATE_RECEIPT_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionTasks=new Map,pendingGateTasksBySession.set(sessionID,sessionTasks)}if(!sessionTasks.has(callID)&&sessionTasks.size>=MAX_PENDING_GATE_RECEIPTS_PER_SESSION)throw Error("GATE_RECEIPT_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionTasks.set(callID,{sessionID,taskId,generation})},pendingGateRoutesBySession=new Map,takePendingGateRoute=(sessionID,callID)=>{let sessionRoutes=pendingGateRoutesBySession.get(sessionID),route=sessionRoutes?.get(callID);if(sessionRoutes){if(sessionRoutes.delete(callID),sessionRoutes.size===0)pendingGateRoutesBySession.delete(sessionID)}return route},rememberPendingGateRoute=(sessionID,callID,route)=>{let sessionRoutes=pendingGateRoutesBySession.get(sessionID);if(!sessionRoutes){if(pendingGateRoutesBySession.size>=MAX_PENDING_GATE_ROUTE_SESSIONS)throw Error("GATE_ROUTE_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionRoutes=new Map,pendingGateRoutesBySession.set(sessionID,sessionRoutes)}if(!sessionRoutes.has(callID)&&sessionRoutes.size>=MAX_PENDING_GATE_ROUTES_PER_SESSION)throw Error("GATE_ROUTE_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionRoutes.set(callID,route)},scopeLeaseRenewal=createScopeLeaseRenewalTracker(),rememberReviewerScopeWrite=(input)=>{if(!pendingReviewerScopeWrites.has(input.callID)&&pendingReviewerScopeWrites.size>=256){let oldest=pendingReviewerScopeWrites.keys().next().value;if(oldest!==void 0)pendingReviewerScopeWrites.delete(oldest)}let pending=pendingReviewerScopeWrites.get(input.callID)??[],candidate={parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,file:input.file};if(!pending.some((entry)=>entry.parentSessionID===candidate.parentSessionID&&entry.taskId===candidate.taskId&&entry.coderCallID===candidate.coderCallID&&entry.file===candidate.file)&&pending.length<256)pending.push(candidate);pendingReviewerScopeWrites.set(input.callID,pending)},executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},baseToolBefore=createToolBeforeHandler({effectiveDirectory,cfg,enforcePolicy:enforcementEnabled,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,rememberReviewerScopeWrite,rememberScopeLeaseCandidate:scopeLeaseRenewal.remember,getSandboxExecutor:_internals81.getSandboxExecutor,assessSandboxEnforcement:_internals81.assessSandboxEnforcement}),toolBefore=async(input,output)=>{if(isGateTool(input.tool)){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId,unattributableRoute="no_task_correlation";if(!taskId){let callerFiles=extractGateCallFiles(output.args),fallback=await _internals81.resolveDurableGateTaskId(effectiveDirectory,callerFiles);if(fallback){if("taskId"in fallback)taskId=fallback.taskId;else if("ambiguous"in fallback&&fallback.ambiguous.length>0){unattributableRoute="attribution_ambiguous";let shown=fallback.ambiguous.slice(0,10),more=fallback.ambiguous.length-shown.length;emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00${fallback.ambiguous.join(",")}`,`STAGE A ATTRIBUTION AMBIGUOUS: ${fallback.ambiguous.length} tasks are settled at coder_delegated (${shown.join(", ")}${more>0?`, +${more} more`:""}) but this session has no task correlation after reset-session. Stage A evidence cannot be attributed safely. Run /swarm recover to repair Stage A attribution, then re-run the gate.`)}else if("unbound"in fallback)unattributableRoute="attribution_ambiguous",emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00unbound\x00${fallback.unbound}`,fallback.reason==="truncated"?`STAGE A ATTRIBUTION UNVERIFIABLE: task ${fallback.unbound} looks like the sole durable candidate at coder_delegated, but the settlement scan is truncated (more than 200 historical settlements) so a second candidate cannot be ruled out. Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`:`STAGE A ATTRIBUTION UNBOUND: task ${fallback.unbound} is the sole durable candidate at coder_delegated, but this gate call's scanned files do not match its declared changes (or no file scope was provided). Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`)}}if(taskId){let workflow=isStrictTaskId(taskId)?getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId)):null;rememberPendingGateTask(input.sessionID,input.callID,taskId,workflow?.generation??0)}else try{rememberPendingGateRoute(input.sessionID,input.callID,unattributableRoute)}catch(routeError){warn("Stage A route classification dropped at capacity",{sessionID:input.sessionID,error:routeError instanceof Error?routeError.message.slice(0,80):String(routeError)})}}try{await baseToolBefore(input,output)}catch(error93){throw takePendingGateTask(input.sessionID,input.callID),error93}},messagesTransform=enforcementEnabled?createMessagesTransformHandler({effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId,resolveAgentModel}):async()=>{};return{toolBefore,toolAfter:async(input,output)=>{let pendingGateTask=takePendingGateTask(input.sessionID,input.callID)??(_internals81.allowUncorrelatedGateReceipts?(()=>{let testSession=swarmState.agentSessions.get(input.sessionID);return testSession?{sessionID:input.sessionID,taskId:testSession.currentTaskId??`${input.sessionID}:unknown`,generation:testSession.currentTaskId&&isStrictTaskId(testSession.currentTaskId)?testSession.taskWorkflowCache?.get(testSession.currentTaskId)?.generation??0:0}:void 0})():void 0),pendingReviewerScopeWrite=pendingReviewerScopeWrites.get(input.callID);pendingReviewerScopeWrites.delete(input.callID);let correlatedExecution=takeToolExecution(input.sessionID,input.callID);if(correlatedExecution&&!isToolExecutionCurrent(input.sessionID,correlatedExecution)){await scopeLeaseRenewal.consume({...input,output:null});return}let malformedOutput=!output||typeof output!=="object",safeOutput=malformedOutput?{title:"",output:"",metadata:null}:output;await scopeLeaseRenewal.consume({...input,output:malformedOutput?null:safeOutput});let emitStageARoute=(route,taskId)=>{recordStageAGateRoute(effectiveDirectory,{route,sessionID:input.sessionID,callID:input.callID,taskId,guardrailsEnabled:enforcementEnabled,...pendingGateTask?{generation:pendingGateTask.generation}:{}})},stageADuplicateOf=async(taskId,appliedOutcome)=>{try{let snapshot=getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId));return snapshot.authoritative===!0&&snapshot.lastTransitionId===`pre-check:${input.callID}`&&snapshot.lastOutcome===appliedOutcome}catch{return!1}};if(normalizeToolName(input.tool)==="pre_check_batch"&&!pendingGateTask)try{let verdict=decodePreCheckResult(safeOutput.output),sessionTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null,appliedOutcome=verdict.kind==="pass"?"stage_a_passed":verdict.kind==="fail"?"stage_a_failed":null;if(sessionTaskId&&appliedOutcome&&await stageADuplicateOf(sessionTaskId,appliedOutcome))emitStageARoute("duplicate_result",sessionTaskId);else emitStageARoute(takePendingGateRoute(input.sessionID,input.callID)??"no_task_correlation",null)}catch(routeError){warn("Stage A route classification failed",{sessionID:input.sessionID,error:routeError instanceof Error?routeError.message.slice(0,80):String(routeError)})}let session=swarmState.agentSessions.get(input.sessionID);if(session){if(isGateTool(input.tool)&&pendingGateTask?.sessionID===input.sessionID){let taskId=pendingGateTask.taskId;if(!session.gateLog.has(taskId))session.gateLog.set(taskId,new Set);session.gateLog.get(taskId)?.add(input.tool);let outputStr=typeof safeOutput.output==="string"?safeOutput.output:"";if(normalizeToolName(input.tool)==="pre_check_batch"){let verdict=decodePreCheckResult(safeOutput.output);if(verdict.kind==="fail"||verdict.kind==="invalid"){if(session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now(),code:verdict.code},verdict.kind==="invalid")emitStageARoute("invalid_result",isStrictTaskId(taskId)?taskId:null);if(verdict.kind==="fail"&&isStrictTaskId(taskId))try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_failed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next),emitStageARoute("pre_check_failed",taskId)}catch(err){let code=stageAWriteErrorCode(err);if(code&&STAGE_A_CODER_MUTATION_REQUIRED_CODES.has(code))criticalWarn(`[guardrails] Stage A failure write failed for task ${taskId}: ${code}. An accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch failed but an accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`);else if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A failure write failed for task ${taskId}: ${code}. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch failed but the rework transition was rejected. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to persist Stage A failure",{taskId,error:String(err)})}}else if(verdict.kind==="pass"){if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)==="pre_check_batch")session.lastGateFailure=null;if(!isStrictTaskId(taskId))advanceTaskState(session,taskId,"pre_check_passed");if(isStrictTaskId(taskId)&&await stageADuplicateOf(taskId,"stage_a_passed"))emitStageARoute("duplicate_result",taskId);else try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_passed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next),emitStageARoute("valid_pass",taskId)}catch(err){let code=stageAWriteErrorCode(err);if(code==="TASK_WORKFLOW_GENERATION_MISMATCH")emitStageARoute("late_result",taskId);if(code&&STAGE_A_CODER_MUTATION_REQUIRED_CODES.has(code))criticalWarn(`[guardrails] Stage A write failed for task ${taskId}: ${code} — an accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch passed but an accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`);else if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A write failed for task ${taskId}: ${code} — pre_check_batch result was NOT attributed. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch passed but the workflow transition was rejected, so Stage B dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to advance task state after pre_check_batch pass",{taskId,error:String(err)})}}}else if(safeOutput.output===null||safeOutput.output===void 0||outputStr.includes("FAIL")||outputStr.includes("error")||outputStr.toLowerCase().includes("gates_passed: false"))session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now()};else if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)===normalizeToolName(input.tool))session.lastGateFailure=null}let inputArgs=input.args??getStoredInputArgs(input.callID),delegation=isAgentDelegation(input.tool,inputArgs);if(delegation.isDelegation&&(delegation.targetAgent==="reviewer"||delegation.targetAgent==="test_engineer")){let currentPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan){let phaseString=extractCurrentPhaseFromPlan(plan);currentPhase=extractPhaseNumber2(phaseString)}}catch(error93){log("[Guardrails] loadPlan failed during reviewer tracking",{error:error93 instanceof Error?error93.message:String(error93)})}let count=session.reviewerCallCount.get(currentPhase)??0;session.reviewerCallCount.set(currentPhase,count+1)}if(delegation.isDelegation&&delegation.targetAgent==="coder"){let exactGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:input.sessionID,coderCallID:input.callID}),completedTaskId=exactGeneration?.taskId??session.lastCoderDelegationTaskId;if(completedTaskId){session.currentTaskId=completedTaskId;let exactGenerationFiles=exactGeneration?.modifiedFiles??session.modifiedFilesThisCoderTask;if(!session.revisionLimitHit){if(session.coderRevisions++,session.coderRevisions>1&&session.qaSkipCount===0){let conflictPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan)conflictPhase=extractPhaseNumber2(extractCurrentPhaseFromPlan(plan))}catch{}resolveAgentConflict({sessionID:input.sessionID,phase:conflictPhase,taskId:session.currentTaskId??void 0,sourceAgent:"reviewer",targetAgent:"coder",conflictType:"feedback_rejection",rejectionCount:session.coderRevisions-1,summary:`Coder revision ${session.coderRevisions} for task ${session.currentTaskId??"unknown"}`}),session.lastDelegationReason="review_rejected"}let maxRevisions=cfg.max_coder_revisions??5;if(session.coderRevisions>=maxRevisions)session.revisionLimitHit=!0,telemetry.revisionLimitHit(input.sessionID,session.agentName),pushAdvisory(session,`CODER REVISION LIMIT: Agent has been revised ${session.coderRevisions} times (max: ${maxRevisions}) for task ${session.currentTaskId??"unknown"}. Escalate to user or consider a fundamentally different approach.`),swarmState.pendingEvents++}if(session.partialGateWarningsIssuedForTask?.delete(session.currentTaskId),session.declaredCoderScope!==null){let undeclaredFiles=exactGenerationFiles.map((f)=>f.replace(/[\r\n\t]/g,"_")).filter((f)=>!isInDeclaredScope(f,session.declaredCoderScope,directory));if(undeclaredFiles.length>=1){let safeTaskId=String(session.currentTaskId??"").replace(/[\r\n\t]/g,"_");session.lastScopeViolation=`Scope violation for task ${safeTaskId}: ${undeclaredFiles.length} undeclared files modified: `+undeclaredFiles.join(", "),session.scopeViolationDetected=!0,telemetry.scopeViolation(input.sessionID,session.agentName,session.currentTaskId??"unknown","undeclared files modified")}}session.modifiedFilesThisCoderTask=[]}}}await recordExecutionStallToolAfter({sessionID:input.sessionID,tool:input.tool,callID:input.callID,args:input.args??getStoredInputArgs(input.callID),output:safeOutput,directory:effectiveDirectory,options:executionStallOptions});let sessionId=input.sessionID,normalizedToolName=normalizeToolName(input.tool),isSubagentDispatch=new Set(["dispatch_lanes","dispatch_lanes_async"]).has(normalizedToolName)||isAgentDelegation(input.tool,input.args??getStoredInputArgs(input.callID)).isDelegation;if(isWriteTool2(normalizedToolName)||isSubagentDispatch)touchNoOpSession(sessionId,0),noOpWarningIssued.delete(sessionId),noOpStrongWarningIssued.delete(sessionId);else{let count=(toolCallsSinceLastWrite.get(sessionId)??0)+1;touchNoOpSession(sessionId,count);let threshold=cfg.no_op_warning_threshold??15,strongThreshold=threshold*2;if(count>=threshold&&!noOpWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`WARNING: Agent has made ${count} tool calls with no file modifications and no subagent dispatches. If you are stuck, state what is blocking you and report BLOCKED rather than continuing to probe.`);if(count>=strongThreshold&&!noOpStrongWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpStrongWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`CRITICAL: Agent has made ${count} tool calls with no file modifications and no subagent dispatches — twice the point at which you were first warned. STOP investigating; report BLOCKED to the user now with what you tried.`),telemetry.noOpStrongWarning(sessionId,session.agentName,count,strongThreshold)}let outcome=malformedOutput?{kind:"unknown",signal:""}:classifyToolOutcome(input,safeOutput,correlatedExecution),circuitArgs=correlatedExecution&&typeof input.args==="object"&&input.args!==null&&!Array.isArray(input.args)?{...input.args,command:correlatedExecution.originalCommand}:input.args;if(pendingReviewerScopeWrite&&classifyTaskResult(safeOutput)==="success"){let sessionCaptureRoot=resolveSessionWorkspaceDirectory(input.sessionID,effectiveDirectory),sessionRootIdentity=canonicalWorkspaceIdentity(sessionCaptureRoot),batchDeadline=Date.now()+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let pendingWrite of pendingReviewerScopeWrite){let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID});if(generation&&sessionRootIdentity&&generation.workspaceIdentity!==sessionRootIdentity){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:"workspace_mismatch",retryable:!1});let mismatchSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(mismatchSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} was written from workspace ${sessionRootIdentity} but the coder generation is bound to ${generation.workspaceIdentity} (code workspace_mismatch, retryable=false, responsible: architect). ACTION[architect]: verify the coder dispatch lane/scope binding, then redispatch`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`});continue}let captureRoot=generation?.captureDirectory?.trim()||sessionCaptureRoot,lastFailure=null,attempts=0;while(attempts<REVIEWER_SCOPE_CAPTURE_ATTEMPTS){attempts+=1;let captured=captureReviewerScopeFileFingerprint(captureRoot,pendingWrite.file,{deadlineAt:batchDeadline});if(captured.kind!=="capture_failed"){let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,fingerprint:fingerprint2});lastFailure=null;break}if(lastFailure={code:captured.code,retryable:captured.retryable},!captured.retryable)break}if(lastFailure){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:lastFailure.code,retryable:lastFailure.retryable});let captureSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(captureSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} could not be fingerprinted exactly (code ${lastFailure.code}, retryable=${lastFailure.retryable}, attempts=${attempts}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${lastFailure.retryable?"retry the coder write or re-dispatch the coder so capture re-runs":`resolve the ${lastFailure.code} condition for the file, then retry or route explicit manual review`}`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`})}}}if(outcome.kind==="fatal")recordNonTransientFailure(input.sessionID,outcome.category,outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});else if(outcome.kind==="success"||outcome.kind==="neutral")clearNonTransientCircuit(input.sessionID,{tool:input.tool,args:circuitArgs});else if(outcome.kind==="failure")recordNonTransientFailure(input.sessionID,"general_permanent",outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});let window2=getActiveWindow(input.sessionID);if(!window2)return;if(outcome.kind==="fatal"){window2.consecutiveErrors++;return}if(outcome.kind==="failure")window2.consecutiveErrors++;else if(window2.consecutiveErrors=0,window2.transientRetryCount=0,window2.lastSuccessTimeMs=Date.now(),session){if(session.model_fallback_index>0)session.model_fallback_index=0,session.modelFallbackExhausted=!1}},messagesTransform}}var MAX_PENDING_GATE_RECEIPTS_PER_SESSION=256,MAX_PENDING_GATE_RECEIPT_SESSIONS=500,MAX_PENDING_GATE_ROUTES_PER_SESSION=256,MAX_PENDING_GATE_ROUTE_SESSIONS=500,_internals81,DURABLE_ATTRIBUTION_ADVISORY_COOLDOWN_MS=60000,MAX_DURABLE_ATTRIBUTION_ADVISORY_SESSIONS=500,durableAttributionAdvisoryBySession,STAGE_A_CODER_MUTATION_REQUIRED_CODES,STAGE_A_ATTRIBUTION_MISS_CODES,SPEC_DRIFT_BLOCKED_TOOLS,MAX_TRACKED_NO_OP_SESSIONS=200,toolCallsSinceLastWrite,noOpWarningIssued,noOpStrongWarningIssued;var init_guardrails=__esm(()=>{init_agents2();init_constants();init_schema();init_gate_evidence();init_manager();init_executor();init_path_identity();init_scope_binding();init_scope_lease_renewal();init_state2();init_telemetry();init_utils();init_logger();init_spec_hash();init_task_id();init_coder_settlement();init_conflict_resolution();init_extractors();init_normalize_tool_name();init_reviewer_scope_file_fingerprint();init_task_result_classifier();init_destructive_command();init_execution_stall();init_file_authority();init_helpers();init_messages_transform();init_nontransient_circuit();init_pre_check_result();init_stage_a_route();init_stored_input_args();init_tool_before();init_helpers();_internals81={extractSwarmIdFromAgentName,getSwarmAgents,getMostRecentAssistantText,getProviderFailureFingerprint,isTransientProviderFailureText,resolveFallbackModel,dcCheckJunctionCreation,extractErrorSignal,getSandboxExecutor:getExecutor,assessSandboxEnforcement,allowUncorrelatedGateReceipts:!1,MAX_PENDING_GATE_RECEIPTS_PER_SESSION,MAX_PENDING_GATE_RECEIPT_SESSIONS,MAX_PENDING_GATE_ROUTES_PER_SESSION,MAX_PENDING_GATE_ROUTE_SESSIONS,noOpStateSize:()=>toolCallsSinceLastWrite.size,hasNoOpState:(sessionID)=>toolCallsSinceLastWrite.has(sessionID),resolveDurableGateTaskId:(directory,callerFiles)=>resolveDurableGateTaskId(directory,callerFiles)},durableAttributionAdvisoryBySession=new Map;STAGE_A_CODER_MUTATION_REQUIRED_CODES=new Set(["TASK_WORKFLOW_CODER_MUTATION_REQUIRED"]),STAGE_A_ATTRIBUTION_MISS_CODES=new Set(["TASK_WORKFLOW_STAGE_A_REQUIRED"]);SPEC_DRIFT_BLOCKED_TOOLS=new Set(["save_plan","update_task_status","phase_complete","lean_turbo_run_phase","lean_turbo_acquire_locks"]);toolCallsSinceLastWrite=new Map,noOpWarningIssued=new Set,noOpStrongWarningIssued=new Set});var init_guardrails2=__esm(()=>{init_file_authority();init_guardrails();init_stored_input_args()});var exports_model_preflight={};__export(exports_model_preflight,{splitModelId:()=>splitModelId,sanitizePreflightText:()=>sanitizePreflightText,runModelPreflight:()=>runModelPreflight,resolveAgainstCatalog:()=>resolveAgainstCatalog,invalidateProviderCatalogCache:()=>invalidateProviderCatalogCache,formatModelPreflightWarning:()=>formatModelPreflightWarning,fetchProviderCatalog:()=>fetchProviderCatalog,enumerateEnabledAgentRoles:()=>enumerateEnabledAgentRoles,collectEnabledAgentModels:()=>collectEnabledAgentModels,collectConfiguredAgentModels:()=>collectConfiguredAgentModels,checkSingleModelResolution:()=>checkSingleModelResolution,_internals:()=>_internals82,PROVIDER_LIST_TIMEOUT_MS:()=>PROVIDER_LIST_TIMEOUT_MS});function splitModelId(model){let separator=model.indexOf("/");if(separator<=0||separator===model.length-1)return null;return{provider:model.slice(0,separator),model:model.slice(separator+1)}}function collectConfiguredAgentModels(config3){let collected=[],overriddenAgents=new Set,overrides2=config3?.agents??{};for(let[agent,override]of Object.entries(overrides2)){if(typeof override?.model==="string"&&override.model.trim())collected.push({agent,model:override.model.trim(),source:"override"}),overriddenAgents.add(agent);for(let fallback of override?.fallback_models??[])if(typeof fallback==="string"&&fallback.trim())collected.push({agent,model:fallback.trim(),source:"fallback"})}for(let[agent,model]of Object.entries(DEFAULT_MODELS)){if(overriddenAgents.has(agent))continue;collected.push({agent,model,source:"default"})}return collected}function enumerateEnabledAgentRoles(config3){let names=[],emitSwarm=(swarmId,isDefault)=>{let prefix=isDefault?"":`${swarmId}_`,swarmAgents=config3?.swarms?.[swarmId]?.agents,merged=config3?.agents?{...config3.agents,...swarmAgents??{}}:swarmAgents??{};for(let role of ALWAYS_ON_ROLES){if(merged?.[role]?.disabled===!0)continue;names.push(`${prefix}${role}`)}for(let[role,flagEnabled]of FEATURE_GATED_ROLES){if(!flagEnabled(config3))continue;if(merged?.[role]?.disabled===!0)continue;names.push(`${prefix}${role}`)}},swarms=config3?.swarms;if(swarms&&Object.keys(swarms).length>0)for(let swarmId of Object.keys(swarms))emitSwarm(swarmId,swarmId==="default");else emitSwarm("default",!0);return names}function collectEnabledAgentModels(config3,opts){let names=opts?.generatedAgentNames&&opts.generatedAgentNames.length>0?[...opts.generatedAgentNames]:enumerateEnabledAgentRoles(config3),primaryNames=opts?.registeredAgents?new Set(Object.entries(opts.registeredAgents).filter(([,value])=>value?.mode==="primary").map(([name])=>name)):resolvePrimaryAgentNames(names,config3?.default_agent).primaryNames,collected=[];for(let name of names){let mode=primaryNames.has(name)?"primary":"subagent",effective=config3?resolveEffectiveAgentOverride(config3,name):void 0,configuredModel=config3?resolveConfiguredAgentModel(config3,name):void 0,finalModel=config3?resolveRegisteredAgentModel(config3,name):DEFAULT_MODELS[stripKnownSwarmPrefix(name)]??DEFAULT_MODELS.default;if(effective&&typeof effective.model==="string"&&effective.model.trim()==="")collected.push({agent:name,model:"",source:"override",mode});else collected.push({agent:name,model:finalModel??"",source:configuredModel!==void 0?"override":"default",mode});for(let fallback of effective?.fallbackModels??[])if(typeof fallback==="string"&&fallback.trim())collected.push({agent:name,model:fallback.trim(),source:"fallback",mode})}return collected}function invalidateProviderCatalogCache(){catalogCacheEpoch++,catalogCacheByClient=new WeakMap}function sanitizePreflightText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}async function fetchProviderCatalog(client){if(!client)return null;let cached3=catalogCacheByClient.get(client);if(cached3&&Date.now()-cached3.fetchedAt<CATALOG_CACHE_TTL_MS)return cached3.catalog;let epochAtFetchStart=catalogCacheEpoch,response;try{response=await _internals82.providerList(client)}catch{return null}let all=response?.data?.all;if(!Array.isArray(all))return null;let catalog2=new Map;for(let provider of all){if(typeof provider?.id!=="string")continue;let models=new Set;if(provider.models&&typeof provider.models==="object"&&!Array.isArray(provider.models))for(let modelKey of Object.keys(provider.models))models.add(modelKey);catalog2.set(provider.id,models)}if(epochAtFetchStart===catalogCacheEpoch)catalogCacheByClient.set(client,{fetchedAt:Date.now(),catalog:catalog2});return catalog2}function resolveAgainstCatalog(models,catalog2){let classifySelection=(entry)=>{if(entry.model.trim()==="")return{...entry,status:"missing-selection",detail:"enabled role has no final model selection: the exact agent target resolved to no configured model and no default (blank model override or a stale swarm registry entry). Fix agents.<role>.model in opencode-swarm.json — the matching swarm override wins over the top-level entry."};if(entry.mode==="primary")return{...entry,status:"host-controlled",detail:"primary agent: OpenCode UI owns the model selection; the registered model is intentionally not applied"};let split=splitModelId(entry.model);if(!split)return{...entry,status:"unknown",detail:"model id has no provider prefix; resolution not checked against the catalog"};let providerModels=catalog2?.get(split.provider);if(providerModels===void 0)return{...entry,status:"unresolved",detail:`provider "${split.provider}" is not present in the provider catalog`};if(!providerModels.has(split.model))return{...entry,status:"unresolved",detail:`provider "${split.provider}" does not list model "${split.model}"`};return{...entry,status:"ok"}};if(catalog2===null)return{catalogAvailable:!1,resolutions:models.map((entry)=>entry.model.trim()===""?classifySelection(entry):{...entry,status:"unknown",detail:"provider catalog unavailable; model resolution not checked"})};return{catalogAvailable:!0,resolutions:models.map(classifySelection)}}function formatModelPreflightWarning(result){let reportable=result.resolutions.filter((resolution)=>resolution.status==="unresolved"||resolution.status==="missing-selection");if(reportable.length===0)return null;let lines=reportable.map((resolution)=>{let label=resolution.source==="fallback"?`${sanitizePreflightText(resolution.agent)} (fallback entry)`:sanitizePreflightText(resolution.agent);if(resolution.status==="missing-selection")return` ${label}: no final model selection — ${sanitizePreflightText(resolution.detail??"")}`;return` ${label}: ${sanitizePreflightText(resolution.model)} (${sanitizePreflightText(resolution.detail??"does not resolve")})`});return`[opencode-swarm] WARNING: ${reportable.length} enabled agent model selection(s) failed preflight:
1239
+ (no recorded snapshot to diff against)`;throw Error(message)}}function isPlainObject4(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function readSignalField(source,key2){try{return source[key2]}catch{return}}function pushSignalValue(parts,value){if(typeof value==="string"){parts.push(value);return}if(typeof value==="number"||typeof value==="boolean")parts.push(String(value))}function appendSelectedFields(parts,source,keys){for(let key2 of keys)pushSignalValue(parts,readSignalField(source,key2))}function appendNestedErrorSignal(parts,value){if(typeof value==="string"){parts.push(value);return}if(value instanceof Error){parts.push(value.name,value.message),appendSelectedFields(parts,value,["code","status","statusCode"]);return}if(!isPlainObject4(value))return;appendSelectedFields(parts,value,["code","status","statusCode","message","error_type"])}function extractErrorSignal(errorContent){if(typeof errorContent==="string")return errorContent;if(errorContent==null)return"";let parts=[];try{if(errorContent instanceof Error)return parts.push(errorContent.name,errorContent.message),appendSelectedFields(parts,errorContent,["code","status","statusCode"]),parts.join(" ");if(!isPlainObject4(errorContent))return"";appendSelectedFields(parts,errorContent,["code","status","statusCode","message","error_type"]),appendNestedErrorSignal(parts,readSignalField(errorContent,"error"));let metadata=readSignalField(errorContent,"metadata");if(isPlainObject4(metadata))appendSelectedFields(parts,metadata,["code","status","statusCode","error_type"]);appendNestedErrorSignal(parts,readSignalField(errorContent,"cause"))}catch{return parts.join(" ")}return parts.join(" ")}function touchNoOpSession(sessionID,count){toolCallsSinceLastWrite.delete(sessionID),toolCallsSinceLastWrite.set(sessionID,count),evictNoOpStateIfOverBound()}function evictNoOpStateIfOverBound(){while(toolCallsSinceLastWrite.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=toolCallsSinceLastWrite.keys().next().value;if(stalestKey===void 0)break;toolCallsSinceLastWrite.delete(stalestKey),noOpWarningIssued.delete(stalestKey),noOpStrongWarningIssued.delete(stalestKey)}while(noOpWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpWarningIssued.delete(stalestKey)}while(noOpStrongWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpStrongWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpStrongWarningIssued.delete(stalestKey)}}function extractPhaseNumber2(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function isWriteTool2(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isGateTool(toolName){let normalized=normalizeToolName(toolName);return["diff","syntax_check","placeholder_scan","imports","lint","build_check","pre_check_batch","secretscan","sast_scan","quality_budget"].includes(normalized)}function isAgentDelegation(toolName,args2){if(!isTaskToolId(toolName))return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function createGuardrailsHooks(directory,directoryOrConfig,config3,authorityConfig,worktreeBaseDirOverrides,resolveAgentModel){let guardrailsConfig;if(directory&&typeof directory==="object"&&"enabled"in directory)warn("[guardrails] Legacy call without directory, falling back to process.cwd()"),guardrailsConfig=directory;else if(directoryOrConfig&&typeof directoryOrConfig==="object"&&"enabled"in directoryOrConfig)guardrailsConfig=directoryOrConfig;else guardrailsConfig=config3;let effectiveDirectory=(()=>{if(typeof directory==="string")return directory;let cwd=process.cwd();return warn(`[guardrails] effectiveDirectory resolved to process.cwd() "${cwd}" — `+"pass an explicit directory string to createGuardrailsHooks to avoid .swarm artifacts in wrong locations"),cwd})(),enforcementEnabled=guardrailsConfig?.enabled!==!1,precomputedAuthorityRules=buildEffectiveRules(authorityConfig),verifierPaths=authorityConfig?.verifier_config_paths;if(verifierPaths&&verifierPaths.length>0){let existingArchitect=precomputedAuthorityRules.architect??{};precomputedAuthorityRules.architect={...existingArchitect,blockedGlobs:[...existingArchitect.blockedGlobs??[],...verifierPaths]}}let universalDenyPrefixes=authorityConfig?.universal_deny_prefixes??[];if(guardrailsConfig===void 0||guardrailsConfig===null)throw TypeError("createGuardrailsHooks: guardrailsConfig is required — pass the resolved GuardrailsConfig object");let cfg=guardrailsConfig,requiredQaGates=cfg.qa_gates?.required_tools??["diff","syntax_check","placeholder_scan","lint","pre_check_batch"],requireReviewerAndTestEngineer=cfg.qa_gates?.require_reviewer_test_engineer??!0,interpreterAllowedAgents=cfg.interpreter_allowed_agents,shellAuditEnabled=cfg.shell_audit_log??!0,consecutiveNoToolTurns=new Map,lastCountedAssistantMsgId=new Map,pendingReviewerScopeWrites=new Map,pendingGateTasksBySession=new Map,takePendingGateTask=(sessionID,callID)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID),pending=sessionTasks?.get(callID);if(sessionTasks){if(sessionTasks.delete(callID),sessionTasks.size===0)pendingGateTasksBySession.delete(sessionID)}return pending},rememberPendingGateTask=(sessionID,callID,taskId,generation)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID);if(!sessionTasks){if(pendingGateTasksBySession.size>=MAX_PENDING_GATE_RECEIPT_SESSIONS)throw Error("GATE_RECEIPT_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionTasks=new Map,pendingGateTasksBySession.set(sessionID,sessionTasks)}if(!sessionTasks.has(callID)&&sessionTasks.size>=MAX_PENDING_GATE_RECEIPTS_PER_SESSION)throw Error("GATE_RECEIPT_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionTasks.set(callID,{sessionID,taskId,generation})},pendingGateRoutesBySession=new Map,takePendingGateRoute=(sessionID,callID)=>{let sessionRoutes=pendingGateRoutesBySession.get(sessionID),route=sessionRoutes?.get(callID);if(sessionRoutes){if(sessionRoutes.delete(callID),sessionRoutes.size===0)pendingGateRoutesBySession.delete(sessionID)}return route},rememberPendingGateRoute=(sessionID,callID,route)=>{let sessionRoutes=pendingGateRoutesBySession.get(sessionID);if(!sessionRoutes){if(pendingGateRoutesBySession.size>=MAX_PENDING_GATE_ROUTE_SESSIONS)throw Error("GATE_ROUTE_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionRoutes=new Map,pendingGateRoutesBySession.set(sessionID,sessionRoutes)}if(!sessionRoutes.has(callID)&&sessionRoutes.size>=MAX_PENDING_GATE_ROUTES_PER_SESSION)throw Error("GATE_ROUTE_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionRoutes.set(callID,route)},scopeLeaseRenewal=createScopeLeaseRenewalTracker(),rememberReviewerScopeWrite=(input)=>{if(!pendingReviewerScopeWrites.has(input.callID)&&pendingReviewerScopeWrites.size>=256){let oldest=pendingReviewerScopeWrites.keys().next().value;if(oldest!==void 0)pendingReviewerScopeWrites.delete(oldest)}let pending=pendingReviewerScopeWrites.get(input.callID)??[],candidate={parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,file:input.file};if(!pending.some((entry)=>entry.parentSessionID===candidate.parentSessionID&&entry.taskId===candidate.taskId&&entry.coderCallID===candidate.coderCallID&&entry.file===candidate.file)&&pending.length<256)pending.push(candidate);pendingReviewerScopeWrites.set(input.callID,pending)},executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},baseToolBefore=createToolBeforeHandler({effectiveDirectory,cfg,enforcePolicy:enforcementEnabled,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,rememberReviewerScopeWrite,rememberScopeLeaseCandidate:scopeLeaseRenewal.remember,getSandboxExecutor:_internals81.getSandboxExecutor,assessSandboxEnforcement:_internals81.assessSandboxEnforcement}),toolBefore=async(input,output)=>{if(isGateTool(input.tool)){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId,unattributableRoute="no_task_correlation";if(!taskId){let callerFiles=extractGateCallFiles(output.args),fallback=await _internals81.resolveDurableGateTaskId(effectiveDirectory,callerFiles);if(fallback){if("taskId"in fallback)taskId=fallback.taskId;else if("ambiguous"in fallback&&fallback.ambiguous.length>0){unattributableRoute="attribution_ambiguous";let shown=fallback.ambiguous.slice(0,10),more=fallback.ambiguous.length-shown.length;emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00${fallback.ambiguous.join(",")}`,`STAGE A ATTRIBUTION AMBIGUOUS: ${fallback.ambiguous.length} tasks are settled at coder_delegated (${shown.join(", ")}${more>0?`, +${more} more`:""}) but this session has no task correlation after reset-session. Stage A evidence cannot be attributed safely. Run /swarm recover to repair Stage A attribution, then re-run the gate.`)}else if("unbound"in fallback)unattributableRoute="attribution_ambiguous",emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00unbound\x00${fallback.unbound}`,fallback.reason==="truncated"?`STAGE A ATTRIBUTION UNVERIFIABLE: task ${fallback.unbound} looks like the sole durable candidate at coder_delegated, but the settlement scan is truncated (more than 200 historical settlements) so a second candidate cannot be ruled out. Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`:`STAGE A ATTRIBUTION UNBOUND: task ${fallback.unbound} is the sole durable candidate at coder_delegated, but this gate call's scanned files do not match its declared changes (or no file scope was provided). Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`)}}if(taskId){let workflow=isStrictTaskId(taskId)?getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId)):null;rememberPendingGateTask(input.sessionID,input.callID,taskId,workflow?.generation??0)}else try{rememberPendingGateRoute(input.sessionID,input.callID,unattributableRoute)}catch(routeError){warn("Stage A route classification dropped at capacity",{sessionID:input.sessionID,error:routeError instanceof Error?routeError.message.slice(0,80):String(routeError)})}}try{await baseToolBefore(input,output)}catch(error93){throw takePendingGateTask(input.sessionID,input.callID),error93}},messagesTransform=enforcementEnabled?createMessagesTransformHandler({effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId,resolveAgentModel}):async()=>{};return{toolBefore,toolAfter:async(input,output)=>{let pendingGateTask=takePendingGateTask(input.sessionID,input.callID)??(_internals81.allowUncorrelatedGateReceipts?(()=>{let testSession=swarmState.agentSessions.get(input.sessionID);return testSession?{sessionID:input.sessionID,taskId:testSession.currentTaskId??`${input.sessionID}:unknown`,generation:testSession.currentTaskId&&isStrictTaskId(testSession.currentTaskId)?testSession.taskWorkflowCache?.get(testSession.currentTaskId)?.generation??0:0}:void 0})():void 0),pendingReviewerScopeWrite=pendingReviewerScopeWrites.get(input.callID);pendingReviewerScopeWrites.delete(input.callID);let correlatedExecution=takeToolExecution(input.sessionID,input.callID);if(correlatedExecution&&!isToolExecutionCurrent(input.sessionID,correlatedExecution)){await scopeLeaseRenewal.consume({...input,output:null});return}let malformedOutput=!output||typeof output!=="object",safeOutput=malformedOutput?{title:"",output:"",metadata:null}:output;await scopeLeaseRenewal.consume({...input,output:malformedOutput?null:safeOutput});let emitStageARoute=(route,taskId)=>{recordStageAGateRoute(effectiveDirectory,{route,sessionID:input.sessionID,callID:input.callID,taskId,guardrailsEnabled:enforcementEnabled,...pendingGateTask?{generation:pendingGateTask.generation}:{}})},stageADuplicateOf=async(taskId,appliedOutcome)=>{try{let snapshot=getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId));return snapshot.authoritative===!0&&snapshot.lastTransitionId===`pre-check:${input.callID}`&&snapshot.lastOutcome===appliedOutcome}catch{return!1}};if(normalizeToolName(input.tool)==="pre_check_batch"&&!pendingGateTask)try{let verdict=decodePreCheckResult(safeOutput.output),sessionTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null,appliedOutcome=verdict.kind==="pass"?"stage_a_passed":verdict.kind==="fail"?"stage_a_failed":null;if(sessionTaskId&&appliedOutcome&&await stageADuplicateOf(sessionTaskId,appliedOutcome))emitStageARoute("duplicate_result",sessionTaskId);else emitStageARoute(takePendingGateRoute(input.sessionID,input.callID)??"no_task_correlation",null)}catch(routeError){warn("Stage A route classification failed",{sessionID:input.sessionID,error:routeError instanceof Error?routeError.message.slice(0,80):String(routeError)})}let session=swarmState.agentSessions.get(input.sessionID);if(session){if(isGateTool(input.tool)&&pendingGateTask?.sessionID===input.sessionID){let taskId=pendingGateTask.taskId;if(!session.gateLog.has(taskId))session.gateLog.set(taskId,new Set);session.gateLog.get(taskId)?.add(input.tool);let outputStr=typeof safeOutput.output==="string"?safeOutput.output:"";if(normalizeToolName(input.tool)==="pre_check_batch"){let verdict=decodePreCheckResult(safeOutput.output);if(verdict.kind==="fail"||verdict.kind==="invalid"){if(session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now(),code:verdict.code},verdict.kind==="invalid")emitStageARoute("invalid_result",isStrictTaskId(taskId)?taskId:null);if(verdict.kind==="fail"&&isStrictTaskId(taskId))try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_failed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next),emitStageARoute("pre_check_failed",taskId)}catch(err){let code=stageAWriteErrorCode(err);if(code&&STAGE_A_CODER_MUTATION_REQUIRED_CODES.has(code))criticalWarn(`[guardrails] Stage A failure write failed for task ${taskId}: ${code}. An accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch failed but an accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`);else if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A failure write failed for task ${taskId}: ${code}. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch failed but the rework transition was rejected. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to persist Stage A failure",{taskId,error:String(err)})}}else if(verdict.kind==="pass"){if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)==="pre_check_batch")session.lastGateFailure=null;if(!isStrictTaskId(taskId))advanceTaskState(session,taskId,"pre_check_passed");if(isStrictTaskId(taskId)&&await stageADuplicateOf(taskId,"stage_a_passed"))emitStageARoute("duplicate_result",taskId);else try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_passed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next),emitStageARoute("valid_pass",taskId)}catch(err){let code=stageAWriteErrorCode(err);if(code==="TASK_WORKFLOW_GENERATION_MISMATCH")emitStageARoute("late_result",taskId);if(code&&STAGE_A_CODER_MUTATION_REQUIRED_CODES.has(code))criticalWarn(`[guardrails] Stage A write failed for task ${taskId}: ${code} — an accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch passed but an accepted coder mutation is required before Stage A can be recorded again. If the task is rework_required because Stage B did not require a code change, the architect-only recover_rework_task path is valid after fresh green pre_check_batch proof; for a genuine defect, dispatch a coder for a real code change, and mark the task blocked only when neither path applies.`);else if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A write failed for task ${taskId}: ${code} — pre_check_batch result was NOT attributed. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch passed but the workflow transition was rejected, so Stage B dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to advance task state after pre_check_batch pass",{taskId,error:String(err)})}}}else if(safeOutput.output===null||safeOutput.output===void 0||outputStr.includes("FAIL")||outputStr.includes("error")||outputStr.toLowerCase().includes("gates_passed: false"))session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now()};else if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)===normalizeToolName(input.tool))session.lastGateFailure=null}let inputArgs=input.args??getStoredInputArgs(input.callID),delegation=isAgentDelegation(input.tool,inputArgs);if(delegation.isDelegation&&(delegation.targetAgent==="reviewer"||delegation.targetAgent==="test_engineer")){let currentPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan){let phaseString=extractCurrentPhaseFromPlan(plan);currentPhase=extractPhaseNumber2(phaseString)}}catch(error93){log("[Guardrails] loadPlan failed during reviewer tracking",{error:error93 instanceof Error?error93.message:String(error93)})}let count=session.reviewerCallCount.get(currentPhase)??0;session.reviewerCallCount.set(currentPhase,count+1)}if(delegation.isDelegation&&delegation.targetAgent==="coder"){let exactGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:input.sessionID,coderCallID:input.callID}),completedTaskId=exactGeneration?.taskId??session.lastCoderDelegationTaskId;if(completedTaskId){session.currentTaskId=completedTaskId;let exactGenerationFiles=exactGeneration?.modifiedFiles??session.modifiedFilesThisCoderTask;if(!session.revisionLimitHit){if(session.coderRevisions++,session.coderRevisions>1&&session.qaSkipCount===0){let conflictPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan)conflictPhase=extractPhaseNumber2(extractCurrentPhaseFromPlan(plan))}catch{}resolveAgentConflict({sessionID:input.sessionID,phase:conflictPhase,taskId:session.currentTaskId??void 0,sourceAgent:"reviewer",targetAgent:"coder",conflictType:"feedback_rejection",rejectionCount:session.coderRevisions-1,summary:`Coder revision ${session.coderRevisions} for task ${session.currentTaskId??"unknown"}`}),session.lastDelegationReason="review_rejected"}let maxRevisions=cfg.max_coder_revisions??5;if(session.coderRevisions>=maxRevisions)session.revisionLimitHit=!0,telemetry.revisionLimitHit(input.sessionID,session.agentName),pushAdvisory(session,`CODER REVISION LIMIT: Agent has been revised ${session.coderRevisions} times (max: ${maxRevisions}) for task ${session.currentTaskId??"unknown"}. Escalate to user or consider a fundamentally different approach.`),swarmState.pendingEvents++}if(session.partialGateWarningsIssuedForTask?.delete(session.currentTaskId),session.declaredCoderScope!==null){let undeclaredFiles=exactGenerationFiles.map((f)=>f.replace(/[\r\n\t]/g,"_")).filter((f)=>!isInDeclaredScope(f,session.declaredCoderScope,directory));if(undeclaredFiles.length>=1){let safeTaskId=String(session.currentTaskId??"").replace(/[\r\n\t]/g,"_");session.lastScopeViolation=`Scope violation for task ${safeTaskId}: ${undeclaredFiles.length} undeclared files modified: `+undeclaredFiles.join(", "),session.scopeViolationDetected=!0,telemetry.scopeViolation(input.sessionID,session.agentName,session.currentTaskId??"unknown","undeclared files modified")}}session.modifiedFilesThisCoderTask=[]}}}await recordExecutionStallToolAfter({sessionID:input.sessionID,tool:input.tool,callID:input.callID,args:input.args??getStoredInputArgs(input.callID),output:safeOutput,directory:effectiveDirectory,options:executionStallOptions});let sessionId=input.sessionID,normalizedToolName=normalizeToolName(input.tool),isSubagentDispatch=new Set(["dispatch_lanes","dispatch_lanes_async"]).has(normalizedToolName)||isAgentDelegation(input.tool,input.args??getStoredInputArgs(input.callID)).isDelegation;if(isWriteTool2(normalizedToolName)||isSubagentDispatch)touchNoOpSession(sessionId,0),noOpWarningIssued.delete(sessionId),noOpStrongWarningIssued.delete(sessionId);else{let count=(toolCallsSinceLastWrite.get(sessionId)??0)+1;touchNoOpSession(sessionId,count);let threshold=cfg.no_op_warning_threshold??15,strongThreshold=threshold*2;if(count>=threshold&&!noOpWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`WARNING: Agent has made ${count} tool calls with no file modifications and no subagent dispatches. If you are stuck, state what is blocking you and report BLOCKED rather than continuing to probe.`);if(count>=strongThreshold&&!noOpStrongWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpStrongWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`CRITICAL: Agent has made ${count} tool calls with no file modifications and no subagent dispatches — twice the point at which you were first warned. STOP investigating; report BLOCKED to the user now with what you tried.`),telemetry.noOpStrongWarning(sessionId,session.agentName,count,strongThreshold)}let outcome=malformedOutput?{kind:"unknown",signal:""}:classifyToolOutcome(input,safeOutput,correlatedExecution),circuitArgs=correlatedExecution&&typeof input.args==="object"&&input.args!==null&&!Array.isArray(input.args)?{...input.args,command:correlatedExecution.originalCommand}:input.args;if(pendingReviewerScopeWrite&&classifyTaskResult(safeOutput)==="success"){let sessionCaptureRoot=resolveSessionWorkspaceDirectory(input.sessionID,effectiveDirectory),sessionRootIdentity=canonicalWorkspaceIdentity(sessionCaptureRoot),batchDeadline=Date.now()+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let pendingWrite of pendingReviewerScopeWrite){let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID});if(generation&&sessionRootIdentity&&generation.workspaceIdentity!==sessionRootIdentity){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:"workspace_mismatch",retryable:!1});let mismatchSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(mismatchSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} was written from workspace ${sessionRootIdentity} but the coder generation is bound to ${generation.workspaceIdentity} (code workspace_mismatch, retryable=false, responsible: architect). ACTION[architect]: verify the coder dispatch lane/scope binding, then redispatch`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`});continue}let captureRoot=generation?.captureDirectory?.trim()||sessionCaptureRoot,lastFailure=null,attempts=0;while(attempts<REVIEWER_SCOPE_CAPTURE_ATTEMPTS){attempts+=1;let captured=captureReviewerScopeFileFingerprint(captureRoot,pendingWrite.file,{deadlineAt:batchDeadline});if(captured.kind!=="capture_failed"){let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,fingerprint:fingerprint2});lastFailure=null;break}if(lastFailure={code:captured.code,retryable:captured.retryable},!captured.retryable)break}if(lastFailure){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:lastFailure.code,retryable:lastFailure.retryable});let captureSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(captureSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} could not be fingerprinted exactly (code ${lastFailure.code}, retryable=${lastFailure.retryable}, attempts=${attempts}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${lastFailure.retryable?"retry the coder write or re-dispatch the coder so capture re-runs":`resolve the ${lastFailure.code} condition for the file, then retry or route explicit manual review`}`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`})}}}if(outcome.kind==="fatal")recordNonTransientFailure(input.sessionID,outcome.category,outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});else if(outcome.kind==="success"||outcome.kind==="neutral")clearNonTransientCircuit(input.sessionID,{tool:input.tool,args:circuitArgs});else if(outcome.kind==="failure")recordNonTransientFailure(input.sessionID,"general_permanent",outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});let window2=getActiveWindow(input.sessionID);if(!window2)return;if(outcome.kind==="fatal"){window2.consecutiveErrors++;return}if(outcome.kind==="failure")window2.consecutiveErrors++;else if(window2.consecutiveErrors=0,window2.transientRetryCount=0,window2.lastSuccessTimeMs=Date.now(),session){if(session.model_fallback_index>0)session.model_fallback_index=0,session.modelFallbackExhausted=!1}},messagesTransform}}var MAX_PENDING_GATE_RECEIPTS_PER_SESSION=256,MAX_PENDING_GATE_RECEIPT_SESSIONS=500,MAX_PENDING_GATE_ROUTES_PER_SESSION=256,MAX_PENDING_GATE_ROUTE_SESSIONS=500,_internals81,DURABLE_ATTRIBUTION_ADVISORY_COOLDOWN_MS=60000,MAX_DURABLE_ATTRIBUTION_ADVISORY_SESSIONS=500,durableAttributionAdvisoryBySession,STAGE_A_CODER_MUTATION_REQUIRED_CODES,STAGE_A_ATTRIBUTION_MISS_CODES,SPEC_DRIFT_BLOCKED_TOOLS,MAX_TRACKED_NO_OP_SESSIONS=200,toolCallsSinceLastWrite,noOpWarningIssued,noOpStrongWarningIssued;var init_guardrails=__esm(()=>{init_agents2();init_constants();init_schema();init_gate_evidence();init_manager();init_executor();init_path_identity();init_scope_binding();init_scope_lease_renewal();init_state2();init_telemetry();init_utils();init_logger();init_spec_hash();init_task_id();init_coder_settlement();init_conflict_resolution();init_extractors();init_normalize_tool_name();init_reviewer_scope_file_fingerprint();init_task_result_classifier();init_destructive_command();init_execution_stall();init_file_authority();init_helpers();init_messages_transform();init_nontransient_circuit();init_pre_check_result();init_stage_a_route();init_stored_input_args();init_tool_before();init_helpers();_internals81={extractSwarmIdFromAgentName,getSwarmAgents,getMostRecentAssistantText,getProviderFailureFingerprint,isTransientProviderFailureText,resolveFallbackModel,dcCheckJunctionCreation,extractErrorSignal,getSandboxExecutor:getExecutor,assessSandboxEnforcement,allowUncorrelatedGateReceipts:!1,MAX_PENDING_GATE_RECEIPTS_PER_SESSION,MAX_PENDING_GATE_RECEIPT_SESSIONS,MAX_PENDING_GATE_ROUTES_PER_SESSION,MAX_PENDING_GATE_ROUTE_SESSIONS,noOpStateSize:()=>toolCallsSinceLastWrite.size,hasNoOpState:(sessionID)=>toolCallsSinceLastWrite.has(sessionID),resolveDurableGateTaskId:(directory,callerFiles)=>resolveDurableGateTaskId(directory,callerFiles)},durableAttributionAdvisoryBySession=new Map;STAGE_A_CODER_MUTATION_REQUIRED_CODES=new Set(["TASK_WORKFLOW_CODER_MUTATION_REQUIRED"]),STAGE_A_ATTRIBUTION_MISS_CODES=new Set(["TASK_WORKFLOW_STAGE_A_REQUIRED"]);SPEC_DRIFT_BLOCKED_TOOLS=new Set(["save_plan","update_task_status","phase_complete","lean_turbo_run_phase","lean_turbo_acquire_locks"]);toolCallsSinceLastWrite=new Map,noOpWarningIssued=new Set,noOpStrongWarningIssued=new Set});var init_guardrails2=__esm(()=>{init_file_authority();init_guardrails();init_stored_input_args()});var exports_model_preflight={};__export(exports_model_preflight,{splitModelId:()=>splitModelId,sanitizePreflightText:()=>sanitizePreflightText,runModelPreflight:()=>runModelPreflight,resolveAgainstCatalog:()=>resolveAgainstCatalog,invalidateProviderCatalogCache:()=>invalidateProviderCatalogCache,formatModelPreflightWarning:()=>formatModelPreflightWarning,fetchProviderCatalog:()=>fetchProviderCatalog,enumerateEnabledAgentRoles:()=>enumerateEnabledAgentRoles,collectModelRosterWarnings:()=>collectModelRosterWarnings,collectEnabledAgentModels:()=>collectEnabledAgentModels,collectConfiguredAgentModels:()=>collectConfiguredAgentModels,checkSingleModelResolution:()=>checkSingleModelResolution,_internals:()=>_internals82,VERIFIED_KEYLESS_MODEL_ROSTER:()=>VERIFIED_KEYLESS_MODEL_ROSTER,PROVIDER_LIST_TIMEOUT_MS:()=>PROVIDER_LIST_TIMEOUT_MS});function splitModelId(model){let separator=model.indexOf("/");if(separator<=0||separator===model.length-1)return null;return{provider:model.slice(0,separator),model:model.slice(separator+1)}}function collectConfiguredAgentModels(config3){let collected=[],overriddenAgents=new Set,overrides2=config3?.agents??{};for(let[agent,override]of Object.entries(overrides2)){if(typeof override?.model==="string"&&override.model.trim())collected.push({agent,model:override.model.trim(),source:"override"}),overriddenAgents.add(agent);for(let fallback of override?.fallback_models??[])if(typeof fallback==="string"&&fallback.trim())collected.push({agent,model:fallback.trim(),source:"fallback"})}for(let[agent,model]of Object.entries(DEFAULT_MODELS)){if(overriddenAgents.has(agent))continue;collected.push({agent,model,source:"default"})}return collected}function enumerateEnabledAgentRoles(config3){let names=[],emitSwarm=(swarmId,isDefault)=>{let prefix=isDefault?"":`${swarmId}_`,swarmAgents=config3?.swarms?.[swarmId]?.agents,merged=config3?.agents?{...config3.agents,...swarmAgents??{}}:swarmAgents??{};for(let role of ALWAYS_ON_ROLES){if(merged?.[role]?.disabled===!0)continue;names.push(`${prefix}${role}`)}for(let[role,flagEnabled]of FEATURE_GATED_ROLES){if(!flagEnabled(config3))continue;if(merged?.[role]?.disabled===!0)continue;names.push(`${prefix}${role}`)}},swarms=config3?.swarms;if(swarms&&Object.keys(swarms).length>0)for(let swarmId of Object.keys(swarms))emitSwarm(swarmId,swarmId==="default");else emitSwarm("default",!0);return names}function collectEnabledAgentModels(config3,opts){let names=opts?.generatedAgentNames&&opts.generatedAgentNames.length>0?[...opts.generatedAgentNames]:enumerateEnabledAgentRoles(config3),primaryNames=opts?.registeredAgents?new Set(Object.entries(opts.registeredAgents).filter(([,value])=>value?.mode==="primary").map(([name])=>name)):resolvePrimaryAgentNames(names,config3?.default_agent).primaryNames,collected=[];for(let name of names){let mode=primaryNames.has(name)?"primary":"subagent",effective=config3?resolveEffectiveAgentOverride(config3,name):void 0,configuredModel=config3?resolveConfiguredAgentModel(config3,name):void 0,finalModel=config3?resolveRegisteredAgentModel(config3,name):DEFAULT_MODELS[stripKnownSwarmPrefix(name)]??DEFAULT_MODELS.default;if(effective&&typeof effective.model==="string"&&effective.model.trim()==="")collected.push({agent:name,model:"",source:"override",mode});else collected.push({agent:name,model:finalModel??"",source:configuredModel!==void 0?"override":"default",mode});for(let fallback of effective?.fallbackModels??[])if(typeof fallback==="string"&&fallback.trim())collected.push({agent:name,model:fallback.trim(),source:"fallback",mode})}return collected}function invalidateProviderCatalogCache(){catalogCacheEpoch++,catalogCacheByClient=new WeakMap}function sanitizePreflightText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}async function fetchProviderCatalog(client){if(!client)return null;let cached3=catalogCacheByClient.get(client);if(cached3&&Date.now()-cached3.fetchedAt<CATALOG_CACHE_TTL_MS)return cached3.catalog;let epochAtFetchStart=catalogCacheEpoch,response;try{response=await _internals82.providerList(client)}catch{return null}let all=response?.data?.all;if(!Array.isArray(all))return null;let catalog2=new Map;for(let provider of all){if(typeof provider?.id!=="string")continue;let models=new Set;if(provider.models&&typeof provider.models==="object"&&!Array.isArray(provider.models))for(let modelKey of Object.keys(provider.models))models.add(modelKey);catalog2.set(provider.id,models)}if(epochAtFetchStart===catalogCacheEpoch)catalogCacheByClient.set(client,{fetchedAt:Date.now(),catalog:catalog2});return catalog2}function resolveAgainstCatalog(models,catalog2){let classifySelection=(entry)=>{if(entry.model.trim()==="")return{...entry,status:"missing-selection",detail:"enabled role has no final model selection: the exact agent target resolved to no configured model and no default (blank model override or a stale swarm registry entry). Fix agents.<role>.model in opencode-swarm.json — the matching swarm override wins over the top-level entry."};if(entry.mode==="primary")return{...entry,status:"host-controlled",detail:"primary agent: OpenCode UI owns the model selection; the registered model is intentionally not applied"};let split=splitModelId(entry.model);if(!split)return{...entry,status:"unknown",detail:"model id has no provider prefix; resolution not checked against the catalog"};let providerModels=catalog2?.get(split.provider);if(providerModels===void 0)return{...entry,status:"unresolved",detail:`provider "${split.provider}" is not present in the provider catalog`};if(!providerModels.has(split.model))return{...entry,status:"unresolved",detail:`provider "${split.provider}" does not list model "${split.model}"`};return{...entry,status:"ok"}};if(catalog2===null)return{catalogAvailable:!1,resolutions:models.map((entry)=>entry.model.trim()===""?classifySelection(entry):{...entry,status:"unknown",detail:"provider catalog unavailable; model resolution not checked"})};return{catalogAvailable:!0,resolutions:models.map(classifySelection)}}function formatModelPreflightWarning(result){let reportable=result.resolutions.filter((resolution)=>resolution.status==="unresolved"||resolution.status==="missing-selection");if(reportable.length===0)return null;let lines=reportable.map((resolution)=>{let label=resolution.source==="fallback"?`${sanitizePreflightText(resolution.agent)} (fallback entry)`:sanitizePreflightText(resolution.agent);if(resolution.status==="missing-selection")return` ${label}: no final model selection — ${sanitizePreflightText(resolution.detail??"")}`;return` ${label}: ${sanitizePreflightText(resolution.model)} (${sanitizePreflightText(resolution.detail??"does not resolve")})`});return`[opencode-swarm] WARNING: ${reportable.length} enabled agent model selection(s) failed preflight:
1240
1240
  ${lines.join(`
1241
1241
  `)}
1242
- Dispatching these roles will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json — the matching swarm override wins over top-level agents.<role>.model. "+"fallback_models entries only serve transient runtime failures; configure a resolvable primary model for the affected role."}async function runModelPreflight(config3,client,opts){let models=collectEnabledAgentModels(config3,opts),catalog2=await fetchProviderCatalog(client);return resolveAgainstCatalog(models,catalog2)}async function checkSingleModelResolution(model,client){let catalog2=await fetchProviderCatalog(client);if(catalog2===null)return"unknown";let split=splitModelId(model);if(!split)return"unknown";let providerModels=catalog2.get(split.provider);if(providerModels===void 0||!providerModels.has(split.model))return"unresolved";return"ok"}var PROVIDER_LIST_TIMEOUT_MS=2000,FEATURE_GATED_ROLES,ALWAYS_ON_ROLES,CATALOG_CACHE_TTL_MS=30000,catalogCacheByClient,catalogCacheEpoch=0,_internals82;var init_model_preflight=__esm(()=>{init_agents2();init_agent_model();init_constants();init_schema();FEATURE_GATED_ROLES=new Map([["council_generalist",(c)=>c?.council?.general?.enabled===!0],["council_skeptic",(c)=>c?.council?.general?.enabled===!0],["council_domain_expert",(c)=>c?.council?.general?.enabled===!0],["docs_design",(c)=>c?.design_docs?.enabled===!0],["designer",(c)=>c?.ui_review?.enabled===!0]]),ALWAYS_ON_ROLES=ALL_AGENT_NAMES.filter((role)=>!FEATURE_GATED_ROLES.has(role));catalogCacheByClient=new WeakMap;_internals82={providerList:async(client)=>{let timer;try{return await Promise.race([client.provider.list(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("provider list timed out")),PROVIDER_LIST_TIMEOUT_MS)})])}finally{if(timer)clearTimeout(timer)}}}});var exports_task_envelope={};__export(exports_task_envelope,{parseTaskEnvelope:()=>parseTaskEnvelope,extractDispatchIds:()=>extractDispatchIds});function parseTaskEnvelope(text){if(typeof text!=="string"||text.length===0)return null;let match=text.match(TASK_ENVELOPE_RE);if(!match)return null;let sessionId=match[1],rawState=match[2],state2=rawState==="canceled"?"cancelled":rawState;if(!sessionId)return null;let summary=extractTagText(text,"summary"),resultRaw=state2==="error"||state2==="cancelled"?extractTagText(text,"task_error")??extractTagText(text,"task_result"):extractTagText(text,"task_result"),bounded=boundEnvelopeText(resultRaw);return{sessionId,state:state2,...summary!==void 0?{summary}:{},...state2==="error"||state2==="cancelled"?{...bounded?{errorText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}:{},...state2!=="error"&&state2!=="cancelled"&&bounded?{resultText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}}function extractTagText(text,tag){let re=new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),match=text.match(re);if(!match)return;return match[1]}function boundEnvelopeText(text){if(text===void 0)return;if(text.length<=20000)return{text,chars:text.length,truncated:!1};let suffix=`
1242
+ Dispatching these roles will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json — the matching swarm override wins over top-level agents.<role>.model. "+"fallback_models entries only serve transient runtime failures; configure a resolvable primary model for the affected role."}async function runModelPreflight(config3,client,opts){let models=collectEnabledAgentModels(config3,opts),catalog2=await fetchProviderCatalog(client);return resolveAgainstCatalog(models,catalog2)}async function checkSingleModelResolution(model,client){let catalog2=await fetchProviderCatalog(client);if(catalog2===null)return"unknown";let split=splitModelId(model);if(!split)return"unknown";let providerModels=catalog2.get(split.provider);if(providerModels===void 0||!providerModels.has(split.model))return"unresolved";return"ok"}function collectModelRosterWarnings(models,roster){let known=new Set(roster),toCheck=[];if(Array.isArray(models))toCheck.push(...models);else if(models&&typeof models==="object")for(let entry of Object.values(models)){if(!entry||typeof entry!=="object")continue;if(typeof entry.model==="string"&&entry.model.length>0)toCheck.push(entry.model);for(let fb of entry.fallback_models??[])if(typeof fb==="string"&&fb.length>0)toCheck.push(fb)}let seen=new Set,warnings=[];for(let model of toCheck){if(seen.has(model))continue;if(seen.add(model),!model.startsWith("opencode/"))continue;if(!known.has(model))warnings.push(`[opencode-swarm] model preflight: ${model} is not in the verified opencode zen keyless roster (tests/fixtures/opencode-zen-keyless-roster.json); if this is a zen free-tier id, delegation will fail with "Model unavailable" until the roster/constants are refreshed.`)}return warnings}var PROVIDER_LIST_TIMEOUT_MS=2000,FEATURE_GATED_ROLES,ALWAYS_ON_ROLES,CATALOG_CACHE_TTL_MS=30000,catalogCacheByClient,catalogCacheEpoch=0,VERIFIED_KEYLESS_MODEL_ROSTER,_internals82;var init_model_preflight=__esm(()=>{init_agents2();init_agent_model();init_constants();init_schema();FEATURE_GATED_ROLES=new Map([["council_generalist",(c)=>c?.council?.general?.enabled===!0],["council_skeptic",(c)=>c?.council?.general?.enabled===!0],["council_domain_expert",(c)=>c?.council?.general?.enabled===!0],["docs_design",(c)=>c?.design_docs?.enabled===!0],["designer",(c)=>c?.ui_review?.enabled===!0]]),ALWAYS_ON_ROLES=ALL_AGENT_NAMES.filter((role)=>!FEATURE_GATED_ROLES.has(role));catalogCacheByClient=new WeakMap;VERIFIED_KEYLESS_MODEL_ROSTER=["opencode/big-pickle","opencode/longcat-2.5-preview-free","opencode/nemotron-3-ultra-free","opencode/space-bunny-free","opencode/mimo-v2.6-flash-free","opencode/fledge-alpha-free","opencode/nemotron-3.5-lightning-free","opencode/muse-spark-1.3-contributor-free"];_internals82={providerList:async(client)=>{let timer;try{return await Promise.race([client.provider.list(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("provider list timed out")),PROVIDER_LIST_TIMEOUT_MS)})])}finally{if(timer)clearTimeout(timer)}}}});var exports_task_envelope={};__export(exports_task_envelope,{parseTaskEnvelope:()=>parseTaskEnvelope,extractDispatchIds:()=>extractDispatchIds});function parseTaskEnvelope(text){if(typeof text!=="string"||text.length===0)return null;let match=text.match(TASK_ENVELOPE_RE);if(!match)return null;let sessionId=match[1],rawState=match[2],state2=rawState==="canceled"?"cancelled":rawState;if(!sessionId)return null;let summary=extractTagText(text,"summary"),resultRaw=state2==="error"||state2==="cancelled"?extractTagText(text,"task_error")??extractTagText(text,"task_result"):extractTagText(text,"task_result"),bounded=boundEnvelopeText(resultRaw);return{sessionId,state:state2,...summary!==void 0?{summary}:{},...state2==="error"||state2==="cancelled"?{...bounded?{errorText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}:{},...state2!=="error"&&state2!=="cancelled"&&bounded?{resultText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}}function extractTagText(text,tag){let re=new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),match=text.match(re);if(!match)return;return match[1]}function boundEnvelopeText(text){if(text===void 0)return;if(text.length<=20000)return{text,chars:text.length,truncated:!1};let suffix=`
1243
1243
  [... ${text.length-20000} chars truncated by task-envelope ...]`,maxContent=Math.max(0,20000-suffix.length);return{text:`${text.slice(0,maxContent)}${suffix}`,chars:text.length,truncated:!0}}function extractDispatchIds(output){let subagentSessionId=null,jobId=null;if(typeof output==="object"&&output!==null){let o=output,metadata=o.metadata;if(typeof metadata==="object"&&metadata!==null){let rawJobId=metadata.jobId;if(typeof rawJobId==="string"&&rawJobId.length>0)jobId=rawJobId}let rendered=o.output,envelope=parseTaskEnvelope(typeof rendered==="string"?rendered:void 0);if(envelope&&envelope.state==="running")subagentSessionId=envelope.sessionId}else if(typeof output==="string"){let envelope=parseTaskEnvelope(output);if(envelope&&envelope.state==="running")subagentSessionId=envelope.sessionId}if(!subagentSessionId&&jobId)subagentSessionId=jobId;return{subagentSessionId,jobId}}var TASK_ENVELOPE_RE;var init_task_envelope=__esm(()=>{TASK_ENVELOPE_RE=/<task\s+id="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"\s*>/});import*as fs60 from"node:fs";import*as path97 from"node:path";function exactProvisioningOwnerForBackgroundDescriptor(owner){if(owner?.reservationId===void 0||owner.generation===void 0||owner.branchName===void 0)return;return{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}}function clearPendingCoderScope(){pendingCoderScopeByTaskId.clear()}async function prepareCoderScope(directory,input,args2){let rawTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"";if(isStrictTaskId(rawTaskId)){let resolvedFeedbackScope=await resolvePrFeedbackScopeDeclaration(directory,input.sessionID,rawTaskId);if(resolvedFeedbackScope){let directives2=extractTaskFileDirectives(args2);if(directives2.present&&!directives2.files)throw Error("SCOPE_NOT_DECLARED: FILE: directives are present but empty or ambiguous; provide one complete relative path per FILE: line.");let resolved2=resolveCoderScopeSources({explicitFiles:resolvedFeedbackScope.files,planFiles:null,fileDirectiveFiles:directives2.files});if(!resolved2.ok)throw Error(formatCoderScopeConflict(resolved2));await _internals84.beforePrFeedbackScopeConsume?.();let feedbackScope=await consumePrFeedbackScopeDeclaration(directory,input.sessionID,rawTaskId,input.callID,resolvedFeedbackScope);if(!feedbackScope)throw Error("SCOPE_NOT_DECLARED: PR-feedback scope could not be reserved by this Task invocation (the declaration was replaced, the workflow left PR_FEEDBACK, or its revision changed).");let binding2=createPrFeedbackScopeBinding({directory,taskId:rawTaskId,files:resolved2.files,ownerSessionId:input.sessionID,ownerMessageId:input.callID,dispatchCallId:input.callID,activation:"pending_child",workflowSessionId:input.sessionID,workflowRevisionDigest:feedbackScope.revisionDigest});if(!binding2)throw Error("SCOPE_NOT_DECLARED: PR-feedback scope could not be bound to this Task invocation.");return{kind:"pr_feedback",plan:null,taskId:rawTaskId,declaredFiles:resolved2.files,binding:binding2}}}let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path97.join(directory,".swarm","plan.json");throw Error(`SCOPE_NOT_DECLARED: no valid plan found at ${planPath} (file missing or invalid). Declare a plan via save_plan or run /swarm plan first.`)}let planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases),taskId=resolveDelegatedPlanTaskId(args2,toTaskIdPlanContextOptions(planTaskIdContext));if(!taskId)throw Error(`SCOPE_NOT_DECLARED: ${describeCoderScopeFailure(args2,planTaskIdContext)}`);let declaredFilesForTask=getPlanTaskDeclaredFiles(plan,taskId);if(!declaredFilesForTask){let known=planTaskIdContext.status==="available"?[...planTaskIdContext.taskIds].sort().join(", ")||"(none)":"(omitted: plan task context over limit)";throw Error(`SCOPE_NOT_DECLARED: task_id "${taskId}" does not match any known plan task id. Known: ${known}. Update the dispatch or revise the plan.`)}let directives=extractTaskFileDirectives(args2);if(directives.present&&!directives.files)throw Error("SCOPE_NOT_DECLARED: FILE: directives are present but empty or ambiguous; provide one complete relative path per FILE: line.");let explicitResolution=resolveScopeBindingFromDisk({directory,plan,taskId,ownerSessionId:input.sessionID,requireDeclaration:!0,includeExpired:!0});if(explicitResolution.status==="ambiguous"||explicitResolution.status==="expired"||explicitResolution.status==="overloaded")throw Error(formatScopeResolutionDiagnostic({resolution:explicitResolution,taskId,sessionId:input.sessionID})??"SCOPE_NOT_DECLARED: durable declaration resolution failed.");let explicitBinding=explicitResolution.status==="found"?explicitResolution.binding:null,resolved=resolveCoderScopeSources({explicitFiles:explicitBinding?.files,planFiles:declaredFilesForTask,fileDirectiveFiles:directives.files});if(!resolved.ok)throw Error(formatCoderScopeConflict(resolved));let binding=createScopeBinding({directory,plan,taskId,files:resolved.files,ownerSessionId:input.sessionID,ownerMessageId:input.callID,dispatchCallId:input.callID,activation:"pending_child",source:resolved.source});if(!binding)throw Error("SCOPE_NOT_DECLARED: coder scope could not be bound to this Task invocation.");return{kind:"plan",plan,taskId,declaredFiles:resolved.files,binding}}function isBackgroundTrue(value){return value===!0||value==="true"}function outputLooksLikeBackgroundRunning(output){if(typeof output!=="object"||output===null)return!1;let o=output;if(o.state==="running")return!0;let metadata=o.metadata;return typeof metadata==="object"&&metadata!==null&&metadata.background===!0}function isEnvelope(obj){if(typeof obj!=="object"||obj===null)return!1;let e=obj;return typeof e.taskId==="string"&&typeof e.targetAgent==="string"&&typeof e.action==="string"}function parseDelegationEnvelope(content,directory){let validateEnvelopePaths=(envelope2)=>{if(directory)for(let filePath of envelope2.files){try{validateSwarmPath(directory,filePath)}catch{return null}let resolvedPath=path97.resolve(directory,filePath);if(!fs60.existsSync(resolvedPath))return null}return envelope2};try{let parsed=JSON.parse(content);if(isEnvelope(parsed))return validateEnvelopePaths(parsed)}catch{let match=content.match(/\{[\s\S]*\}/);if(match)try{let parsed=JSON.parse(match[0]);if(isEnvelope(parsed))return validateEnvelopePaths(parsed)}catch{}}let lines=content.split(`
1244
1244
  `),keyValueMap={};for(let line of lines){let match=line.match(/^([^:]+):\s*(.+)$/);if(match){let key2=match[1].trim().toLowerCase(),value=match[2].trim();keyValueMap[key2]=value}}let keyNormalization={taskid:"taskId",task_id:"taskId",targetagent:"targetAgent",target_agent:"targetAgent",commandtype:"commandType",command_type:"commandType",acceptancecriteria:"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",technicalcontext:"technicalContext",technical_context:"technicalContext",errorstrategy:"errorStrategy",error_strategy:"errorStrategy",platformnotes:"platformNotes",platform_notes:"platformNotes",action:"action",files:"files"},normalizedMap={};for(let[key2,value]of Object.entries(keyValueMap)){let normalized=keyNormalization[key2]||key2;normalizedMap[normalized]=value}if(Object.keys(normalizedMap).length<3)return null;let requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!normalizedMap[field])return null;let parseArrayField=(value)=>{let parts=value.split(",");if(parts.length===1)parts=value.split(";");return parts.map((s)=>s.trim()).filter((s)=>s.length>0)},envelope={taskId:normalizedMap.taskId,targetAgent:normalizedMap.targetAgent,action:normalizedMap.action,commandType:normalizedMap.commandType,files:parseArrayField(normalizedMap.files),acceptanceCriteria:parseArrayField(normalizedMap.acceptanceCriteria),technicalContext:normalizedMap.technicalContext||""};if(normalizedMap.technicalContext)envelope.technicalContext=normalizedMap.technicalContext;if(normalizedMap.errorStrategy)envelope.errorStrategy=normalizedMap.errorStrategy;if(normalizedMap.platformNotes)envelope.platformNotes=normalizedMap.platformNotes;return validateEnvelopePaths(envelope)}function validateDelegationEnvelope(envelope,context){if(typeof envelope!=="object"||envelope===null)return{valid:!1,reason:"envelope_not_object"};let e=envelope,requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!(field in e)||e[field]===void 0||e[field]===null)return{valid:!1,reason:`missing_field_${field}`};if(e.commandType==="slash_command")return{valid:!1,reason:"slash_command_delegation_blocked"};let taskId=e.taskId;if(context.planTasks.length>0&&!context.planTasks.includes(taskId))return{valid:!1,reason:"taskId_not_in_plan"};let rawAgent=e.targetAgent,normalizedAgent=stripKnownSwarmPrefix(rawAgent);if(!context.validAgents.includes(normalizedAgent))return{valid:!1,reason:"invalid_target_agent"};let{action,files}=e;if((action==="implement"||action==="review")&&(!Array.isArray(files)||files.length===0))return{valid:!1,reason:"files_required_for_action"};let acceptanceCriteria=e.acceptanceCriteria;if(!Array.isArray(acceptanceCriteria)||acceptanceCriteria.length===0)return{valid:!1,reason:"acceptanceCriteria_required"};if("specCriteria"in e&&e.specCriteria!==void 0&&e.specCriteria!==null){let spec=e.specCriteria;if(typeof spec!=="object"||Array.isArray(spec))return{valid:!1,reason:"specCriteria_malformed"};let specObj=spec;for(let member of["fr","sc","acceptance"]){let value=specObj[member];if(value===void 0||value===null)continue;if(!Array.isArray(value)||!value.every((entry)=>typeof entry==="string"))return{valid:!1,reason:`specCriteria_${member}_malformed`}}}return{valid:!0}}function appendDelegationEnvelopeAdvisory(session,promptText,context){try{let envelope=parseDelegationEnvelope(promptText);if(!envelope)return null;let result=validateDelegationEnvelope(envelope,context);if(!result.valid)pushAdvisory(session,`DELEGATION ENVELOPE ADVISORY: a parsed delegation envelope failed validation (${result.reason}). `+"This is advisory-only — the delegation was NOT blocked. Review the envelope's structured "+"fields (including the optional specCriteria acceptance/FR/SC arrays) before the next dispatch.");return result}catch{return null}}function validateCoderReviewerAcceptanceField(promptText){let lines=promptText.split(/\r?\n/),headerRe=/^ACCEPTANCE:[ \t]*(.*)$/i,nextFieldRe=/^[A-Z][A-Z0-9_]*:/;for(let i=0;i<lines.length;i++){let match=headerRe.exec(lines[i]);if(!match)continue;if(match[1].trim().length>0)return{valid:!0};for(let j=i+1;j<lines.length;j++){if(nextFieldRe.test(lines[j]))break;if(lines[j].trim().length>0)return{valid:!0}}return{valid:!1,reason:"acceptance_field_empty"}}return{valid:!1,reason:"acceptance_field_missing"}}function extractSpecRequirementBodyById(specText,id){if(!id||id.trim().length===0)return null;let escapedId=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lines=specText.split(/\r?\n/),headerRe=new RegExp(`^\\s*[-*]?\\s*\\*\\*\\s*${escapedId}\\b`),headerIdx=-1;for(let i=0;i<lines.length;i++)if(headerRe.test(lines[i])){headerIdx=i;break}if(headerIdx===-1)return null;let headerLine=lines[headerIdx],openIdx=headerLine.indexOf("**"),closeIdx=openIdx===-1?-1:headerLine.indexOf("**",openIdx+2);if(closeIdx===-1)return null;let body=headerLine.slice(closeIdx+2);for(let i=headerIdx+1;i<lines.length;i++){let line=lines[i];if(line.trim().length===0)break;if(/^#/.test(line))break;if(/^\s*[-*]\s/.test(line))break;if(/^\s*[-*]?\s*\*\*\s*(?:FR|SC)-/.test(line))break;body+=` ${line}`}return body}function normalizeAcceptanceText(s){return s.normalize("NFC").replace(/`/g,"").replace(/\*\*/g,"").replace(/\*/g,"").replace(/^[ \t]*[-*][ \t]+/gm,"").replace(/[‘’]/g,"'").replace(/[“”]/g,'"').replace(/[—–]/g,"-").replace(/-{2,}/g,"-").replace(/Â?§/g," section ").replace(/\s+/g," ").trim().toLowerCase()}function longestCommonSuffixLength(expected,acceptance,maxScan){let len=0,cap=Math.min(expected.length,maxScan);while(len<cap&&acceptance.includes(expected.slice(expected.length-len-1)))len++;return len}function describeCoverageMiss(params){let{normalizedExpected,normalizedAcceptance}=params,divergenceOffset=0,maxScan=Math.min(normalizedExpected.length,COVERAGE_DIAG_MAX_SCAN);while(divergenceOffset<maxScan&&normalizedAcceptance.includes(normalizedExpected.slice(0,divergenceOffset+1)))divergenceOffset++;let raw=`${params.rawExpectedBody}
1245
1245
  ${params.rawAcceptanceText}`,corruptionHint;if(/�/.test(raw))corruptionHint="the text contains U+FFFD (the Unicode replacement char), a sign spec.md was decoded with the wrong encoding — re-save spec.md as UTF-8";else if(/\?{2,}/.test(raw))corruptionHint="the text contains a '??' run — a non-UTF-8 save can turn characters like § into ?? on disk; open .swarm/spec.md and re-type the affected character, then re-save as UTF-8";else if(/Ã.|â€|Â[^\s]/.test(raw))corruptionHint="the text contains a Latin-1 mojibake byte sequence (e.g. §, é) — re-save spec.md as UTF-8";if(divergenceOffset<COVERAGE_DIAG_MIN_PREFIX){let suffixLen=longestCommonSuffixLength(normalizedExpected,normalizedAcceptance,COVERAGE_DIAG_MAX_SCAN);if(suffixLen<COVERAGE_DIAG_MIN_PREFIX)return{expectedSnippet:normalizedExpected.slice(0,COVERAGE_DIAG_SNIPPET_CAP),foundSnippet:"",divergenceOffset:0,completelyMissing:!0,...corruptionHint?{corruptionHint}:{}};let matchedSuffix=normalizedExpected.slice(normalizedExpected.length-suffixLen),foundIdx2=normalizedAcceptance.indexOf(matchedSuffix),mismatchedHeadLen=Math.max(0,normalizedExpected.length-suffixLen),expectedSnippet2=normalizedExpected.slice(0,Math.min(mismatchedHeadLen,COVERAGE_DIAG_SNIPPET_CAP)),foundSnippet2=foundIdx2>0?normalizedAcceptance.slice(Math.max(0,foundIdx2-COVERAGE_DIAG_SNIPPET_CAP),foundIdx2):normalizedAcceptance.slice(0,Math.min(normalizedAcceptance.length,COVERAGE_DIAG_SNIPPET_CAP));return{expectedSnippet:expectedSnippet2,foundSnippet:foundSnippet2,divergenceOffset:0,...corruptionHint?{corruptionHint}:{}}}let expectedSnippet=normalizedExpected.slice(divergenceOffset,divergenceOffset+COVERAGE_DIAG_SNIPPET_CAP),matchedPrefix=normalizedExpected.slice(0,divergenceOffset),foundIdx=matchedPrefix.length>0?normalizedAcceptance.indexOf(matchedPrefix):-1,foundPos=foundIdx>=0?foundIdx+matchedPrefix.length:0,foundSnippet=normalizedAcceptance.slice(foundPos,foundPos+COVERAGE_DIAG_SNIPPET_CAP);return{expectedSnippet,foundSnippet,divergenceOffset,...corruptionHint?{corruptionHint}:{}}}function buildAcceptanceCoverageMismatchError(params){let{targetAgent,coverageTaskId,coverageResult}=params,diag=coverageResult.diagnostic,diagLines=[];if(diag){if(diag.completelyMissing)diagLines.push(` neither the leading nor the trailing ${COVERAGE_DIAG_MIN_PREFIX} characters of the requirement text were found anywhere in ACCEPTANCE (a shorter or partial match is treated as coincidental)`),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(' ACCEPTANCE has here: "[Requirement text completely missing from prompt]"');else diagLines.push(` first divergence at normalized offset ${diag.divergenceOffset}`+(diag.divergenceOffset===0?" (no aligned prefix found)":"")),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(` ACCEPTANCE has here: "${diag.foundSnippet}"`);if(diag.corruptionHint)diagLines.push(` ENCODING WARNING: ${diag.corruptionHint}`)}let rawExpectedBody=coverageResult.expectedBody??"",truncated=rawExpectedBody.length>ACCEPTANCE_EXPECTED_BODY_CAP,expectedBodyBlock=truncated?`${rawExpectedBody.slice(0,ACCEPTANCE_EXPECTED_BODY_CAP)}
@@ -1272,7 +1272,7 @@ ${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else
1272
1272
  Rule 3: ONE task per coder call. Split this into separate delegations.
1273
1273
  ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1274
1274
  `)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID,void 0,directory),councilActive=await isCouncilGateActive(directory,config3.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(isTaskTool2){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals83.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},normalizedSubagentType=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(normalizedSubagentType)),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(normalizedSubagentType)?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals84.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals84.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals84.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals83.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config3,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge);coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged",observedFiles:observedForMerge,settlementFailed:unattributedEmptyScopeMutation})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals83.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals83.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals83.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);let stageBSettlementDrops=new Map;do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state2))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state2,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){let reconstructed=_internals84.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===taskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)launchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B binding for ${taskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"unbound",detail:"ignoring unbound Stage B settlement",drops:stageBSettlementDrops});continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${state2} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"rejection_persist_failed",detail:`rejection could not be persisted: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops})}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config3.review_routing?.enforce_receipts??!0,routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_blocked",detail:`route receipt blocked: ${routeDecision.reason??"unknown reason"}`,drops:stageBSettlementDrops});continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_capacity",detail:"route evidence capacity exceeded",drops:stageBSettlementDrops});continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"evidence_rejected",detail:`gate evidence recording rejected the settlement: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops});continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB))try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(routeComplete&&targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1);flushStageBSettlementDropWarnings(stageBSettlementDrops)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},targetAgentForEvidence=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(targetAgentForEvidence));if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID);if(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"].includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0){let reconstructed=_internals84.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===evidenceTaskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)gateLaunchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B gate binding for ${evidenceTaskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(taskChangeContext?.declaredFiles,rawObservedFiles),context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&(observedFiles.length>0||unattributedEmptyScopeMutation),updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure||unattributedEmptyScopeMutation,observedFiles:rawObservedFiles})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID,sessionID)=>{if(stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),sessionID)deleteStageBDispatchBindings(directory,sessionID,callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error93){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES=4194304,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,EXPLICIT_TASK_EVIDENCE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals84,STAGE_B_SETTLEMENT_DROP_REASONS;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_stage_b_dispatch_binding_store();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_system_guidance_carrier();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]),EXPLICIT_TASK_EVIDENCE_AGENTS=new Set(["critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor"]);_internals84={recordStageBDispatchBindings,readStageBDispatchBindings,deleteStageBDispatchBindings,resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals83.provisionWorktree},set provisionWorktree(v){_internals83.provisionWorktree=v},get removeWorktree(){return _internals83.removeWorktree},set removeWorktree(v){_internals83.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals83.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals83.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals83.postMergeCleanup},set postMergeCleanup(v){_internals83.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals83.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals83.preserveBackgroundWorktreeOwnershipForCallId=v}};STAGE_B_SETTLEMENT_DROP_REASONS={unbound:"unbound launch generation (the dispatch-generation binding is process-local and was lost)",route_blocked:"review route receipt enforcement blocked the settlement",route_capacity:"route evidence capacity exceeded",evidence_rejected:"gate evidence recording rejected the settlement (generation fencing)",rejection_persist_failed:"the rejection verdict could not be persisted"}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
1275
- `)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function trajectoryStepGeneration(){return stepCounterGeneration}function bumpStepCounterGeneration(){stepCounterGeneration+=1}function evictOldestStepSessionIfNeeded(key2){if(sessionStepCounters.has(key2))return;while(sessionStepCounters.size>=MAX_TRACKED_STEP_SESSIONS){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId,directory){let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let step=(sessionStepCounters.get(key2)??0)+1;return sessionStepCounters.set(key2,step),step}function seedTrajectoryStepCounter(sessionId,directory,step){if(!Number.isFinite(step)||step<=0)return;let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let current=sessionStepCounters.get(key2)??0;if(step>current)sessionStepCounters.set(key2,Math.floor(step))}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0){let suffix=sessionKeySuffix(sessionId),removed=!1;for(let key2 of sessionStepCounters.keys())if(key2.endsWith(suffix))sessionStepCounters.delete(key2),removed=!0;if(removed)bumpStepCounterGeneration()}else if(sessionStepCounters.size>0)sessionStepCounters.clear(),bumpStepCounterGeneration()}var MAX_TRACKED_STEP_SESSIONS=500,sessionStepCounters,stepCounterGeneration=0;var init_trajectory_step_state=__esm(()=>{init_canonical_root();sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key2,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key2);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature){let next={key:key2,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current)return!1;if(expectedGeneration!==void 0&&current.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function peekScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return;return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function clearScopedModelSelectionsForSession(sessionID,opts){let normalizedSessionID=normalizeText2(sessionID),primaryScopes=opts?.primaryScopes??!0;for(let[key2,entry]of scopedModelOverrides){if(!key2.startsWith(`${normalizedSessionID}␟`))continue;if(!primaryScopes){if((key2.split("␟")[1]??"")==="")continue}scopedModelOverrides.delete(entry.key)}}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key2=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key2);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key2),routesByParentCall.set(key2,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key2)}function pruneRoutes(now){for(let[key2,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key2=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key2);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function sessionFallbackScope(input){return{sessionID:normalizeText3(input.sessionID),invocationID:PRIMARY_SESSION_INVOCATION_ID,swarmID:normalizeText3(input.swarmID)||void 0,role:normalizeText3(input.role)}}function advanceSessionFallbackSelection(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(scope,chain,now),advanced=advanceScopedModelSelection(scope,chain,selection.generation,now);return{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,scope}}function resolveSessionChatModelOverride(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]);if(chain.fallbacks.length===0)return{status:"missing"};let selection=peekScopedModelSelection(scope,chain,now);if(selection===void 0)return{status:"missing"};if(selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex}}function recordSessionChatAgent(sessionID,agentName){let session=normalizeText3(sessionID),agent=normalizeText3(agentName);if(!session||!agent)return;while(sessionChatAgentBySession.size>=MAX_SESSION_CHAT_AGENTS){let oldest=sessionChatAgentBySession.keys().next().value;if(typeof oldest!=="string")break;sessionChatAgentBySession.delete(oldest)}sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent)}function resolveSessionChatAgent(sessionID){let session=normalizeText3(sessionID);if(!session)return;let agent=sessionChatAgentBySession.get(session);if(agent===void 0)return;return sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent),agent}function clearPendingTaskModelRoutesForSession(sessionID,mode="session"){let normalizedSessionID=normalizeText3(sessionID);for(let[key2,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}if(clearScopedModelSelectionsForSession(normalizedSessionID,{primaryScopes:mode==="session"}),mode==="session")sessionChatAgentBySession.delete(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),sessionChatAgentBySession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,MAX_SESSION_CHAT_AGENTS=256,sessionChatAgentBySession,routesByParentCall,routeKeyByChildSession,PRIMARY_SESSION_INVOCATION_ID="";var init_task_model_routing=__esm(()=>{init_model_override_state();sessionChatAgentBySession=new Map,routesByParentCall=new Map,routeKeyByChildSession=new Map});function evictOldest(map3,cap){while(map3.size>=cap){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}function hydrationProjectKey(directory){let memoKey=canonicalRootKeyLexical(directory),memoized=directoryKeyMemo.get(memoKey);if(memoized!==void 0)return memoized;let key2=canonicalProjectKey(directory);if(!directoryKeyMemo.has(memoKey))evictOldest(directoryKeyMemo,MAX_DIRECTORY_KEY_MEMO);return directoryKeyMemo.set(memoKey,key2),key2}function beginHydrationScope(directory){let projectKey=hydrationProjectKey(directory),current=projectHydrationAuthorities.get(projectKey),generation=(current?.generation??0)+1;if(!current)evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let authorityEpoch=current?.authorityEpoch??nextHydrationAuthorityEpoch();return projectHydrationAuthorities.set(projectKey,{generation,authorityEpoch}),{projectKey,generation,authorityEpoch}}function currentHydrationGeneration(projectKey){return projectHydrationAuthorities.get(projectKey)?.generation??0}function captureCurrentHydrationAuthority(projectKey){let current=projectHydrationAuthorities.get(projectKey);if(current)return{projectKey,...current};let authorityEpoch=nextHydrationAuthorityEpoch();evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let record3={generation:0,authorityEpoch};return projectHydrationAuthorities.set(projectKey,record3),{projectKey,...record3}}function nextHydrationAuthorityEpoch(){if(hydrationAuthorityEpoch>=Number.MAX_SAFE_INTEGER)throw Error("hydration authority epoch exhausted");return hydrationAuthorityEpoch+=1,hydrationAuthorityEpoch}function isHydrationAuthorityCurrent(authority){let current=projectHydrationAuthorities.get(authority.projectKey);return current?.generation===authority.generation&&current.authorityEpoch===authority.authorityEpoch}function isHydrationScopeCurrent(scope){return isHydrationAuthorityCurrent(scope)}function nextSessionHydrationStamp(projectKey){return currentHydrationGeneration(projectKey)+1}function getRehydrationCache(projectKey){let entry=rehydrationCaches.get(projectKey),authority=projectHydrationAuthorities.get(projectKey);if(!entry||!authority||entry.authorityEpoch!==authority.authorityEpoch)return;return entry.cache}function setRehydrationCache(projectKey,cache2,authority){let cacheAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(cacheAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(cacheAuthority))return!1;if(!rehydrationCaches.has(projectKey))evictOldest(rehydrationCaches,MAX_TRACKED_PROJECTS);return rehydrationCaches.set(projectKey,{cache:cache2,authorityEpoch:cacheAuthority.authorityEpoch}),!0}function recordHydratedAggregateKeys(projectKey,keys,authority){let aggregateAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(aggregateAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(aggregateAuthority))return!1;if(!hydratedAggregateKeys.has(projectKey))evictOldest(hydratedAggregateKeys,MAX_TRACKED_PROJECTS);return hydratedAggregateKeys.set(projectKey,{keys:new Set(keys),authorityEpoch:aggregateAuthority.authorityEpoch}),!0}function hydratedAggregateKeysFor(projectKey,authority){let entry=hydratedAggregateKeys.get(projectKey),current=authority??projectHydrationAuthorities.get(projectKey);if(!entry||!current||entry.authorityEpoch!==current.authorityEpoch)return new Set;return entry.keys}function clearHydrationOwnershipState(){projectHydrationAuthorities.clear(),rehydrationCaches.clear(),hydratedAggregateKeys.clear(),directoryKeyMemo.clear()}var MAX_TRACKED_PROJECTS=32,MAX_DIRECTORY_KEY_MEMO=64,projectHydrationAuthorities,hydrationAuthorityEpoch=0,rehydrationCaches,hydratedAggregateKeys,directoryKeyMemo;var init_hydration_ownership=__esm(()=>{init_canonical_project();init_canonical_root();projectHydrationAuthorities=new Map,rehydrationCaches=new Map,hydratedAggregateKeys=new Map,directoryKeyMemo=new Map});import{existsSync as existsSync52,mkdirSync as mkdirSync32,readFileSync as readFileSync38,writeFileSync as writeFileSync21}from"node:fs";import*as path98 from"node:path";function recordSessionStart(directory,startMs){try{let swarmDir=path98.join(directory,".swarm"),sessionDir=path98.join(swarmDir,"session"),filePath=path98.join(sessionDir,SESSION_START_FILE),line=JSON.stringify({startMs,ts:Date.now()});mkdirSync32(sessionDir,{recursive:!0}),writeFileSync21(filePath,`${line}
1275
+ `)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function trajectoryStepGeneration(){return stepCounterGeneration}function bumpStepCounterGeneration(){stepCounterGeneration+=1}function evictOldestStepSessionIfNeeded(key2){if(sessionStepCounters.has(key2))return;while(sessionStepCounters.size>=MAX_TRACKED_STEP_SESSIONS){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId,directory){let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let step=(sessionStepCounters.get(key2)??0)+1;return sessionStepCounters.set(key2,step),step}function seedTrajectoryStepCounter(sessionId,directory,step){if(!Number.isFinite(step)||step<=0)return;let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let current=sessionStepCounters.get(key2)??0;if(step>current)sessionStepCounters.set(key2,Math.floor(step))}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0){let suffix=sessionKeySuffix(sessionId),removed=!1;for(let key2 of sessionStepCounters.keys())if(key2.endsWith(suffix))sessionStepCounters.delete(key2),removed=!0;if(removed)bumpStepCounterGeneration()}else if(sessionStepCounters.size>0)sessionStepCounters.clear(),bumpStepCounterGeneration()}var MAX_TRACKED_STEP_SESSIONS=500,sessionStepCounters,stepCounterGeneration=0;var init_trajectory_step_state=__esm(()=>{init_canonical_root();sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key2,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key2);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature){let next={key:key2,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current)return!1;if(expectedGeneration!==void 0&&current.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function peekScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return;return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function clearScopedModelSelectionsForSession(sessionID,opts){let normalizedSessionID=normalizeText2(sessionID),primaryScopes=opts?.primaryScopes??!0;for(let[key2,entry]of scopedModelOverrides){if(!key2.startsWith(`${normalizedSessionID}␟`))continue;if(!primaryScopes){if((key2.split("␟")[1]??"")==="")continue}scopedModelOverrides.delete(entry.key)}}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key2=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key2);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key2),routesByParentCall.set(key2,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key2)}function pruneRoutes(now){for(let[key2,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key2=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key2);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function sessionFallbackScope(input){return{sessionID:normalizeText3(input.sessionID),invocationID:PRIMARY_SESSION_INVOCATION_ID,swarmID:normalizeText3(input.swarmID)||void 0,role:normalizeText3(input.role)}}function advanceSessionFallbackSelection(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(scope,chain,now),advanced=advanceScopedModelSelection(scope,chain,selection.generation,now);return{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,scope}}function resolveSessionChatModelOverride(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]);if(chain.fallbacks.length===0)return{status:"missing"};let selection=peekScopedModelSelection(scope,chain,now);if(selection===void 0)return{status:"missing"};if(selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex}}function recordSessionChatAgent(sessionID,agentName){let session=normalizeText3(sessionID),agent=normalizeText3(agentName);if(!session||!agent)return;while(sessionChatAgentBySession.size>=MAX_SESSION_CHAT_AGENTS){let oldest=sessionChatAgentBySession.keys().next().value;if(typeof oldest!=="string")break;sessionChatAgentBySession.delete(oldest)}sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent)}function resolveSessionChatAgent(sessionID){let session=normalizeText3(sessionID);if(!session)return;let agent=sessionChatAgentBySession.get(session);if(agent===void 0)return;return sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent),agent}function clearPendingTaskModelRoutesForSession(sessionID,mode="session"){let normalizedSessionID=normalizeText3(sessionID);for(let[key2,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}if(clearScopedModelSelectionsForSession(normalizedSessionID,{primaryScopes:mode==="session"}),mode==="session")sessionChatAgentBySession.delete(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),sessionChatAgentBySession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,MAX_SESSION_CHAT_AGENTS=256,sessionChatAgentBySession,routesByParentCall,routeKeyByChildSession,PRIMARY_SESSION_INVOCATION_ID="";var init_task_model_routing=__esm(()=>{init_model_override_state();sessionChatAgentBySession=new Map,routesByParentCall=new Map,routeKeyByChildSession=new Map});function evictOldest(map3,cap){while(map3.size>=cap){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}function hydrationProjectKey(directory){let memoKey=canonicalRootKeyLexical(directory),memoized=directoryKeyMemo.get(memoKey);if(memoized!==void 0)return memoized;let key2=canonicalProjectKey(directory);if(!directoryKeyMemo.has(memoKey))evictOldest(directoryKeyMemo,MAX_DIRECTORY_KEY_MEMO);return directoryKeyMemo.set(memoKey,key2),key2}function beginHydrationScope(directory){let projectKey=hydrationProjectKey(directory),current=projectHydrationAuthorities.get(projectKey),generation=(current?.generation??0)+1;if(!current)evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let authorityEpoch=current?.authorityEpoch??nextHydrationAuthorityEpoch();return projectHydrationAuthorities.set(projectKey,{generation,authorityEpoch}),{projectKey,generation,authorityEpoch}}function currentHydrationGeneration(projectKey){return projectHydrationAuthorities.get(projectKey)?.generation??0}function captureCurrentHydrationAuthority(projectKey){let current=projectHydrationAuthorities.get(projectKey);if(current)return{projectKey,...current};let authorityEpoch=nextHydrationAuthorityEpoch();evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let record3={generation:0,authorityEpoch};return projectHydrationAuthorities.set(projectKey,record3),{projectKey,...record3}}function nextHydrationAuthorityEpoch(){if(hydrationAuthorityEpoch>=Number.MAX_SAFE_INTEGER)throw Error("hydration authority epoch exhausted");return hydrationAuthorityEpoch+=1,hydrationAuthorityEpoch}function isHydrationAuthorityCurrent(authority){let current=projectHydrationAuthorities.get(authority.projectKey);return current?.generation===authority.generation&&current.authorityEpoch===authority.authorityEpoch}function isHydrationScopeCurrent(scope){return isHydrationAuthorityCurrent(scope)}function nextSessionHydrationStamp(projectKey){return currentHydrationGeneration(projectKey)+1}function getRehydrationCache(projectKey){let entry=rehydrationCaches.get(projectKey),authority=projectHydrationAuthorities.get(projectKey);if(!entry||!authority||entry.authorityEpoch!==authority.authorityEpoch)return;return entry.cache}function setRehydrationCache(projectKey,cache2,authority){let cacheAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(cacheAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(cacheAuthority))return!1;if(!rehydrationCaches.has(projectKey))evictOldest(rehydrationCaches,MAX_TRACKED_PROJECTS);return rehydrationCaches.set(projectKey,{cache:cache2,authorityEpoch:cacheAuthority.authorityEpoch}),!0}function recordHydratedAggregateKeys(projectKey,keys,authority){let aggregateAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(aggregateAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(aggregateAuthority))return!1;if(!hydratedAggregateKeys.has(projectKey))evictOldest(hydratedAggregateKeys,MAX_TRACKED_PROJECTS);return hydratedAggregateKeys.set(projectKey,{keys:new Set(keys),authorityEpoch:aggregateAuthority.authorityEpoch}),!0}function hydratedAggregateKeysFor(projectKey,authority){let entry=hydratedAggregateKeys.get(projectKey),current=authority??projectHydrationAuthorities.get(projectKey);if(!entry||!current||entry.authorityEpoch!==current.authorityEpoch)return new Set;return entry.keys}function clearHydrationOwnershipState(){projectHydrationAuthorities.clear(),rehydrationCaches.clear(),hydratedAggregateKeys.clear(),directoryKeyMemo.clear()}var MAX_TRACKED_PROJECTS=32,MAX_DIRECTORY_KEY_MEMO=64,projectHydrationAuthorities,hydrationAuthorityEpoch=0,rehydrationCaches,hydratedAggregateKeys,directoryKeyMemo;var init_hydration_ownership=__esm(()=>{init_canonical_project();init_canonical_root();projectHydrationAuthorities=new Map,rehydrationCaches=new Map,hydratedAggregateKeys=new Map,directoryKeyMemo=new Map});import{existsSync as existsSync52,mkdirSync as mkdirSync32,readFileSync as readFileSync38,writeFileSync as writeFileSync21}from"node:fs";import*as path98 from"node:path";function recordSessionStart(directory,startMs){try{let swarmDir=path98.join(directory,".swarm"),sessionDir=path98.join(swarmDir,"session"),filePath=path98.join(sessionDir,SESSION_START_FILE),line=JSON.stringify({startMs,ts:Date.now()});mkdirSync32(sessionDir,{recursive:!0}),writeFileSync21(filePath,`${line}
1276
1276
  `,{flag:"a"})}catch{}}function readEarliestSessionStart(directory){try{let filePath=path98.join(directory,".swarm","session",SESSION_START_FILE);if(!existsSync52(filePath))return null;let lines=readFileSync38(filePath,"utf-8").split(`
1277
1277
  `),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{randomUUID as randomUUID12}from"node:crypto";function parseRecordPayload(payload,label){let parsed=JSON.parse(payload);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`Invalid SQLite snapshot ${label} payload`);return parsed}function claimSnapshotSessionOwnership(sessionId,canTakeOver=!1){let existing=localSessionOwners.get(sessionId);if(existing){if(canTakeOver)existing.canTakeOver=!0;return existing.token}let token=randomUUID12();return localSessionOwners.set(sessionId,{token,canTakeOver}),token}function isSnapshotSessionOwnedLocally(sessionId){return localSessionOwners.has(sessionId)}function releaseSnapshotSessionOwnership(sessionId){localSessionOwners.delete(sessionId)}function clearSnapshotSessionOwnerships(){localSessionOwners.clear()}function nextGeneration(directory,namespace,entityKey){return(getCoordinationState(directory,namespace,entityKey)?.generation??0)+1}function writeSnapshotRows(directory,snapshot,options={}){withCoordinationTransaction(directory,()=>{transitionCoordinationState(directory,{namespace:META_NAMESPACE,entityKey:"project",generation:nextGeneration(directory,META_NAMESPACE,"project"),status:"active",payload:JSON.stringify({version:snapshot.version,writtenAt:snapshot.writtenAt,workflowSchema:snapshot.workflowSchema})});for(let[key2,aggregate]of Object.entries(snapshot.toolAggregates))transitionCoordinationState(directory,{namespace:TOOL_NAMESPACE,entityKey:key2,generation:nextGeneration(directory,TOOL_NAMESPACE,key2),status:"active",payload:JSON.stringify(aggregate)});for(let[sessionId,agentName]of Object.entries(snapshot.activeAgent)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,ACTIVE_AGENT_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:ACTIVE_AGENT_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,ACTIVE_AGENT_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(agentName)})}for(let[sessionId,chain]of Object.entries(snapshot.delegationChains)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,DELEGATION_CHAIN_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:DELEGATION_CHAIN_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,DELEGATION_CHAIN_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(chain)})}for(let[sessionId,session]of Object.entries(snapshot.agentSessions)){let localOwner=localSessionOwners.get(sessionId),ownerToken=localOwner?.token;if(options.onlyLocallyOwnedSessions&&!localOwner)continue;let current=getCoordinationState(directory,SESSION_NAMESPACE,sessionId),currentOwner2,deleted=null;try{if(current?.status==="deleted")deleted=JSON.parse(current.payload);else if(current)currentOwner2=JSON.parse(current.payload).ownerToken}catch{continue}if(options.onlyLocallyOwnedSessions&&currentOwner2&&currentOwner2!==ownerToken&&!localOwner?.canTakeOver)continue;if(deleted&&(!ownerToken||deleted.reason!=="stale"||deleted.ownerToken!==ownerToken))continue;let payload={session,...ownerToken?{ownerToken}:{}};transitionCoordinationState(directory,{namespace:SESSION_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,SESSION_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(payload)})}})}function importSnapshotRowsOnce(directory,snapshot,sourceDigest,source="session/state.json"){return importCoordinationOnce(directory,{source,sourceDigest,rowCount:Object.keys(snapshot.agentSessions).length,emptyNamespace:META_NAMESPACE},()=>writeSnapshotRows(directory,snapshot))}function readSnapshotRows(directory){if(!projectDbExists(directory))return null;return withCoordinationTransaction(directory,()=>{let meta3=listCoordinationStates(directory,META_NAMESPACE,1)[0];if(!meta3)return null;_snapshotStoreInternals.afterSnapshotMetaRead();let parsedMeta=parseRecordPayload(meta3.payload,"metadata");if(parsedMeta.version!==1&&parsedMeta.version!==2&&parsedMeta.version!==3)throw Error("Unsupported SQLite snapshot version");if(!Number.isFinite(parsedMeta.writtenAt))throw Error("Invalid SQLite snapshot metadata writtenAt");if(parsedMeta.workflowSchema!==void 0&&typeof parsedMeta.workflowSchema!=="string")throw Error("Invalid SQLite snapshot metadata workflowSchema");let snapshot={version:parsedMeta.version,writtenAt:parsedMeta.writtenAt,...parsedMeta.workflowSchema!==void 0&&{workflowSchema:parsedMeta.workflowSchema},toolAggregates:{},activeAgent:{},delegationChains:{},agentSessions:{}};for(let row of listCoordinationStates(directory,TOOL_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS))snapshot.toolAggregates[row.entityKey]=parseRecordPayload(row.payload,"tool aggregate");for(let row of listCoordinationStates(directory,ACTIVE_AGENT_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let agentName=JSON.parse(row.payload);if(typeof agentName!=="string")throw Error("Invalid SQLite snapshot active-agent payload");snapshot.activeAgent[row.entityKey]=agentName}for(let row of listCoordinationStates(directory,DELEGATION_CHAIN_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let chain=JSON.parse(row.payload);if(!Array.isArray(chain))throw Error("Invalid SQLite snapshot delegation-chain payload");snapshot.delegationChains[row.entityKey]=chain}for(let row of listCoordinationStates(directory,SESSION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let payload=parseRecordPayload(row.payload,"agent-session");if(!payload.session||typeof payload.session!=="object"||Array.isArray(payload.session)||payload.ownerToken!==void 0&&typeof payload.ownerToken!=="string")throw Error("Invalid SQLite snapshot agent-session payload");snapshot.agentSessions[row.entityKey]=payload.session}return snapshot})}function isSnapshotSessionAuthoritativelyStale(directory,sessionId,staleDurationMs,now=Date.now()){try{if(!projectDbExists(directory)||!sessionId)return!1;let row=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(!row||row.status==="deleted")return!0;let lastToolCallTime=parseRecordPayload(row.payload,"agent-session").session?.lastToolCallTime;if(typeof lastToolCallTime!=="number"||!Number.isFinite(lastToolCallTime))return!1;return now-lastToolCallTime>staleDurationMs}catch{return!1}}function clearSnapshotRows(directory){if(!projectDbExists(directory))return 0;let removed=0;return withCoordinationTransaction(directory,()=>{for(let namespace of SNAPSHOT_NAMESPACES)for(let row of listCoordinationStates(directory,namespace,MAX_COORDINATION_STATE_LIST_ROWS))if(deleteCoordinationState(directory,namespace,row.entityKey,row.revision))removed+=1;deleteCoordinationImports(directory,["session/state.json",SNAPSHOT_PROJECTION_SOURCE])}),removed}function deleteSnapshotSessionRows(directory,sessionId,reason="ended"){if(!projectDbExists(directory)||!sessionId)return 0;let removed=0;return withCoordinationTransaction(directory,()=>{let ownerToken=localSessionOwners.get(sessionId)?.token,sessionRow=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(reason==="stale"&&!ownerToken)return;if(sessionRow&&sessionRow.status!=="deleted")try{let persistedOwner=JSON.parse(sessionRow.payload).ownerToken;if(persistedOwner&&persistedOwner!==ownerToken)return}catch{return}for(let namespace of[SESSION_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE]){let row=getCoordinationState(directory,namespace,sessionId);if(!row||row.status==="deleted")continue;if(transitionCoordinationState(directory,{namespace,entityKey:sessionId,expectedRevision:row.revision,generation:row.generation+1,status:"deleted",payload:JSON.stringify({reason,...ownerToken?{ownerToken}:{}})}).outcome==="applied")removed+=1}}),removed}var META_NAMESPACE="session.snapshot.meta",SESSION_NAMESPACE="session.snapshot.agent",TOOL_NAMESPACE="session.snapshot.tool",ACTIVE_AGENT_NAMESPACE="session.snapshot.active-agent",DELEGATION_CHAIN_NAMESPACE="session.snapshot.delegation-chain",SNAPSHOT_PROJECTION_SOURCE="session/state.sqlite-projection.json",SNAPSHOT_NAMESPACES,_snapshotStoreInternals,localSessionOwners;var init_snapshot_store=__esm(()=>{init_coordination_store();init_project_db();SNAPSHOT_NAMESPACES=[META_NAMESPACE,SESSION_NAMESPACE,TOOL_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE],_snapshotStoreInternals={afterSnapshotMetaRead:()=>{}},localSessionOwners=new Map});import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}async function countWorktrees(directory){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return 0}return new Promise((resolve50)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS3,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve50(0);return}let count=0;for(let line of stdout.split(`
1278
1278
  `))if(line.startsWith("worktree "))count++;resolve50(count)});try{child.stdin?.end()}catch{}child.on("error",()=>resolve50(0))}catch{resolve50(0)}})}async function maybeSuggestWorktreeLink(directory,sessionId){try{if(!directory||!sessionId)return;if(_suggestedSessions.has(sessionId))return;if(markSuggested(sessionId),isLinked(directory))return;let worktrees=await countWorktrees(directory);if(worktrees>1)advisoryWarn(`[opencode-swarm] Detected ${worktrees} git worktrees of this repo. Run \`/swarm link\` in each to share swarm knowledge across them (or \`/swarm link <name>\` to share with similar projects).`)}catch{}}var GIT_TIMEOUT_MS3=1500,MAX_SUGGESTED_SESSIONS=500,_suggestedSessions;var init_worktree_link_suggestion=__esm(()=>{init_knowledge_link();init_warning_buffer();init_git_executable();_suggestedSessions=new Set});class AgentRunContext{runId;activeToolCalls;activeAgent;delegationChains;agentSessions;environmentProfiles;toolAggregates;constructor(runId,toolAggregates){this.runId=runId,this.activeToolCalls=new Map,this.activeAgent=new Map,this.delegationChains=new Map,this.agentSessions=new Map,this.environmentProfiles=new Map,this.toolAggregates=toolAggregates}}function containsControlCharacters(value){for(let ch of value){let cp2=ch.codePointAt(0);if(cp2!==void 0&&(cp2<=31||cp2===127))return!0}return!1}function hasNonAsciiHostname(hostname5){for(let ch of hostname5){let cp2=ch.codePointAt(0);if(cp2!==void 0&&cp2>127)return!0}return!1}function isIpv4MappedPrivateHost(inner){if(IPV4_PRIVATE.test(inner)||IPV4_LOOPBACK.test(inner)||IPV4_LINK_LOCAL.test(inner)||IPV4_PRIVATE_172.test(inner)||IPV4_PRIVATE_192.test(inner)||IPV4_ZERO_NETWORK.test(inner))return!0;let firstSegment=inner.split(":",1)[0];if(!firstSegment)return!1;let firstWord=Number.parseInt(firstSegment,16);if(!Number.isFinite(firstWord))return!1;return firstWord>=0&&firstWord<=255||firstWord>=2560&&firstWord<=2815||firstWord>=32512&&firstWord<=32767||firstWord===43518||firstWord>=44048&&firstWord<=44063||firstWord===49320}function isPrivateHost(url3){let host=url3.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(host==="localhost"||host==="::1"||host==="0.0.0.0"||IPV4_LOOPBACK.test(host)||IPV4_ZERO_NETWORK.test(host))return!0;if(host.startsWith("localhost")||host==="localhost.com")return!0;if(host.endsWith(".localhost"))return!0;if(IPV4_PRIVATE.test(host)||IPV4_LINK_LOCAL.test(host)||IPV4_PRIVATE_172.test(host)||IPV4_PRIVATE_192.test(host)||IPV6_LINK_LOCAL.test(host)||IPV6_UNIQUE_LOCAL.test(host))return!0;if(host.startsWith("::ffff:")){let inner=host.slice(7);if(isIpv4MappedPrivateHost(inner))return!0}return!1}function hasPunycodeLabel(host){return host.toLowerCase().split(".").some((label)=>label.startsWith("xn--"))}var IPV4_PRIVATE,IPV4_LOOPBACK,IPV4_LINK_LOCAL,IPV4_PRIVATE_172,IPV4_PRIVATE_192,IPV4_ZERO_NETWORK,IPV6_LINK_LOCAL,IPV6_UNIQUE_LOCAL;var init_host_guards=__esm(()=>{IPV4_PRIVATE=/^10\./,IPV4_LOOPBACK=/^127\./,IPV4_LINK_LOCAL=/^169\.254\./,IPV4_PRIVATE_172=/^172\.(1[6-9]|2\d|3[0-1])\./,IPV4_PRIVATE_192=/^192\.168\./,IPV4_ZERO_NETWORK=/^0\./,IPV6_LINK_LOCAL=/^fe80:/i,IPV6_UNIQUE_LOCAL=/^f[cd][0-9a-f]{2}:/i});function isGitLabIndicatingHost(host){let lower=host.toLowerCase();if(lower===GITLAB_PUBLIC_HOST)return!0;if(!lower.startsWith("gitlab."))return!1;let remainder=lower.slice(7);if(remainder.length===0)return!1;return remainder.split(".").every((label)=>/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label))}function isForgePrUrl(url3,configured){return canonicalForgePrUrl(url3,configured)!==null}function detectForgeFromUrl(url3,configured){try{let parsed=new URL(url3);if(parsed.protocol!=="https:")return null;let host=parsed.hostname.toLowerCase();if(hasUserinfo(parsed))return null;if(hasNonAsciiHostname(host)||hasPunycodeLabel(host))return null;if(isPrivateHost(parsed))return null;if(host===GITHUB_CANONICAL_HOST)return{provider:"github",host};if(isGitLabIndicatingHost(host))return{provider:"gitlab",host};if(configured&&configured.provider==="gitlab"&&host===configured.host)return{provider:"gitlab",host};return null}catch{return null}}function hasUserinfo(parsed){return parsed.username!==""||parsed.password!==""}function isConfiguredGitLabHost(host,configured){return configured!==void 0&&configured.provider==="gitlab"&&host===configured.host}function matchForgeResourceUrl(url3,resource,configured){if(containsControlCharacters(url3))return null;let parsed;try{parsed=new URL(url3)}catch{return null}if(parsed.protocol!=="https:")return null;if(hasUserinfo(parsed))return null;let host=parsed.hostname.toLowerCase();if(hasNonAsciiHostname(host)||hasPunycodeLabel(host))return null;if(isPrivateHost(parsed))return null;try{if(containsControlCharacters(decodeURIComponent(parsed.pathname)))return null}catch{return null}if(host===GITHUB_CANONICAL_HOST){let m=parsed.pathname.match(new RegExp(`^\\/([^/]+)\\/([^/]+)\\/${resource==="pull"?"pull":"issues"}\\/([0-9]+)\\/?$`));if(!m)return null;if(containsControlCharacters(m[1])||containsControlCharacters(m[2]))return null;let number7=Number.parseInt(m[3],10);if(!Number.isSafeInteger(number7)||number7<=0)return null;return{provider:"github",host,owner:m[1],repo:m[2],number:number7}}if(isGitLabIndicatingHost(host)||isConfiguredGitLabHost(host,configured)){let resourceSegment=resource==="pull"?"merge_requests":"issues",m=parsed.pathname.match(GITLAB_PROJECT_PATH_PATTERN);if(!m||m[3]!==resourceSegment)return null;if(containsControlCharacters(m[1])||containsControlCharacters(m[2]))return null;let number7=Number.parseInt(m[4],10);if(!Number.isSafeInteger(number7)||number7<=0)return null;return{provider:"gitlab",host,owner:m[1],repo:m[2],number:number7}}return null}function parseForgeRemoteUrl(remoteUrl){let https=remoteUrl.match(/^https:\/\/([^/]+)\/(.+?)(?:\.git)?\/?$/i);if(https)return remotePathResult(https[1],https[2]);let ssh=remoteUrl.match(/^git@([^:/]+):(.+?)(?:\.git)?$/i);if(ssh)return remotePathResult(ssh[1],ssh[2]);return null}function remotePathResult(rawHost,projectPath){let host=rawHost.toLowerCase();if(!host||hasNonAsciiHostname(host)||hasPunycodeLabel(host))return null;if(!isGitLabIndicatingHost(host)&&host!==GITHUB_CANONICAL_HOST)return null;let segments=projectPath.split("/").filter((s)=>s.length>0);if(segments.length<2)return null;let repo=segments[segments.length-1],owner=segments.slice(0,-1).join("/");if(!owner||!repo)return null;if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{provider:host===GITHUB_CANONICAL_HOST?"github":"gitlab",host,owner,repo}}function buildPrUrl(ctx,owner,repo,number7){if(ctx.provider==="gitlab")return`https://${ctx.host}/${owner}/${repo}/-/merge_requests/${number7}`;return`https://github.com/${owner}/${repo}/pull/${number7}`}function buildIssueUrl(ctx,owner,repo,number7){if(ctx.provider==="gitlab")return`https://${ctx.host}/${owner}/${repo}/-/issues/${number7}`;return`https://github.com/${owner}/${repo}/issues/${number7}`}function canonicalForgePrUrl(value,configured){try{let url3=new URL(value);if(url3.protocol!=="https:")return null;if(hasUserinfo(url3))return null;let host=url3.hostname.toLowerCase();if(hasNonAsciiHostname(host)||hasPunycodeLabel(host))return null;if(isPrivateHost(url3))return null;if(host===GITHUB_CANONICAL_HOST){let m=url3.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!m)return null;let number7=Number(m[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`github.com/${m[1].toLowerCase()}/${m[2].toLowerCase()}/pull/${number7}`}if(isGitLabIndicatingHost(host)||isConfiguredGitLabHost(host,configured)){let m=url3.pathname.match(/^\/(.+)\/([^/]+)\/-\/merge_requests\/(\d+)\/?$/);if(!m)return null;let number7=Number(m[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`${host}/${m[1].toLowerCase()}/${m[2].toLowerCase()}/-/merge_requests/${number7}`}return null}catch{return null}}function resolveForgeContextFromPluginConfig(pluginConfig,remotes){if(!pluginConfig?.forge)return null;let forge=pluginConfig.forge,provider=forge.provider==="github"||forge.provider==="gitlab"||forge.provider==="auto"?forge.provider:void 0,selection=resolveProviderSelection({config:{provider,baseUrl:forge.base_url},remotes});return selection.ok?selection.context:null}function invalidBaseUrlError(reason){return`Invalid forge.base_url (${reason}) — provider config rejected; base_url must be an HTTPS URL on a public, ASCII host and is never a trust whitelist.`}function resolveProviderSelection(input){let provider=input.config?.provider??"auto",remotes=input.remotes,baseUrlHost,rawBaseUrl=input.config?.baseUrl??input.config?.base_url;if(rawBaseUrl!==void 0){let raw=rawBaseUrl.trim(),parsed;try{parsed=new URL(raw)}catch{return{ok:!1,error:invalidBaseUrlError("not a valid URL")}}if(parsed.protocol!=="https:")return{ok:!1,error:invalidBaseUrlError("must use HTTPS")};let host=parsed.hostname.toLowerCase();if(hasNonAsciiHostname(host)||hasPunycodeLabel(host))return{ok:!1,error:invalidBaseUrlError("non-ASCII (IDN) hosts are not allowed")};if(isPrivateHost(parsed))return{ok:!1,error:invalidBaseUrlError("private or localhost hosts are not allowed")};if(!host)return{ok:!1,error:invalidBaseUrlError("empty host")};baseUrlHost=host}if(provider==="github"){if(baseUrlHost!==void 0)return{ok:!1,error:'Provider config conflict: forge.provider is "github" but forge.base_url is set — GitHub has a fixed base (github.com) and accepts no override. Remove base_url or set provider to "gitlab".'};return{ok:!0,context:{provider:"github",host:GITHUB_CANONICAL_HOST}}}if(baseUrlHost!==void 0)return{ok:!0,context:{provider:"gitlab",host:baseUrlHost}};let gitlabHosts=new Set,sawGithub=!1,sawUnrecognized=!1;for(let remote of remotes){let parsed=parseForgeRemoteUrl(remote);if(!parsed){sawUnrecognized=!0;continue}if(parsed.provider==="github")sawGithub=!0;else gitlabHosts.add(parsed.host)}if(provider==="gitlab"){if(gitlabHosts.size===1&&!sawGithub&&!sawUnrecognized)return{ok:!0,context:{provider:"gitlab",host:[...gitlabHosts][0]}};return{ok:!1,error:'Provider config incomplete: forge.provider is "gitlab" but no forge.base_url is set and the git remotes do not unanimously indicate a single GitLab host — set forge.base_url (e.g. https://gitlab.example.com) in config.'}}if(sawGithub&&gitlabHosts.size>0)return{ok:!1,error:"Provider selection ambiguous: git remotes indicate both GitHub and GitLab — set forge.provider (and forge.base_url for self-hosted GitLab) explicitly in config."};if(sawUnrecognized)return{ok:!1,error:"Provider selection ambiguous: a git remote host matches no recognized provider (generic self-hosted) — set forge.provider and forge.base_url explicitly in config."};if(sawGithub)return{ok:!0,context:{provider:"github",host:GITHUB_CANONICAL_HOST}};if(gitlabHosts.size===1)return{ok:!0,context:{provider:"gitlab",host:[...gitlabHosts][0]}};if(gitlabHosts.size>1)return{ok:!1,error:"Provider selection ambiguous: git remotes indicate multiple different GitLab hosts — set forge.provider and forge.base_url explicitly in config."};return{ok:!1,error:"Provider selection failed: no workflow-relevant git remote and no forge.base_url — set forge.provider (and forge.base_url for self-hosted GitLab) explicitly in config."}}var GITHUB_CANONICAL_HOST="github.com",GITLAB_PUBLIC_HOST="gitlab.com",GITLAB_PROJECT_PATH_PATTERN;var init_forge_provider=__esm(()=>{init_host_guards();GITLAB_PROJECT_PATH_PATTERN=/^\/(.+)\/([^/]+)\/-\/(merge_requests|issues)\/(\d+)\/?$/});var exports_pr_subscriptions={};__export(exports_pr_subscriptions,{updateSnapshot:()=>updateSnapshot,unsubscribe:()=>unsubscribe,sweepStale:()=>sweepStale,subscribe:()=>subscribe,setOnSubscriptionCreated:()=>setOnSubscriptionCreated,removePrMonitorWorkerHandler:()=>removePrMonitorWorkerHandler,registerPrMonitorWorkerHandler:()=>registerPrMonitorWorkerHandler,lookupByPr:()=>lookupByPr,listActive:()=>listActive,isPrSubscriptionCapacityError:()=>isPrSubscriptionCapacityError,getPrSubscriptionHealth:()=>getPrSubscriptionHealth,findSubscriptionRecordForPrUrl:()=>findSubscriptionRecordForPrUrl,ensurePrSubscriptionDispatcherInstalled:()=>ensurePrSubscriptionDispatcherInstalled,buildCorrelationId:()=>buildCorrelationId,_internals:()=>_internals85,PrSubscriptionCapacityError:()=>PrSubscriptionCapacityError,PR_SUBSCRIPTION_LIMITS:()=>PR_SUBSCRIPTION_LIMITS,PR_SUBSCRIPTIONS_FILE:()=>PR_SUBSCRIPTIONS_FILE,PR_SUBSCRIPTIONS_CHECKPOINT_FILE:()=>PR_SUBSCRIPTIONS_CHECKPOINT_FILE,PR_SUBSCRIPTIONS_AUDIT_FILE:()=>PR_SUBSCRIPTIONS_AUDIT_FILE});import{createHash as createHash44}from"node:crypto";import*as fs61 from"node:fs";import*as path99 from"node:path";function setOnSubscriptionCreated(callback){let previous=onSubscriptionCreated;return onSubscriptionCreated=callback,previous}function registerPrMonitorWorkerHandler(directory,handler){let key2=canonicalRootKey(directory);while(prMonitorWorkerHandlers.size>=MAX_PR_MONITOR_WORKER_HANDLERS&&!prMonitorWorkerHandlers.has(key2)){let oldest=prMonitorWorkerHandlers.keys().next().value;if(oldest===void 0)break;prMonitorWorkerHandlers.delete(oldest)}prMonitorWorkerHandlers.set(key2,handler)}function removePrMonitorWorkerHandler(directory,expectedHandler){let key2=canonicalRootKey(directory);if(expectedHandler!==void 0&&prMonitorWorkerHandlers.get(key2)!==expectedHandler)return;prMonitorWorkerHandlers.delete(key2)}function dispatchPrMonitorWorkerHandler(directory,record3){let handler=prMonitorWorkerHandlers.get(canonicalRootKey(directory));if(handler)handler(directory,record3)}function ensurePrSubscriptionDispatcherInstalled(){if(onSubscriptionCreated===dispatchPrMonitorWorkerHandler)return;if(setOnSubscriptionCreated(dispatchPrMonitorWorkerHandler)!==null)log("[pr-monitor] superseded a previous on-subscription-created callback (installing the per-project dispatcher)")}function storePath3(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_FILE)}function checkpointPath(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_CHECKPOINT_FILE)}function auditPath(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_AUDIT_FILE)}function legacyArchivePath(directory){return validateSwarmPath(directory,LEGACY_ARCHIVE_FILE)}function legacyArchiveNextPath(directory){return`${legacyArchivePath(directory)}.next`}function legacyArchivePreviousPath(directory){return`${legacyArchivePath(directory)}.previous`}function fileExistsStrict(filePath){try{return fs61.statSync(filePath),!0}catch(err){if(err.code==="ENOENT")return!1;throw err}}function importedShadowPath(filePath){return`${filePath}.imported`}function projectionMarkerPath(filePath){return`${filePath}.sqlite-projection`}function foreignSlotPath(directory){return validateSwarmPath(directory,FOREIGN_CHECKPOINT_FILE)}function corruptSlotPath(directory){return validateSwarmPath(directory,CORRUPT_CHECKPOINT_FILE)}function readCoordinationSubscriptions(directory){if(!projectDbExists(directory))return null;try{return Object.fromEntries(listCoordinationStates(directory,PR_SUBSCRIPTION_COORDINATION_NAMESPACE).map((row)=>{let parsed=RecordSchema.safeParse(JSON.parse(row.payload));if(!parsed.success||parsed.data.correlationId!==row.entityKey||row.generation!==1||parsed.data.status!==row.status)throw Error(`PR subscription coordination row failed schema or authority binding validation for ${row.entityKey}`);return[row.entityKey,parsed.data]}))}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);throw log(`[pr-monitor] coordination read failed closed: ${detail}`),Error(`PR subscription coordination authority is unreadable: ${detail}`)}}function projectionSequence(directory){let read=readCheckpoint(directory);return read.kind==="ok"?read.value.sequence:0}function writeCoordinationProjection(directory,view,baseCheckpoint){ensureSwarmDir3(directory);let prepared=prepareCoordinationPersistence(directory,view,baseCheckpoint);assertCoordinationProjectionCapacity(directory,prepared.view,prepared.checkpoint);let sequence=projectionSequence(directory)+1,checkpoint2=prepared.checkpoint;checkpoint2.sequence=sequence,checkpoint2.updatedAt=Date.now(),_internals85.writeCheckpointFile(directory,checkpoint2),fs61.writeFileSync(projectionMarkerPath(checkpointPath(directory)),"","utf-8");let legacyPath=storePath3(directory);if(fs61.existsSync(legacyPath)){let legacyPayload=Object.values(checkpoint2.records).map((entry)=>JSON.stringify(entry)).join(`
@@ -7183,7 +7183,7 @@ ${modeSignal}`:message,usePromptDelivery=config3.event_delivery==="prompt"&&_int
7183
7183
  `),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath2=path295.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile55(manifestPath2,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize4(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize4(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile55(path295.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto14.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path295.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm",".swarm-worktrees","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath2=path295.join(directory,".swarm","doc-manifest.json");try{fs168.unlinkSync(manifestPath2)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals236});var knowledge_recall,_internals236;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_receipt_ledger();init_knowledge_types();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response"),repair_re_evaluation:exports_external.object({repair_id:exports_external.string().uuid(),phase:exports_external.string().min(1).max(256),task_id:exports_external.string().min(1).max(256).optional(),scope_complete:exports_external.boolean()}).optional().describe("Architect-only explicit completion of a repaired receipt scope. The query must comprehensively re-evaluate the exact affected phase/session scope.")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput,repairInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug,repairInput=obj.repair_re_evaluation}}catch{}let wantDebug=debugInput===!0,repairReevaluation;if(repairInput!==void 0){if(stripKnownSwarmPrefix(ctx?.agent??"")!=="architect"||typeof repairInput!=="object"||repairInput===null)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_ARCHITECT_ONLY",error:"Only the architect may complete an explicit receipt repair re-evaluation."});let candidate2=repairInput;if(typeof candidate2.repair_id!=="string"||!candidate2.repair_id||typeof candidate2.phase!=="string"||!candidate2.phase||candidate2.scope_complete!==!0||candidate2.task_id!==void 0&&typeof candidate2.task_id!=="string")return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_PROOF_INVALID",error:"Explicit re-evaluation requires repair_id, exact phase, and scope_complete=true."});repairReevaluation={repair_id:candidate2.repair_id,phase:candidate2.phase,scope_complete:!0,...typeof candidate2.task_id==="string"?{task_id:candidate2.task_id}:{}}}if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1,emitEvent:!1}),sessionId=ctx?.sessionID??"unknown";if(results.length>0){let membership=await commitDisplayedMembership(directory,{trace_id,session_id:sessionId,exposure_kind:"manual_recall",agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation,entries:results.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return JSON.stringify({results:[],total:0,unverifiable:!0,code:membership.ok?"terminal_trace_reuse":membership.code,error:membership.ok?"retrieval trace was already terminalized":membership.detail})}else{let empty=await commitEmptyRetrieval(directory,{trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation});if(!empty.ok)return JSON.stringify({results:[],total:0,unverifiable:!0,code:empty.code,error:empty.detail});if(!empty.terminal_event_id)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"store_unavailable",error:"empty retrieval terminal did not commit"})}let ranks=Object.fromEntries(results.map((entry,index)=>[entry.id,index+1])),scores=Object.fromEntries(results.map((entry)=>[entry.id,entry.finalScore]));await recordKnowledgeEvent(directory,{type:"retrieved",trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",query:queryInput,retrieval_mode:"manual",result_ids:results.map((entry)=>entry.id),ranks,scores});let scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals236={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
7184
7184
  `);if(audience==="coder")return[header,policy.avoidPosixExamples?"- Command policy: Prefer PowerShell-native commands and Node.js APIs. Do not start with POSIX commands (ls, grep, rm, cat, export, pwd) unless the environment profile indicates Docker, WSL, or a POSIX shell.":"- Command policy: Use POSIX-native commands and Node.js APIs.","","EXECUTION ENVIRONMENT AWARENESS","- This session includes a runtime environment profile. Follow it exactly.","- Decision ladder when shell commands are necessary:"," 1. Prefer swarm tools and Node.js fs/path APIs."," 2. Use shell only when the task truly requires it."," 3. When shell commands are needed, match the active shell family above."].join(`
7185
7185
  `);return[header,"- Test execution policy: Always execute tests via the swarm test runner tool.",policy.avoidPosixExamples?" Do not describe POSIX shell setup commands unless the profile indicates Docker, WSL, or POSIX shell.":" Use POSIX semantics for test commands.","","ENVIRONMENT-SPECIFIC TEST EXECUTION RULES",profile.isWindowsNative?"- Native Windows + PowerShell: Assume PowerShell semantics for paths and env vars. Prefer Pester for PowerShell modules where appropriate.":profile.isWindowsDocker?"- Windows + Docker: Host paths are Windows-style; in-container operations use POSIX semantics.":"- Linux/macOS: Use POSIX semantics for all shell-related reasoning.","- In all modes: prefer the swarm test runner over ad hoc shell commands.","- When tests are skipped due to environment issues, explicitly mention the environment profile assumptions in your verdict."].join(`
7186
- `)}var init_prompt_renderer=()=>{};function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync160,readdirSync as readdirSync47,readFileSync as readFileSync131,statSync as statSync93}from"node:fs";import*as path301 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path301.resolve(directory),resolved=path301.resolve(baseDir,concrete),rel3=path301.relative(baseDir,resolved);if(rel3.startsWith("..")||path301.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path301.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path301.join(dir,name);if(existsSync160(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve116)=>setTimeout(()=>resolve116("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync47(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path301.join(dir,entry.name),relPath=path301.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync93(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync131(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path301.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path301.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals245.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals245.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals245.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals245.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals245,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals245={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash102}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash102("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash102("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash102("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash102("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals257,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs180 from"node:fs";import*as path315 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals257.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals257.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals257.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??""),recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},attemptClass:"attempt",outcomeStatus:"unknown"})}catch{}}function terminalAttemptClass(status2){if(status2==="cancelled")return"cancelled";return"result"}function terminalAttemptOutcome(status2){if(status2==="completed")return"success";if(status2==="error"||status2==="failed")return"failure";return"unknown"}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals257.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields);let usageAttested=costFields.cost_source==="reported";recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},...record3.callID?{callId:record3.callID}:{},...record3.laneId?{laneId:record3.laneId}:{},attemptClass:terminalAttemptClass(terminalStatus),outcomeStatus:terminalAttemptOutcome(terminalStatus),cost:{...observations.startedAt!==void 0?{latencyMs:Math.max(0,Date.now()-observations.startedAt)}:{},...usageAttested?{...typeof costFields.tokens_input==="number"?{inputTokens:costFields.tokens_input}:{},...typeof costFields.tokens_output==="number"?{outputTokens:costFields.tokens_output}:{},...typeof costFields.tokens_cache==="number"?{cacheReadTokens:costFields.tokens_cache}:{}}:{},...costFields.cost_source==="reported"&&costFields.cost_usd!==null?{billedCostUsd:costFields.cost_usd}:{},...costFields.cost_source==="estimated"&&costFields.cost_usd!==null?{estimatedCostUsd:costFields.cost_usd}:{}}})}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path315.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs180.existsSync(filePath))return null;let parsed=JSON.parse(fs180.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path315.join(directory,".swarm");fs180.mkdirSync(swarmDir,{recursive:!0});let filePath=path315.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs180.rmSync(filePath,{force:!0});else fs180.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals257;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_execution_attempt();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals257={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals287});import*as fs208 from"node:fs";import*as path346 from"node:path";function mtimeMsOrNull(absPath){try{return fs208.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path346.resolve(directory),resolved=path346.resolve(root,anchor),rel3=path346.relative(root,resolved);if(rel3.startsWith("..")||path346.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path346.resolve(directory),outAbs=path346.resolve(root,outDir),outRel=path346.relative(root,outAbs);if(outRel.startsWith("..")||path346.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path346.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path346.join(outDir,relFile));else checkedDocs.push(path346.join(outDir,relFile))}let traceabilityAbs=path346.join(outAbs,TRACEABILITY_REL),registry4=null;try{if((await fs208.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs208.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry4=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry4=null}let noDocs=checkedDocs.length===0||registry4===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry4?.sections))for(let section2 of registry4.sections){if(!section2||typeof section2.section_id!=="string")continue;if(typeof section2.doc!=="string"||!docMtimes.has(section2.doc))continue;let docMtime=docMtimes.get(section2.doc)??null;if(docMtime===null){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section2.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section2.spec_frs?.length??0)>0)staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals287;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path346.join("reference","reference-impl.md"),"idiom-notes":path346.join("reference","idiom-notes.md")},TRACEABILITY_REL=path346.join("reference","traceability.json");_internals287={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals320,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs236 from"node:fs";import*as path382 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs236.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs236.accessSync(path382.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs236.readFileSync(path382.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals320.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals320.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals320;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals320={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash119}from"node:crypto";import{mkdirSync as mkdirSync101,writeFileSync as writeFileSync66}from"node:fs";import*as path383 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath8}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs153 from"node:fs";import*as path278 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path278.resolve(this.directory,".swarm")}getPlanJsonPath(){return path278.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs153.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs153.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs153.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs153.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs153.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals56.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals56.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path278.join(swarmDir,"plan.json"),markerPath=path278.join(swarmDir,".plan-write-marker"),planStats=fs153.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs153.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve108,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve108(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_feedback_loop_runtime();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash98}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash97}from"node:crypto";import*as fs155 from"node:fs";import*as path280 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey2(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha25610(value){return createHash97("sha256").update(value).digest("hex")}function policyDigest(policy){return sha25610(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey2(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey2(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:receiptStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs155.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs155.openSync(filePath,fs155.constants.O_RDONLY|(fs155.constants.O_NOFOLLOW??0));let openedStat=fs155.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs155.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs155.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs155.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs155.promises.open(filePath,fs155.constants.O_RDONLY|(fs155.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha25610(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs155.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs155.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs155.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs155.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs155.promises.mkdir(path280.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function receiptStructureHash(plan){return computePlanStructureHash({...plan,current_phase:void 0})}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===receiptStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha25610(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha25610(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha25610(correlationKey2(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&&currentPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory),cursorPhase=getCurrentPhase(plan);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receipt.phase===cursorPhase&&cursorPhase<phase))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),cursorPhase=getCurrentPhase(plan),peek=readRawStore(directory);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;if(match[1]==="APPROVED"||match[1]==="PASS")return"pass";if(match[1]==="SKIPPED")return"skip";return"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace,directory);return{...check3,ok:!check3.stale}}var BARE_TASK_ID=/^\d+(?:\.\d+)*$/,SCOPE_CASE_FOLD=process.platform==="win32";function scopeMatchKey(normalized){return SCOPE_CASE_FOLD?normalized.toLowerCase():normalized}function deriveScopeFiles(scope){if(!scope)return null;let files=new Set;for(let fragment of scope.split(",")){let normalized=normalizeAttributionPath(fragment);if(normalized===null||BARE_TASK_ID.test(normalized))continue;files.add(scopeMatchKey(normalized))}return files.size>0?files:null}function scopeDirtySlice(files,scopeFiles){let slice=new Set;for(let file3 of files){let normalized=normalizeAttributionPath(file3);if(normalized!==null&&scopeFiles.has(scopeMatchKey(normalized)))slice.add(normalized)}return slice}function compareStageBWorkspace(record3,actualWorkspace,directory){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;if(!expectedWorkspace)return{stale:!1};if(record3.normalizedAgent==="docs")return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let scopeFiles=deriveScopeFiles(expectedWorkspace.scope),expectedHead=expectedWorkspace.gitHead,currentHead=actualWorkspace.gitHead,expectedChanged=expectedWorkspace.changedFiles,currentChanged=actualWorkspace.changedFiles;if(scopeFiles===null||expectedHead==null||currentHead==null||expectedChanged==null||currentChanged==null||directory===void 0)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let identity=workspaceSnapshotMatches({...expectedWorkspace,gitHead:null,dirtyHash:null},{...actualWorkspace,gitHead:null,dirtyHash:null});if(!identity.ok)return{stale:!0,reason:identity.reason};let committed=committedFilesBetween(directory,expectedHead,currentHead);if(committed===null)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let committedInScope=committed.filter((file3)=>scopeFiles.has(scopeMatchKey(normalizeAttributionPath(file3)??"")));if(committedInScope.length>0){let shown=committedInScope.slice(0,5).join(", "),extra=committedInScope.length>5?` (+${committedInScope.length-5} more)`:"";return{stale:!0,reason:`in-scope committed change: ${shown}${extra}`}}let dispatchDirty=scopeDirtySlice(expectedChanged,scopeFiles),currentDirty=scopeDirtySlice(currentChanged,scopeFiles),dirtied=[...currentDirty].filter((file3)=>!dispatchDirty.has(file3)),cleaned=[...dispatchDirty].filter((file3)=>!currentDirty.has(file3));if(dirtied.length>0||cleaned.length>0)return{stale:!0,reason:`in-scope dirty set changed: +[${dirtied.join(", ")}] -[${cleaned.join(", ")}]`};return{stale:!1}}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles,args2.directory))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict==="skip")return{ok:!1,consumed:!0,skipped:!0,reason:`background ${stageBRole} skipped task ${taskId} — tests not run; re-dispatch the test gate (task stays Stage B eligible; reviewer proof preserved)`};if(stageBRole&&verdict!=="pass"){let rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve108)=>setTimeout(resolve108,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,applied2.skipped?"skipped (tests not run) — re-dispatch the test gate; reviewer proof preserved; task remains Stage B eligible":legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode2(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&&current.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode2(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash98("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash98("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_package();init_constants();import*as fs156 from"node:fs";import*as path281 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path281.join(projectDirectory,".swarm"),dest=path281.join(swarmDir,"config.example.json");if(fs156.existsSync(dest))return;if(!fs156.existsSync(swarmDir))fs156.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs156.writeFileSync(dest,`${JSON.stringify(example,null,2)}
7186
+ `)}var init_prompt_renderer=()=>{};function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync160,readdirSync as readdirSync47,readFileSync as readFileSync131,statSync as statSync93}from"node:fs";import*as path301 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path301.resolve(directory),resolved=path301.resolve(baseDir,concrete),rel3=path301.relative(baseDir,resolved);if(rel3.startsWith("..")||path301.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path301.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path301.join(dir,name);if(existsSync160(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve116)=>setTimeout(()=>resolve116("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync47(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path301.join(dir,entry.name),relPath=path301.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync93(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync131(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path301.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path301.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals245.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals245.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals245.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals245.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals245,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals245={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash102}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash102("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash102("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash102("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash102("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals257,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs180 from"node:fs";import*as path315 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals257.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals257.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals257.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??""),recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},attemptClass:"attempt",outcomeStatus:"unknown"})}catch{}}function terminalAttemptClass(status2){if(status2==="cancelled")return"cancelled";return"result"}function terminalAttemptOutcome(status2){if(status2==="completed")return"success";if(status2==="error"||status2==="failed")return"failure";return"unknown"}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals257.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields);let usageAttested=costFields.cost_source==="reported";recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},...record3.callID?{callId:record3.callID}:{},...record3.laneId?{laneId:record3.laneId}:{},attemptClass:terminalAttemptClass(terminalStatus),outcomeStatus:terminalAttemptOutcome(terminalStatus),cost:{...observations.startedAt!==void 0?{latencyMs:Math.max(0,Date.now()-observations.startedAt)}:{},...usageAttested?{...typeof costFields.tokens_input==="number"?{inputTokens:costFields.tokens_input}:{},...typeof costFields.tokens_output==="number"?{outputTokens:costFields.tokens_output}:{},...typeof costFields.tokens_cache==="number"?{cacheReadTokens:costFields.tokens_cache}:{}}:{},...costFields.cost_source==="reported"&&costFields.cost_usd!==null?{billedCostUsd:costFields.cost_usd}:{},...costFields.cost_source==="estimated"&&costFields.cost_usd!==null?{estimatedCostUsd:costFields.cost_usd}:{}}})}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path315.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs180.existsSync(filePath))return null;let parsed=JSON.parse(fs180.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path315.join(directory,".swarm");fs180.mkdirSync(swarmDir,{recursive:!0});let filePath=path315.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs180.rmSync(filePath,{force:!0});else fs180.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals257;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_execution_attempt();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals257={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals287});import*as fs208 from"node:fs";import*as path346 from"node:path";function mtimeMsOrNull(absPath){try{return fs208.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path346.resolve(directory),resolved=path346.resolve(root,anchor),rel3=path346.relative(root,resolved);if(rel3.startsWith("..")||path346.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path346.resolve(directory),outAbs=path346.resolve(root,outDir),outRel=path346.relative(root,outAbs);if(outRel.startsWith("..")||path346.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path346.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path346.join(outDir,relFile));else checkedDocs.push(path346.join(outDir,relFile))}let traceabilityAbs=path346.join(outAbs,TRACEABILITY_REL),registry4=null;try{if((await fs208.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs208.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry4=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry4=null}let noDocs=checkedDocs.length===0||registry4===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry4?.sections))for(let section2 of registry4.sections){if(!section2||typeof section2.section_id!=="string")continue;if(typeof section2.doc!=="string"||!docMtimes.has(section2.doc))continue;let docMtime=docMtimes.get(section2.doc)??null;if(docMtime===null){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section2.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section2.spec_frs?.length??0)>0)staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals287;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path346.join("reference","reference-impl.md"),"idiom-notes":path346.join("reference","idiom-notes.md")},TRACEABILITY_REL=path346.join("reference","traceability.json");_internals287={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals320,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs236 from"node:fs";import*as path382 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs236.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs236.accessSync(path382.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs236.readFileSync(path382.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals320.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals320.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals320;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals320={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash119}from"node:crypto";import{mkdirSync as mkdirSync101,writeFileSync as writeFileSync66}from"node:fs";import*as path383 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath8}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs153 from"node:fs";import*as path278 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path278.resolve(this.directory,".swarm")}getPlanJsonPath(){return path278.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs153.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs153.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs153.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs153.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs153.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals56.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals56.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path278.join(swarmDir,"plan.json"),markerPath=path278.join(swarmDir,".plan-write-marker"),planStats=fs153.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs153.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve108,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve108(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_feedback_loop_runtime();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash98}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash97}from"node:crypto";import*as fs155 from"node:fs";import*as path280 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey2(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha25610(value){return createHash97("sha256").update(value).digest("hex")}function policyDigest(policy){return sha25610(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey2(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey2(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:receiptStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs155.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs155.openSync(filePath,fs155.constants.O_RDONLY|(fs155.constants.O_NOFOLLOW??0));let openedStat=fs155.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs155.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs155.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs155.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs155.promises.open(filePath,fs155.constants.O_RDONLY|(fs155.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha25610(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs155.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs155.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs155.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs155.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs155.promises.mkdir(path280.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function receiptStructureHash(plan){return computePlanStructureHash({...plan,current_phase:void 0})}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===receiptStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha25610(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha25610(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha25610(correlationKey2(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&&currentPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory),cursorPhase=getCurrentPhase(plan);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receipt.phase===cursorPhase&&cursorPhase<phase))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),cursorPhase=getCurrentPhase(plan),peek=readRawStore(directory);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;if(match[1]==="APPROVED"||match[1]==="PASS")return"pass";if(match[1]==="SKIPPED")return"skip";return"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace,directory);return{...check3,ok:!check3.stale}}var BARE_TASK_ID=/^\d+(?:\.\d+)*$/,SCOPE_CASE_FOLD=process.platform==="win32";function scopeMatchKey(normalized){return SCOPE_CASE_FOLD?normalized.toLowerCase():normalized}function deriveScopeFiles(scope){if(!scope)return null;let files=new Set;for(let fragment of scope.split(",")){let normalized=normalizeAttributionPath(fragment);if(normalized===null||BARE_TASK_ID.test(normalized))continue;files.add(scopeMatchKey(normalized))}return files.size>0?files:null}function scopeDirtySlice(files,scopeFiles){let slice=new Set;for(let file3 of files){let normalized=normalizeAttributionPath(file3);if(normalized!==null&&scopeFiles.has(scopeMatchKey(normalized)))slice.add(normalized)}return slice}function compareStageBWorkspace(record3,actualWorkspace,directory){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;if(!expectedWorkspace)return{stale:!1};if(record3.normalizedAgent==="docs")return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let scopeFiles=deriveScopeFiles(expectedWorkspace.scope),expectedHead=expectedWorkspace.gitHead,currentHead=actualWorkspace.gitHead,expectedChanged=expectedWorkspace.changedFiles,currentChanged=actualWorkspace.changedFiles;if(scopeFiles===null||expectedHead==null||currentHead==null||expectedChanged==null||currentChanged==null||directory===void 0)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let identity=workspaceSnapshotMatches({...expectedWorkspace,gitHead:null,dirtyHash:null},{...actualWorkspace,gitHead:null,dirtyHash:null});if(!identity.ok)return{stale:!0,reason:identity.reason};let committed=committedFilesBetween(directory,expectedHead,currentHead);if(committed===null)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let committedInScope=committed.filter((file3)=>scopeFiles.has(scopeMatchKey(normalizeAttributionPath(file3)??"")));if(committedInScope.length>0){let shown=committedInScope.slice(0,5).join(", "),extra=committedInScope.length>5?` (+${committedInScope.length-5} more)`:"";return{stale:!0,reason:`in-scope committed change: ${shown}${extra}`}}let dispatchDirty=scopeDirtySlice(expectedChanged,scopeFiles),currentDirty=scopeDirtySlice(currentChanged,scopeFiles),dirtied=[...currentDirty].filter((file3)=>!dispatchDirty.has(file3)),cleaned=[...dispatchDirty].filter((file3)=>!currentDirty.has(file3));if(dirtied.length>0||cleaned.length>0)return{stale:!0,reason:`in-scope dirty set changed: +[${dirtied.join(", ")}] -[${cleaned.join(", ")}]`};return{stale:!1}}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles,args2.directory))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict==="skip")return{ok:!1,consumed:!0,skipped:!0,reason:`background ${stageBRole} skipped task ${taskId} — tests not run; re-dispatch the test gate (task stays Stage B eligible; reviewer proof preserved)`};if(stageBRole&&verdict!=="pass"){let rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve108)=>setTimeout(resolve108,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,applied2.skipped?"skipped (tests not run) — re-dispatch the test gate; reviewer proof preserved; task remains Stage B eligible":legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode2(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&&current.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode2(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash98("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash98("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_package();init_constants();import*as fs156 from"node:fs";import*as path281 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path281.join(projectDirectory,".swarm"),dest=path281.join(swarmDir,"config.example.json");if(fs156.existsSync(dest))return;if(!fs156.existsSync(swarmDir))fs156.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:DEFAULT_AGENT_CONFIGS.coder?.fallback_models??["opencode/big-pickle"]}])),max_iterations:5};fs156.writeFileSync(dest,`${JSON.stringify(example,null,2)}
7187
7187
  `,"utf-8")}catch{}}init_schema();init_schema();init_core_events();init_delegation_gate();init_utils2();init_injection_budget();init_utils();var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{appendCoreEventSync(directory,{event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100})}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries2,targetRole,directory,options={}){if(!entries2||entries2.length===0)return[];let filtered=[];for(let entry of entries2){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries2.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=input.agent??getActiveAgentName(input.sessionID);if(!targetRole)return;let entries2=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries2,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content),keptRemaining=new Map;for(let content of kept)keptRemaining.set(content,(keptRemaining.get(content)??0)+1);let removedTokens=0;for(let{content}of entries2){let remaining=keptRemaining.get(content)??0;if(remaining>0)keptRemaining.set(content,remaining-1);else removedTokens+=estimateTokens(content)}if(removedTokens>0)deductProducerEmission(input.sessionID,"system-enhancer",removedTokens,{expectedGeneration:input.expectedGeneration});output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs159 from"node:fs";import*as path284 from"node:path";import*as fs158 from"node:fs";import*as path283 from"node:path";import*as crypto13 from"node:crypto";import*as fs157 from"node:fs";import*as path282 from"node:path";var _internals222={readFileSync:fs157.readFileSync,writeFileSync:fs157.writeFileSync,mkdirSync:fs157.mkdirSync,renameSync:fs157.renameSync,existsSync:fs157.existsSync,statSync:fs157.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals222.createHash("sha256").update(content,"utf-8").digest("hex")}function createEmptyContextMap(){return{schema_version:1,generated_at:new Date().toISOString(),repo_fingerprint:"",files:{},task_history:{},decisions:[]}}function loadContextMap(directory){let filePath=path282.join(directory,".swarm","context-map.json");try{if(!_internals222.existsSync(filePath))return null;let raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.schema_version!==1||!Array.isArray(parsed.decisions)||typeof parsed.files!=="object"||parsed.files===null||Array.isArray(parsed.files)||typeof parsed.task_history!=="object"||parsed.task_history===null||Array.isArray(parsed.task_history))return null;return parsed}catch{return null}}function saveContextMap(map3,directory){let swarmDir=path282.join(directory,".swarm"),tmpPath=path282.join(swarmDir,"context-map.tmp"),finalPath=path282.join(swarmDir,"context-map.json");_internals222.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals222.writeFileSync(tmpPath,json3,"utf-8"),_internals222.renameSync(tmpPath,finalPath)}function appendTaskHistory(map3,summary){return{...map3,task_history:{...map3.task_history,[summary.task_id]:summary}}}function appendDecision(map3,decision){return{...map3,decisions:[...map3.decisions,decision]}}var EXTENSION_LANGUAGE_MAP={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".rs":"rust",".go":"go",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml",".css":"css",".scss":"scss",".html":"html",".sh":"shell",".bash":"shell",".ps1":"powershell"};function detectLanguage(filePath){let ext=path283.extname(filePath).toLowerCase();return EXTENSION_LANGUAGE_MAP[ext]}var RE_EXPORT_NAMED=/export\s+(?:function|class|interface|type|const|let|var|enum)\s+(\w+)/g,RE_EXPORT_BRACE=/export\s*\{\s*([\w,\s]+)\s*\}/g,RE_IMPORT_FROM=/import\s+.*?\s+from\s+['"](.+?)['"]/g,RE_IMPORT_REQUIRE=/require\(\s*['"](.+?)['"]\s*\)/g,RE_FIRST_COMMENT=/\/\*(.+?)\*\//s,MAX_KEY_SYMBOLS=10,MAX_PURPOSE_LENGTH=200;function extractFileSummary(filePath,content,absolutePath2,existingEntry){let contentHash=computeContentHash3(content),language=detectLanguage(filePath),exportsList=extractExports(content),importsList=extractImports6(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs158.statSync(absolutePath2).mtimeMs}catch{}let base={path:filePath,content_hash:contentHash,mtime_ms:mtimeMs,language,purpose,exports:exportsList.length>0?exportsList:void 0,imports:importsList.length>0?importsList:void 0,key_symbols:keySymbols.length>0?keySymbols:void 0,summary:purpose};if(existingEntry)return{...base,invariants:existingEntry.invariants,risks:existingEntry.risks,tests:existingEntry.tests,last_seen_task_ids:existingEntry.last_seen_task_ids};return base}function isFileStale(entry,currentContent){let currentHash=computeContentHash3(currentContent);return entry.content_hash!==currentHash}function extractExports(content){let symbols2=[],namedRe=new RegExp(RE_EXPORT_NAMED.source,"g"),match;match=namedRe.exec(content);while(match!==null)symbols2.push(match[1]),match=namedRe.exec(content);let braceRe=new RegExp(RE_EXPORT_BRACE.source,"g");match=braceRe.exec(content);while(match!==null){let list=match[1];for(let name of list.split(",")){let trimmed=name.trim();if(trimmed)symbols2.push(trimmed)}match=braceRe.exec(content)}return symbols2}function extractImports6(content){let specifiers=[],fromRe=new RegExp(RE_IMPORT_FROM.source,"g"),match;match=fromRe.exec(content);while(match!==null)specifiers.push(match[1]),match=fromRe.exec(content);let requireRe=new RegExp(RE_IMPORT_REQUIRE.source,"g");match=requireRe.exec(content);while(match!==null)specifiers.push(match[1]),match=requireRe.exec(content);return specifiers}function extractPurpose(content){let match=RE_FIRST_COMMENT.exec(content);if(!match)return"No summary available";let body=match[1].split(`
7188
7188
  `).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var MAX_CONTEXT_MD_DECISIONS=50,MAX_CONTEXT_MD_CONTENT_CHARS=1e6;function allocateDecisionId(decisions){let max=0n;for(let entry of decisions){if(typeof entry?.id!=="string")continue;let match=/^A(\d+)$/.exec(entry.id);if(!match)continue;let value=BigInt(match[1]);if(value>max)max=value}return`A${(max+1n).toString()}`}function isArchitectRole(role){return role==="architect"||role.endsWith("_architect")}function extractContextDecisionsFromContextMd(directory,options){if(options?.agent_role!==void 0&&!isArchitectRole(options.agent_role))return[];try{let contextMdPath=path284.join(directory,".swarm","context.md");if(!_internals223.existsSync(contextMdPath))return[];let content=_internals223.readFileSync(contextMdPath,"utf-8"),bounded=content.length>MAX_CONTEXT_MD_CONTENT_CHARS?content.slice(content.length-MAX_CONTEXT_MD_CONTENT_CHARS):content,extracted=extractContextDecisions(bounded),decisions=[];for(let entry of extracted){let separatorIndex=entry.text.indexOf(": "),decision=separatorIndex===-1?entry.text:entry.text.slice(0,separatorIndex),rationale=separatorIndex===-1?"":entry.text.slice(separatorIndex+2);if(decision.trim()===""||/^[\s✅]*$/.test(decision))continue;decisions.push({decision:sanitizeContextText(decision),rationale:sanitizeContextText(rationale),...entry.phase===null?{}:{phase:entry.phase}})}if(decisions.length>MAX_CONTEXT_MD_DECISIONS)return decisions.slice(decisions.length-MAX_CONTEXT_MD_DECISIONS);return decisions}catch{return[]}}var MAX_PERSISTED_DECISIONS=200;function deriveFinalStatus(params){if(params.rejection_reasons&&params.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals223.existsSync(absolutePath2))return null;return _internals223.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals223.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals223={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs159.existsSync,readFileSync:fs159.readFileSync,readdirSync:fs159.readdirSync,realpathSync:fs159.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path284.join(directory,".swarm","evidence",taskId);if(!_internals223.existsSync(evidenceDir))return result;let evidenceFiles=_internals223.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path284.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals223.loadContextMap(params.directory);if(map3===null)map3=_internals223.createEmptyContextMap();let root=path284.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals223.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path284.resolve(root,filePath),realResolved=_internals223.realpathSync(resolved),relative66=path284.relative(realRoot,realResolved);if(relative66.startsWith("..")||path284.isAbsolute(relative66))continue;let normalizedRelative=relative66.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals223.appendTaskHistory(map3,taskSummary),params.decisions&&params.decisions.length>0){let batch=params.decisions.filter((entry)=>(entry.decision??"").trim()!==""),existingTexts=new Set(map3.decisions.map((entry)=>String(entry?.decision??"").trim())),nextSuffix=BigInt(allocateDecisionId(map3.decisions).slice(1));for(let entry of batch){let text=String(entry.decision).trim();if(existingTexts.has(text))continue;existingTexts.add(text);let decision={id:`A${nextSuffix.toString()}`,decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id,...entry.phase===void 0?{}:{phase:entry.phase}};map3=_internals223.appendDecision(map3,decision),nextSuffix+=1n}}if(map3.decisions.length>MAX_PERSISTED_DECISIONS)map3={...map3,decisions:map3.decisions.slice(map3.decisions.length-MAX_PERSISTED_DECISIONS)};return _internals223.saveContextMap(map3,params.directory),map3}catch{try{return _internals223.loadContextMap(params.directory)??_internals223.createEmptyContextMap()}catch{return _internals223.createEmptyContextMap()}}}init_dashboard();init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals224.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals224.now(),hydrated:!0};try{let row=_internals224.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals224.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals224.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate=input.ratePerSecond;if(!(rate>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals224.now();if(refill(bucket,rate,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate*1000);await _internals224.sleep(Math.min(waitMs,1000))}}var _internals224={now:()=>Date.now(),sleep:(ms)=>new Promise((resolve109)=>setTimeout(resolve109,ms)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals225=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals176.boundedAbort,set:(value)=>{_internals176.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals176.boundedDelete,set:(value)=>{_internals176.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals176.log,set:(value)=>{_internals176.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve109,reject)=>{let onAbort=()=>reject(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve109,reject).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId),agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state3();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName2(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName2(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state3();init_task_file();init_invocation_failure();init_state2();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path285=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path285,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
7189
7189
  `);lines.push("| Tool | Calls | Success | Failed | Avg Duration |"),lines.push("|------|-------|---------|--------|--------------|");let sorted2=[...swarmState.toolAggregates.values()].sort((a,b)=>b.count-a.count);for(let agg of sorted2){let avgDuration=agg.count>0?Math.round(agg.totalDuration/agg.count):0;lines.push(`| ${agg.tool} | ${agg.count} | ${agg.successCount} | ${agg.failureCount} | ${avgDuration}ms |`)}return lines.join(`
@@ -7425,8 +7425,8 @@ ${findingText}
7425
7425
  Review before proceeding.`;injectSystemMessage(input.sessionID,message)}}}init_core_events();init_utils2();function createSteeringConsumedHook(directory){return safeHook(async()=>{try{let window2=readCoreEvents(directory);if(!window2.text.trim())return;let lines=window2.text.trim().split(`
7426
7426
  `),directiveIds=new Set,consumedIds=new Set;for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directiveIds.add(parsed.directiveId);else if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}}let unconsumed=[...directiveIds].filter((id)=>!consumedIds.has(id));if(unconsumed.length>0)appendCoreEventsSync(directory,unconsumed.map((directiveId)=>({type:"steering-consumed",directiveId,timestamp:new Date().toISOString()})),{ensureSwarmDir:!1})}catch{}})}init_system_guidance_carrier();init_logger();var CACHE_CAPABLE_PROVIDER_PREFIXES=["anthropic"],STRICT_FAMILY_PATTERN=/(?:^|[^a-z0-9])(?:qwen|gemma)/i;function readModelStringField(model,key2){if(typeof model!=="object"||model===null)return"";let value=model[key2];return typeof value==="string"?value:""}function resolveSystemRenderCapability(model){let providerID=readModelStringField(model,"providerID").toLowerCase();if(CACHE_CAPABLE_PROVIDER_PREFIXES.some((prefix)=>providerID.startsWith(prefix)))return"multi-system";let modelID=readModelStringField(model,"id");if(modelID.length>0&&STRICT_FAMILY_PATTERN.test(modelID))return"strict-single-system";return"multi-system"}function applySystemRenderBoundary(model,system){let capability=resolveSystemRenderCapability(model);if(!Array.isArray(system))return{capability,entriesBefore:-1,entriesAfter:-1,collapsed:!1};let entriesBefore=system.length;if(capability!=="strict-single-system"||entriesBefore<=1)return{capability,entriesBefore,entriesAfter:entriesBefore,collapsed:!1};let nonEmpty2=system.filter((entry)=>typeof entry==="string"&&entry.length>0);if(nonEmpty2.length===0)return{capability,entriesBefore,entriesAfter:entriesBefore,collapsed:!1};let joined=nonEmpty2.join(`
7427
7427
 
7428
- `);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_zod();init_state2();init_utils();init_project_boundary();init_timeout();init_utils();init_timeout();var V2_REGISTRATION_TIMEOUT_MS=60000;function mapV1AgentToV2(name,config3){let info={id:name,name,mode:config3.mode==="primary"||config3.mode==="subagent"||config3.mode==="all"?config3.mode:"subagent",hidden:!1,request:{settings:{},headers:{},body:{}}};if(typeof config3.prompt==="string"&&config3.prompt.length>0)info.system=config3.prompt;if(typeof config3.description==="string"&&config3.description.length>0)info.description=config3.description;if(typeof config3.model==="string"&&config3.model.includes("/")){let separator=config3.model.indexOf("/");info.model={providerID:config3.model.slice(0,separator),id:config3.model.slice(separator+1)}}let rules=[];if(Array.isArray(config3.tools)){for(let tool3 of config3.tools)if(typeof tool3==="string"&&tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}else if(config3.tools&&typeof config3.tools==="object")for(let[tool3,enabled]of Object.entries(config3.tools)){if(enabled===!1)continue;if(tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}if(rules.length>0)info.permissions=rules;return info}function expandV1Template(template,argumentsText){return template.replaceAll("$ARGUMENTS",argumentsText).trim()}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations){if(typeof hooks2.config!=="function")return;let syntheticConfig={};await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"));let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{Object.assign(agent,mapped)})}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration);let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key2,entry]of Object.entries(commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key2,description:typeof entry.description==="string"?entry.description:void 0,execute:async(invocation)=>{let text=expandV1Template(template,invocation?.prompt?.text??""),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key2});return}await withTimeout(Promise.resolve(prompt(invocation.sessionID,{text})),V2_REGISTRATION_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key2} prompt exceeded budget`))}};editor.add(definition)}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length})}init_utils();init_timeout();var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function mapV2EventToV1(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelope.data??{},sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;let mapped=mapV2EventToV1(envelope);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function toV1MessageView(message,sessionID){let textParts=[];for(let part of message.content??[])if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID},parts:textParts}}function writeBackTextParts(message,parts){let kept=(message.content??[]).filter((part)=>!(part&&typeof part==="object"&&part.type==="text")),texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text}));message.content=[...kept,...texts]}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let views=(event.messages??[]).map((m)=>toV1MessageView(m,sessionID)),originalMessages=[...event.messages??[]];await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)});for(let i=0;i<originalMessages.length;i+=1)views[i]=toV1MessageView(originalMessages[i],sessionID)});let originalById=new Map,originalsWithoutId=[];for(let message of originalMessages){let id=typeof message.id==="string"?message.id:void 0;if(id!==void 0&&id.length>0)originalById.set(id,message);else originalsWithoutId.push(message)}let usedIds=new Set,nextIdless=0,keptParts=[];event.system=event.system??[];for(let view of views){let id=view.info.id;if(typeof id==="string"&&id.startsWith(GUIDANCE_CARRIER_ID_PREFIX)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});continue}let message;if(typeof id==="string"&&id.length>0&&originalById.has(id)&&!usedIds.has(id))message=originalById.get(id),usedIds.add(id);else if((id===void 0||id.length===0)&&nextIdless<originalsWithoutId.length)message=originalsWithoutId[nextIdless],nextIdless+=1;if(message)keptParts.push({message,parts:view.parts})}for(let{message,parts}of keptParts)writeBackTextParts(message,parts);event.messages.length=0,event.messages.push(...keptParts.map((k)=>k.message))}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_utils();init_timeout();var V2_HOOK_TIMEOUT_MS=60000;async function onV2ToolBefore(event,hooks2,directory){let handler=hooks2["tool.execute.before"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let output={args:event.input};await withTimeout(Promise.resolve(handler({tool:event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.before exceeded budget")),event.input=output.args}async function onV2ToolAfter(event,hooks2,directory){let handler=hooks2["tool.execute.after"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let output=translateV2ResultToV1Output(event);await withTimeout(Promise.resolve(handler({tool:event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.after exceeded budget")).catch((err)=>{log("v2 tool.execute.after failed (non-fatal)",{tool:event.tool,error:err instanceof Error?err.message:String(err)})})}function translateV2ResultToV1Output(event){if(event.status==="error")return{title:"error",state:"error",output:event.error&&typeof event.error.message==="string"?event.error.message:"tool error",metadata:{}};let result=event.result;return{title:"",state:"completed",output:typeof result?.content==="string"?result.content:Array.isArray(result?.content)?(result?.content).filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>p.text).join(`
7429
- `):"",metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget"));registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget"));registrations.push(after)}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget"));registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget"));registrations.push(prompt)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},permissionBridge=buildPermissionBridge(ctx),registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,permissionBridge))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx){let permission=ctx.permission;if(!permission||typeof permission.reply!=="function")return;return async(input)=>{let askInput=input;log("v2 permission bridge invoked (best-effort passthrough)",{permission:typeof askInput?.permission==="string"?askInput.permission:"unknown",patternCount:Array.isArray(askInput?.patterns)?askInput.patterns.length:0}),await withTimeout(Promise.resolve(permission.reply?.(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}var V2_SETUP_TIMEOUT_MS=60000;function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2={registrations:[]},input={client:void 0,directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget"));await withTimeout(registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: agent/command registration exceeded budget")).catch((err)=>{log("v2 agent/command registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2Tools(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool registration exceeded budget")).catch((err)=>{log("v2 tool registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ContextHook(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: guidance registration exceeded budget")).catch((err)=>{log("v2 context-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ToolHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool-hook registration exceeded budget")).catch((err)=>{log("v2 tool-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2SessionHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: prompt-hook registration exceeded budget")).catch((err)=>{log("v2 prompt-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(typeof state2.pumpStop==="function")state2.pumpStop();for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;try{ensureAgentSession(sessionID,agentName,directory)}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
7428
+ `);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_utils();init_timeout();var V2_MODEL_APPLY_TIMEOUT_MS=1e4,registeredTransform,MAX_HELD_APPLY_REGISTRATIONS=128,registrationsByAgent=new Map;function registerV2AgentTransformSurface(ctx){let transform3=ctx?.agent&&typeof ctx.agent.transform==="function"?ctx.agent.transform.bind(ctx.agent):void 0;if(registeredTransform=transform3,transform3===void 0)log("v2 agent transform surface absent; runtime model apply disabled",{})}function clearV2AgentTransformSurface(){registeredTransform=void 0;let held=[...registrationsByAgent.values()];registrationsByAgent.clear();for(let reg of held)reg.dispose().catch((err)=>{log("v2 model-apply registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function applyV2AgentModelOverride(agentName,modelString){let transform3=registeredTransform;if(transform3===void 0)return!1;let separator=modelString.indexOf("/");if(typeof agentName!=="string"||agentName.length===0||separator<=0||separator===modelString.length-1)return log("v2 model apply rejected malformed input (non-fatal)",{agentName,modelString}),!1;let providerID=modelString.slice(0,separator),id=modelString.slice(separator+1);try{let applied2=await withTimeout(Promise.resolve(transform3((editor)=>{editor.update(agentName,(agent)=>{agent.model={providerID,id}})})),V2_MODEL_APPLY_TIMEOUT_MS,Error(`[opencode-swarm] v2: model apply for ${agentName} exceeded budget`)),previous=registrationsByAgent.get(agentName);registrationsByAgent.set(agentName,applied2);while(registrationsByAgent.size>MAX_HELD_APPLY_REGISTRATIONS){let oldest=registrationsByAgent.keys().next().value;if(typeof oldest!=="string")break;let evicted=registrationsByAgent.get(oldest);registrationsByAgent.delete(oldest),evicted?.dispose().catch((err)=>{log("v2 evicted model-apply registration dispose failed (non-fatal)",{agentName:oldest,error:err instanceof Error?err.message:String(err)})})}if(previous)previous.dispose().catch((err)=>{log("v2 previous model-apply registration dispose failed (non-fatal)",{agentName,error:err instanceof Error?err.message:String(err)})});return log("v2 agent model applied",{agentName,modelString}),!0}catch(err){return log("v2 agent model apply failed (non-fatal)",{agentName,modelString,error:err instanceof Error?err.message:String(err)}),!1}}init_zod();init_loader();init_model_preflight();init_warning_buffer();init_state2();init_utils();init_project_boundary();init_timeout();init_utils();init_timeout();var V2_REGISTRATION_TIMEOUT_MS=60000;function mapV1AgentToV2(name,config3){let info={id:name,name,mode:config3.mode==="primary"||config3.mode==="subagent"||config3.mode==="all"?config3.mode:"subagent",hidden:!1,request:{settings:{},headers:{},body:{}}};if(typeof config3.prompt==="string"&&config3.prompt.length>0)info.system=config3.prompt;if(typeof config3.description==="string"&&config3.description.length>0)info.description=config3.description;if(typeof config3.model==="string"&&config3.model.includes("/")){let separator=config3.model.indexOf("/");info.model={providerID:config3.model.slice(0,separator),id:config3.model.slice(separator+1)}}let rules=[];if(Array.isArray(config3.tools)){for(let tool3 of config3.tools)if(typeof tool3==="string"&&tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}else if(config3.tools&&typeof config3.tools==="object")for(let[tool3,enabled]of Object.entries(config3.tools)){if(enabled===!1)continue;if(tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}if(rules.length>0)info.permissions=rules;return info}function expandV1Template(template,argumentsText){return template.replaceAll("$ARGUMENTS",argumentsText).trim()}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations){if(typeof hooks2.config!=="function")return;let syntheticConfig={};await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"));let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{Object.assign(agent,mapped)})}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration);let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key2,entry]of Object.entries(commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key2,description:typeof entry.description==="string"?entry.description:void 0,execute:async(invocation)=>{let text=expandV1Template(template,invocation?.prompt?.text??""),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key2});return}await withTimeout(Promise.resolve(prompt(invocation.sessionID,{text})),V2_REGISTRATION_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key2} prompt exceeded budget`))}};editor.add(definition)}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length})}init_task_model_routing();init_utils();init_timeout();var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function mapV2EventToV1(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelope.data??envelope.properties??{},sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.status":return{type:"session.status",properties:{...sessionID?{sessionID}:{},...data}};case"session.error":case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function seedSessionIdentityFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.created"&&type!=="session.agent.selected")return;let payload=envelope.data??envelope.properties??{},sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,agent=typeof payload.agent==="string"?payload.agent:void 0;if(sessionID&&agent)recordSessionChatAgent(sessionID,agent)}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;seedSessionIdentityFromEnvelope(envelope);let mapped=mapV2EventToV1(envelope);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function toV1MessageView(message,sessionID){let textParts=[];for(let part of message.content??[])if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID},parts:textParts}}function writeBackTextParts(message,parts){let kept=(message.content??[]).filter((part)=>!(part&&typeof part==="object"&&part.type==="text")),texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text}));message.content=[...kept,...texts]}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let views=(event.messages??[]).map((m)=>toV1MessageView(m,sessionID)),originalMessages=[...event.messages??[]];await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)});for(let i=0;i<originalMessages.length;i+=1)views[i]=toV1MessageView(originalMessages[i],sessionID)});let originalById=new Map,originalsWithoutId=[];for(let message of originalMessages){let id=typeof message.id==="string"?message.id:void 0;if(id!==void 0&&id.length>0)originalById.set(id,message);else originalsWithoutId.push(message)}let usedIds=new Set,nextIdless=0,keptParts=[];event.system=event.system??[];for(let view of views){let id=view.info.id;if(typeof id==="string"&&id.startsWith(GUIDANCE_CARRIER_ID_PREFIX)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});continue}let message;if(typeof id==="string"&&id.length>0&&originalById.has(id)&&!usedIds.has(id))message=originalById.get(id),usedIds.add(id);else if((id===void 0||id.length===0)&&nextIdless<originalsWithoutId.length)message=originalsWithoutId[nextIdless],nextIdless+=1;if(message)keptParts.push({message,parts:view.parts})}for(let{message,parts}of keptParts)writeBackTextParts(message,parts);event.messages.length=0,event.messages.push(...keptParts.map((k)=>k.message))}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_utils();init_timeout();var V2_HOOK_TIMEOUT_MS=60000;async function onV2ToolBefore(event,hooks2,directory){let handler=hooks2["tool.execute.before"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let output={args:event.input};await withTimeout(Promise.resolve(handler({tool:event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.before exceeded budget")),event.input=output.args}async function onV2ToolAfter(event,hooks2,directory){let handler=hooks2["tool.execute.after"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let output=translateV2ResultToV1Output(event);await withTimeout(Promise.resolve(handler({tool:event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.after exceeded budget")).catch((err)=>{log("v2 tool.execute.after failed (non-fatal)",{tool:event.tool,error:err instanceof Error?err.message:String(err)})})}function translateV2ResultToV1Output(event){if(event.status==="error")return{title:"error",state:"error",output:event.error&&typeof event.error.message==="string"?event.error.message:"tool error",metadata:{}};let result=event.result;return{title:"",state:"completed",output:typeof result?.content==="string"?result.content:Array.isArray(result?.content)?(result?.content).filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>p.text).join(`
7429
+ `):"",metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget"));registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget"));registrations.push(after)}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget"));registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget"));registrations.push(prompt)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},permissionBridge=buildPermissionBridge(ctx),registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,permissionBridge))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx){let permission=ctx.permission;if(!permission||typeof permission.reply!=="function")return;return async(input)=>{let askInput=input;log("v2 permission bridge invoked (best-effort passthrough)",{permission:typeof askInput?.permission==="string"?askInput.permission:"unknown",patternCount:Array.isArray(askInput?.patterns)?askInput.patterns.length:0}),await withTimeout(Promise.resolve(permission.reply?.(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}async function deferredV2StartupModelPreflight(directory){try{let loaded=await withTimeout(Promise.resolve(loadPluginConfigWithMeta(directory)),2000,Error("[opencode-swarm] v2: startup preflight config read exceeded budget")),models=collectEnabledAgentModels(loaded?.config).map((entry)=>entry.model).filter((model)=>typeof model==="string"&&model.length>0),quiet=loaded?.config?.quiet===!0;for(let warning of collectModelRosterWarnings(models,VERIFIED_KEYLESS_MODEL_ROSTER))if(addDeferredWarning(warning),!quiet)console.warn(warning)}catch(err){log("v2 startup model preflight failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}var V2_SETUP_TIMEOUT_MS=60000;function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2={registrations:[]},input={client:void 0,directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget"));await withTimeout(registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: agent/command registration exceeded budget")).catch((err)=>{log("v2 agent/command registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2Tools(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool registration exceeded budget")).catch((err)=>{log("v2 tool registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ContextHook(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: guidance registration exceeded budget")).catch((err)=>{log("v2 context-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ToolHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool-hook registration exceeded budget")).catch((err)=>{log("v2 tool-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2SessionHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: prompt-hook registration exceeded budget")).catch((err)=>{log("v2 prompt-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,registerV2AgentTransformSurface(ctx),await withTimeout(deferredV2StartupModelPreflight(directory),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2: startup model preflight exceeded budget")),state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(typeof state2.pumpStop==="function")state2.pumpStop();clearV2AgentTransformSurface();for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;try{ensureAgentSession(sessionID,agentName,directory)}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
7430
7430
  `).slice(0,SCREENING_PROMPT_CAP)}async function screenCandidate(candidate2,deps){let perCandidateMs=deps.llmTimeoutMs??0;if(!deps.llmDelegate||perCandidateMs<=0||!deps.sessionID)return!0;let llmDelegate=deps.llmDelegate;if(!deps.llmBudget)return!0;let remainingMs2=deps.remainingBudgetMs?.()??Number.POSITIVE_INFINITY,timeoutMs=Math.min(perCandidateMs,Math.max(0,remainingMs2));if(timeoutMs<=0)return!0;if(!reserveLlmBudget(deps.sessionID,SCREENING_TOKEN_ESTIMATE,deps.llmBudget))return!0;return!/\bREJECT\b/i.test(await withTimeoutSignal((signal2)=>llmDelegate("",buildScreeningPrompt(candidate2),signal2),timeoutMs,Error(`Knowledge admission screening timed out after ${timeoutMs}ms`)))}async function admitCandidate(directory,candidate2,deps){let candidateId2=resolveInsightCandidateId(candidate2),marker=insightAdmissionMarker(candidateId2),now2=deps.now??(()=>Date.now());if(!validateActionableFields({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks,triggers:candidate2.triggers,directive_priority:candidate2.directive_priority}).valid)return{outcome:"rejected",reason:"invalid_shape",marker};let actionability=validateActionability({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks});if(!actionability.actionable)return{outcome:"rejected",reason:actionability.reason??"unactionable",marker};if(!await screenCandidate(candidate2,deps))return{outcome:"rejected",reason:"screened_out",marker};let provenance=stampLearningProvenance({mechanism:candidate2.source?.kind==="prm_pattern"?"prm_pattern":"micro_reflection",sourceKnowledgeIds:[marker],sourceTaskIds:candidate2.source?.task_id?[candidate2.source.task_id]:[],sourceEvidenceRefs:candidate2.source_refs??[]},{sessionId:deps.sessionID,agentRole:candidate2.source?.agent,producedAt:new Date(now2()).toISOString()}),knowledgePath=(deps.resolveKnowledgePath??resolveSwarmKnowledgePath)(directory),entry=insightCandidateToEntry(candidate2,deps.projectName,deps.phaseNumber,deps.knowledgeConfig);if(unionSourceKnowledgeIds(entry,provenance.sourceKnowledgeIds),provenance.sourceEvidenceRefs.length>0){let refs=new Set([...entry.source_refs??[],...provenance.sourceEvidenceRefs]);entry.source_refs=[...refs]}let outcome="rejected",reason="no_change",entryId;if(await transactKnowledge(knowledgePath,(current)=>{if(findActiveEntryWithMarker(current,marker))return outcome="rejected",reason="already_admitted",null;let duplicate=findActiveSwarmNearDuplicate(entry.lesson,current,deps.knowledgeConfig.dedup_threshold);if(duplicate){let result=reinforceSwarmKnowledgeEntry(duplicate,{phase_number:deps.phaseNumber,confirmed_at:new Date(now2()).toISOString(),project_name:deps.projectName});return unionSourceKnowledgeIds(duplicate,[marker]),outcome="reinforced",reason=result.reason,entryId=duplicate.id,current}return current.push(entry),outcome="admitted",reason=void 0,entryId=entry.id,current}),outcome!=="rejected")deps.onKnowledgeChanged?.();return{outcome,reason,entryId,marker,provenance}}async function realtimeAdmissionAfter(directory,input,config3,resolveDeps){if(!isTaskTool(input.tool))return;if(!config3?.enabled)return;let sessionID=typeof input.sessionID==="string"&&input.sessionID.length>0?input.sessionID:void 0;if(!sessionID)return;if(getQueueDepth(sessionID)===0)return;let deps=await resolveDeps();return drainSessionQueue(directory,sessionID,config3,deps)}function emptySummary(){return{attempted:0,admitted:0,reinforced:0,rejected:0,deferred:0,failed:0,retries:0}}async function drainSessionQueue(directory,sessionID,config3,deps){let summary=emptySummary();if(!config3.enabled)return summary;let now2=deps.now??(()=>Date.now()),stats2=getQueueStats(sessionID);if(stats2.depth===0)return summary;let velocity=computeArrivalVelocity(stats2,now2()),size=computeDrainSize(stats2.depth,velocity,{minDrain:config3.min_drain,maxDrain:config3.max_drain,drainDepthFactor:config3.drain_depth_factor,drainVelocityFactor:config3.drain_velocity_factor});if(size<=0)return summary;let batch=takeDrainBatch(sessionID,size);if(batch.length===0)return summary;summary.attempted=batch.length;let startedAt=now2(),wallTimeMs=Math.max(0,Number(config3.max_drain_wall_time_ms)||0),deadline=wallTimeMs>0?startedAt+wallTimeMs:Number.POSITIVE_INFINITY,budgetExhausted=()=>now2()>=deadline,maxRetries=Math.max(0,Math.floor(Number(config3.max_retries_per_candidate)||0)),limit=pLimit(Math.max(1,Math.floor(Number(config3.max_concurrent_admissions)||1))),admissionDeps={...deps,sessionID,llmTimeoutMs:config3.max_llm_calls_per_session>0?deps.llmTimeoutMs??config3.per_candidate_llm_timeout_ms:0,llmBudget:deps.llmBudget??{maxLlmCallsPerSession:config3.max_llm_calls_per_session,maxTokensPerSession:config3.max_tokens_per_session},remainingBudgetMs:()=>deadline-now2()},deferOrAbandon=(item)=>{if(item.attempts>=MAX_CANDIDATE_DRAIN_ATTEMPTS){summary.failed++,warn(`[learning-admission] candidate abandoned after ${item.attempts} drain attempt(s) without completing`);return}requeueCandidate(sessionID,item,{maxQueueSize:config3.max_queue_size}),summary.deferred++};return await Promise.all(batch.map((item)=>limit(async()=>{if(budgetExhausted()){deferOrAbandon(item);return}for(let attempt=0;;attempt++)try{let result=await admitCandidate(directory,item.candidate,admissionDeps);if(result.outcome==="admitted")summary.admitted++;else if(result.outcome==="reinforced")summary.reinforced++;else summary.rejected++;return}catch(err){if(attempt>=maxRetries){warn(`[learning-admission] candidate failed after ${attempt+1} attempt(s): ${isAbortError(err)?"cancelled":err instanceof Error?err.message:String(err)}`),deferOrAbandon(item);return}if(summary.retries++,recordRetry(sessionID),budgetExhausted()){deferOrAbandon(item);return}}}))),summary}init_memory();init_provider_pool();init_task_model_routing();init_observability();init_otlp_exporter();init_startup_contract();init_manager();init_prm();init_trajectory_store();init_sweep();init_ephemeral_agent_dispatcher();function createReviewModelDispatcher(client,pricing){return{dispatch:(request)=>dispatchEphemeralAgent({client,directory:request.directory,parentSessionId:request.parentSessionId,agentName:request.agentName,model:request.model,system:request.system,prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:request.title,timeoutMs:request.timeoutMs&&request.timeoutMs>0?request.timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,promptByteLimit:request.promptByteLimit,responseByteLimit:request.responseByteLimit,abortSignal:request.abortSignal,pricing})}}init_finding_validator();init_runtime3();init_compaction_service();init_config_doctor();init_cost_accounting();init_injection_budget();init_model_preflight();init_version_check();init_snapshot_coordination_init();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();init_state2();init_telemetry();init_startup_contract();init_zod();init_agents2();init_schema();init_runtime3();init_state2();init_telemetry();init_ephemeral_session_teardown();init_model_dispatch_fallback();init_provider_error_classification();init_swarm_artifact_cache();import*as fs175 from"node:fs/promises";import*as path306 from"node:path";init_bun_compat();init_swarm_artifact_cache();import{rmSync as rmSync32}from"node:fs";import*as fs174 from"node:fs/promises";import*as path305 from"node:path";function leanTurboEvidenceDir(directory,phase){return path305.join(directory,".swarm","evidence",String(phase),"lean-turbo")}function validateLaneId(laneId){if(laneId.length===0)throw Error("Invalid laneId: empty string is not allowed");if(laneId.length>128)throw Error(`Invalid laneId: exceeds maximum length of 128 characters (got ${laneId.length})`);if(laneId.includes("/")||laneId.includes("\\"))throw Error(`Invalid laneId: path separators are not allowed (got "${laneId}")`);if(laneId.includes(".."))throw Error(`Invalid laneId: parent-directory references are not allowed (got "${laneId}")`);if(laneId.startsWith("/")||/^[a-zA-Z]:/i.test(laneId))throw Error(`Invalid laneId: absolute paths are not allowed (got "${laneId}")`)}function laneEvidencePath(directory,phase,laneId){validateLaneId(laneId);let expectedDir=leanTurboEvidenceDir(directory,phase),resolvedPath=path305.resolve(path305.join(expectedDir,`${laneId}.json`)),resolvedDir=path305.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path305.sep)&&resolvedPath!==resolvedDir)throw Error(`Invalid laneId: path traversal detected (got "${laneId}")`);return resolvedPath}async function atomicWriteJson(filePath,data){let content=JSON.stringify(data,null,2),dir=path305.dirname(filePath);await fs174.mkdir(dir,{recursive:!0});let tempPath=`${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await bunWrite(tempPath,content),await fs174.rename(tempPath,filePath),invalidateCachedArtifact(filePath)}catch(error93){try{rmSync32(tempPath,{force:!0})}catch{}throw error93}}function phaseEvidencePath(directory,phase){return path305.join(leanTurboEvidenceDir(directory,phase),"lean-turbo-phase.json")}async function writeLaneEvidence(directory,phase,evidence2){let targetPath=laneEvidencePath(directory,phase,evidence2.laneId);await atomicWriteJson(targetPath,evidence2)}async function writePhaseEvidence(directory,evidence2){let targetPath=phaseEvidencePath(directory,evidence2.phase);await atomicWriteJson(targetPath,evidence2)}async function readPhaseEvidence(directory,phase){let targetPath=phaseEvidencePath(directory,phase),content;try{content=await fs174.readFile(targetPath,"utf-8")}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw error93}try{return JSON.parse(content)}catch{return null}}async function listLaneEvidence(directory,phase){let evidenceDir=leanTurboEvidenceDir(directory,phase),entries2;try{entries2=await fs174.readdir(evidenceDir)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw error93}entries2.sort();let lanes=[];for(let entry of entries2){if(!entry.endsWith(".json"))continue;if(entry==="lean-turbo-phase.json")continue;let filePath=path305.join(evidenceDir,entry),content;try{content=await fs174.readFile(filePath,"utf-8")}catch{continue}try{let parsed=JSON.parse(content);lanes.push(parsed)}catch{}}return lanes}var DEFAULT_CONFIG2={criticAgent:"",timeoutMs:0};function resolveDefaultCriticAgent(generatedAgentNames,activeAgentName){return resolveAgentForActiveSwarm(generatedAgentNames,"critic",activeAgentName)}function resolveLegacyCriticModelConfig(agentName,config3){if(config3?.dispatcher||config3?.agentModelRegistry)return;let agentBaseName=stripKnownSwarmPrefix(agentName),swarmId=agentBaseName!==agentName?agentName.slice(0,agentName.length-agentBaseName.length-1):void 0;return{agentBaseName,swarmAgents:getSwarmAgents(swarmId)}}async function readReviewerEvidence(directory,phase){let evidencePath=path306.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json"),content;try{content=await fs175.readFile(evidencePath,"utf-8")}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw error93}try{return JSON.parse(content)}catch{return null}}async function compileCriticPackage(directory,phase,sessionID){let lanes=await listLaneEvidence(directory,phase),phaseEvidence=await readPhaseEvidence(directory,phase),reviewerEvidence=await readReviewerEvidence(directory,phase),filesChangedSet=new Set;for(let lane of lanes)for(let file3 of lane.files)filesChangedSet.add(file3);let completedLanes=lanes.filter((l)=>l.status==="completed").length,failedLanes=lanes.filter((l)=>l.status==="failed").length,laneSummaries=lanes.map((lane)=>({laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:lane.status,agent:lane.agent})),degradedTasks=phaseEvidence?.degradedTasks??[],pendingDegraded=degradedTasks.filter((dt)=>!lanes.some((l)=>l.taskIds.includes(dt.taskId)&&l.status==="completed")).length,safetyConcerns=[];if(!reviewerEvidence)safetyConcerns.push("Reviewer evidence is missing — critic cannot verify reviewer assessment");else if(reviewerEvidence.verdict==="REJECTED")safetyConcerns.push(`Reviewer verdict is REJECTED: ${reviewerEvidence.reason??"no reason provided"}`);else if(reviewerEvidence.verdict==="NEEDS_REVISION")safetyConcerns.push(`Reviewer verdict is NEEDS_REVISION: ${reviewerEvidence.reason??"no reason provided"}`);if(pendingDegraded>0)safetyConcerns.push(`${pendingDegraded} degraded task(s) remain unresolved`);if(failedLanes>0)safetyConcerns.push(`${failedLanes} lane(s) failed`);let pkg={phase,sessionID,reviewerVerdict:reviewerEvidence?.verdict,reviewerMissing:!reviewerEvidence,safetyConcerns,laneSummaries,filesChanged:[...filesChangedSet],testResults:{totalLanes:lanes.length,completedLanes,failedLanes},degradationSummary:{totalDegraded:degradedTasks.length,resolvedDegraded:degradedTasks.length-pendingDegraded,pendingDegraded}};if(phaseEvidence?.validationArtifacts)pkg.validationArtifacts=phaseEvidence.validationArtifacts;return pkg}function parseCriticVerdict2(responseText){let verdictMatch=responseText.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED|ESCALATE_TO_HUMAN)/);if(!verdictMatch)return null;let verdict=verdictMatch[1],lines=responseText.split(`
7431
7431
  `),verdictIndex=lines.findIndex((l)=>l.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED|ESCALATE_TO_HUMAN)/i)),reason;if(verdictIndex>=0&&verdictIndex+1<lines.length){let reasonMatch=lines[verdictIndex+1].match(/^REASON\s*:\s*(.+)/i);if(reasonMatch)reason=reasonMatch[1].trim()}return{verdict,reason}}async function writeCriticEvidence(directory,phase,verdict,reason){let evidenceDir=path306.join(directory,".swarm","evidence",String(phase));await fs175.mkdir(evidenceDir,{recursive:!0});let evidencePath=path306.join(evidenceDir,"lean-turbo-critic.json"),content=JSON.stringify({phase,verdict,reason:reason??null,timestamp:new Date().toISOString()},null,2),tempPath=`${evidencePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await fs175.writeFile(tempPath,content,"utf-8"),await fs175.rename(tempPath,evidencePath),invalidateCachedArtifact(evidencePath)}catch(error93){try{await fs175.unlink(tempPath)}catch{}throw error93}return evidencePath}async function dispatchCriticWithReviewDispatcher(dispatcher,directory,criticPackage,agentName,timeoutMs,parentSessionId,model){let result=await dispatcher.dispatch({directory,parentSessionId,agentName,model,system:"You are a read-only phase critic for Lean Turbo execution. Evaluate phase-boundary safety, lane integrity, degraded tasks, and the reviewer verdict. Conclude with exactly one verdict marker and a REASON line.",prompt:`Review this boundary evidence and conclude with VERDICT: APPROVED, NEEDS_REVISION, REJECTED, or ESCALATE_TO_HUMAN plus a REASON line.
7432
7432
 
@@ -7875,4 +7875,4 @@ ${footerLines.join(`
7875
7875
  `:""}`}function gitBlobObjectId(content,algorithm){let header=Buffer.from(`blob ${content.byteLength}\x00`,"utf8");return createHash118(algorithm).update(header).update(content).digest("hex")}function matchesDeclaredObjectId(actual,declared){return/^0+$/.test(declared)?!1:actual.startsWith(declared)}function decodeTextFile(relativePath2,buffer){if(buffer.includes(0))throw Error(`binary file rejected: ${relativePath2}`);return TEXT_DECODER.decode(buffer)}function parseBaseTreeEntry(output){let trimmed=output.split("\x00").find(Boolean)?.trim();if(!trimmed)return null;let match=/^(\d{6}) blob ([a-f0-9]{40,64})\t(.+)$/.exec(trimmed);if(!match)return null;return{mode:match[1],objectId:match[2],relativePath:normalizeRelativePath2(match[3])}}function fail3(code,reason){return{ok:!1,code,reason}}function snapshotPathIdentity(absolutePath2){if(!existsSync202(absolutePath2))return{exists:!1};let stat25=_internals319.lstatSync(absolutePath2),isSymbolicLink=typeof stat25.isSymbolicLink==="function"?stat25.isSymbolicLink():!1,isFile=typeof stat25.isFile==="function"?stat25.isFile():!1;return{exists:!0,isSymbolicLink,isFile,nlink:stat25.nlink,size:stat25.size,mtimeMs:stat25.mtimeMs,ctimeMs:stat25.ctimeMs,dev:stat25.dev,ino:stat25.ino,mode:stat25.mode}}function samePathIdentity(left,right){if(left.exists!==right.exists)return!1;if(!left.exists)return!0;return left.isSymbolicLink===right.isSymbolicLink&&left.isFile===right.isFile&&left.nlink===right.nlink&&left.size===right.size&&left.mtimeMs===right.mtimeMs&&left.ctimeMs===right.ctimeMs&&left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode}async function validateSourceCandidate(args2){if(assertProjectRoot(args2.directory),args2.config.source_allowlist.length===0)return fail3("ALLOWLIST_EMPTY","harness source allowlist is empty");if(!SHA_RE.test(args2.baseSha))return fail3("INVALID_BASE_SHA","baseSha must be a 40-64 hex digest");if(Buffer.byteLength(args2.patch,"utf8")>args2.config.max_patch_bytes)return fail3("PATCH_TOO_LARGE",`patch exceeds max_patch_bytes (${args2.config.max_patch_bytes})`);let base=await _internals319.runGitCommand(args2.directory,["rev-parse","HEAD"]);if(!base.ok)return fail3("GIT_FAILED",`git rev-parse failed: ${base.stderr||base.stdout}`);let currentBase=base.stdout.trim().toLowerCase();if(currentBase!==args2.baseSha.toLowerCase())return fail3("STALE_BASE",`source candidate base ${args2.baseSha} does not match current HEAD ${currentBase}`);let parsed=parsePatch(args2.patch);if(!parsed)return fail3("UNSUPPORTED_PATCH","patch grammar is not an admitted two-way unified diff");if(parsed.files.length>args2.config.max_files)return fail3("FILE_COUNT_EXCEEDED",`patch touches ${parsed.files.length} files, exceeding max_files ${args2.config.max_files}`);let approvedPaths=[],files=[],admittedPathSnapshots=new Map,totalBytes=0,totalChangedLines=0;for(let filePatch of parsed.files){let relativePath2=normalizeRelativePath2(filePatch.relativePath),oldRelativePath=filePatch.oldRelativePath?normalizeRelativePath2(filePatch.oldRelativePath):null;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let rejection=validateTargetWithinRoot(admittedPath,args2.directory);if(rejection)return fail3("PATH_REJECTED",`${admittedPath}: ${rejection}`);if(!isAllowlisted(admittedPath,args2.config.source_allowlist))return fail3("PATH_NOT_ALLOWLISTED",`${admittedPath} is outside the harness source allowlist`);if(isProtectedPath4(admittedPath,args2.config.extra_protected_paths))return fail3("PROTECTED_PATH",`${admittedPath} is protected from harness source candidates`)}let sourcePath=oldRelativePath??relativePath2;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let absolutePath2=path381.resolve(args2.directory,admittedPath),identity=snapshotPathIdentity(absolutePath2);if(admittedPathSnapshots.set(admittedPath,identity),!identity.exists)continue;if(identity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} is a symlink or junction`);if(identity.isFile&&(identity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} is a hardlinked file and is not trusted for harness source candidates`)}let tracked=await _internals319.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",sourcePath]);if(!tracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${sourcePath}`);let trackedEntry=parseBaseTreeEntry(tracked.stdout);if(!trackedEntry&&filePatch.operation!=="add")return fail3("UNTRACKED_PATH",`${sourcePath} is not tracked`);if(trackedEntry&&filePatch.operation==="add")return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`);if(filePatch.oldObjectId){if(filePatch.operation==="add"){if(!/^0+$/.test(filePatch.oldObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} add has a non-zero old object id`)}else if(!trackedEntry||!matchesDeclaredObjectId(trackedEntry.objectId,filePatch.oldObjectId))return fail3("STALE_BASE",`${sourcePath} object id does not match the declared patch base`)}if(filePatch.operation!=="add"&&(!trackedEntry||trackedEntry.relativePath!==sourcePath))return fail3("UNTRACKED_PATH",`${sourcePath} is not an admitted tracked file`);if(relativePath2!==sourcePath){let targetTracked=await _internals319.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",relativePath2]);if(!targetTracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${relativePath2}`);if(parseBaseTreeEntry(targetTracked.stdout))return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`)}let trackedMode=trackedEntry?.mode??filePatch.newMode??"100644";if(!["100644","100755"].includes(trackedMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} uses unsupported tracked mode ${trackedMode}`);let beforeBuffer=Buffer.alloc(0);if(trackedEntry){let baseBlob=await _internals319.runGitBinaryCommand(args2.directory,["show","--no-textconv",`${args2.baseSha}:${sourcePath}`],args2.config.max_file_bytes+1);if(!baseBlob.ok)return fail3("GIT_FAILED",`git show failed for ${sourcePath}: ${baseBlob.stderr}`);beforeBuffer=baseBlob.stdout}let beforeText;try{beforeText=decodeTextFile(relativePath2,beforeBuffer)}catch(error93){return fail3("BINARY_FILE",error93 instanceof Error?error93.message:String(error93))}let patchedText=filePatch.hunks.length===0?beforeText:applyFilePatch(beforeText,filePatch);if(patchedText===null)return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} did not apply cleanly`);let afterText=filePatch.operation==="delete"?"":patchedText;if(filePatch.newObjectId)if(filePatch.operation==="delete"){if(!/^0+$/.test(filePatch.newObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} delete has a non-zero new object id`)}else{let objectAlgorithm=args2.baseSha.length===64?"sha256":"sha1",actualObjectId=gitBlobObjectId(Buffer.from(afterText,"utf8"),objectAlgorithm);if(!matchesDeclaredObjectId(actualObjectId,filePatch.newObjectId))return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} object id does not match reconstructed output`)}if(filePatch.newMode&&!["100644","100755"].includes(filePatch.newMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} requests unsupported mode ${filePatch.newMode}`);if(filePatch.oldMode&&trackedEntry&&filePatch.oldMode!==trackedMode)return fail3("UNSUPPORTED_TRACKED_MODE",`${sourcePath} mode does not match the tracked base`);if(afterText.includes("\x00"))return fail3("BINARY_FILE",`${relativePath2} patch produces binary output`);let bytesBefore=Buffer.byteLength(beforeText,"utf8"),bytesAfter=Buffer.byteLength(afterText,"utf8");if(Math.max(bytesBefore,bytesAfter)>args2.config.max_file_bytes)return fail3("FILE_TOO_LARGE",`${relativePath2} exceeds max_file_bytes ${args2.config.max_file_bytes}`);if(totalBytes+=bytesAfter,totalBytes>args2.config.max_total_bytes)return fail3("TOTAL_TOO_LARGE",`patched output exceeds max_total_bytes ${args2.config.max_total_bytes}`);let addedLines=0,removedLines=0;for(let line of filePatch.hunks.flatMap((hunk)=>hunk.lines)){if(line.startsWith("+")&&!line.startsWith("+++"))addedLines++;if(line.startsWith("-")&&!line.startsWith("---"))removedLines++}let changedLines=addedLines+removedLines;if(totalChangedLines+=changedLines,totalChangedLines>args2.config.max_changed_lines)return fail3("LINE_COUNT_EXCEEDED",`patch exceeds max_changed_lines ${args2.config.max_changed_lines}`);approvedPaths.push(relativePath2),files.push({relativePath:relativePath2,...oldRelativePath&&oldRelativePath!==relativePath2?{oldRelativePath}:{},operation:filePatch.operation,trackedMode,...filePatch.newMode?{afterMode:filePatch.newMode}:{},beforeSha256:sha2569(beforeText),afterSha256:sha2569(afterText),bytesBefore,bytesAfter,addedLines,removedLines,changedLines})}for(let[admittedPath,initialIdentity]of admittedPathSnapshots){let absolutePath2=path381.resolve(args2.directory,admittedPath),finalIdentity=snapshotPathIdentity(absolutePath2);if(!samePathIdentity(initialIdentity,finalIdentity))return fail3("PATH_CHANGED_DURING_VALIDATION",`${admittedPath} changed on disk while the harness source candidate was being validated`);if(finalIdentity.exists&&finalIdentity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} became a symlink or junction during validation`);if(finalIdentity.exists&&finalIdentity.isFile&&(finalIdentity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} became a hardlinked file during validation`)}let manifestBase={v:RECORD_VERSION2,candidateId:args2.candidateId,baseSha:args2.baseSha.toLowerCase(),origin:args2.origin,patchSha256:sha2569(args2.patch),promptArtifactHashes:[],approvedPaths:[...approvedPaths].sort(),files},riskTier=deriveHarnessCandidateRiskTier(manifestBase),manifestHash2=computeHarnessCandidateManifestHash(manifestBase);return{ok:!0,candidate:{...parseHarnessCandidateManifest({...manifestBase,riskTier,manifestHash:manifestHash2}),patch:args2.patch}}}async function runGitCommand(directory,args2){return new Promise((resolve153)=>{let stdout="",stderr="",stdoutBytes=0,stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve153(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stdoutBytes);stdout+=slice.toString("utf8"),stdoutBytes+=slice.byteLength}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout,stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout,stderr})})})}async function runGitBinaryCommand(directory,args2,maxOutputBytes=MAX_GIT_OUTPUT_BYTES3){return new Promise((resolve153)=>{let stdoutChunks=[],stdoutBytes=0,stderr="",stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve153(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=maxOutputBytes)return;let slice=chunk.subarray(0,maxOutputBytes-stdoutBytes);if(stdoutChunks.push(slice),stdoutBytes+=slice.byteLength,slice.byteLength<chunk.byteLength||stdoutBytes>=maxOutputBytes)finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:`git output exceeds bound ${maxOutputBytes}`})}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout:Buffer.concat(stdoutChunks),stderr})})})}var _internals319={runGitCommand,runGitBinaryCommand,lstatSync:lstatSync44};init_store3();function projectStaticBlueprint2(agents){let runtimeDefinitions=Object.entries(agents).sort(([leftKey,left],[rightKey,right])=>left.name.localeCompare(right.name)||leftKey.localeCompare(rightKey)).map(([,agent])=>{let config3=agent.config,tools=config3.tools?Object.fromEntries(Object.entries(config3.tools).sort(([a],[b])=>a.localeCompare(b))):config3.tools;return{name:agent.name,description:agent.description,config:{...config3,tools,mode:config3.mode==="primary"?"primary":"subagent",temperature:config3.temperature??0.1,prompt:config3.prompt??`Static runtime definition for ${agent.name}`}}}),registeredToolIds=[...new Set(runtimeDefinitions.flatMap((definition)=>Object.keys(definition.config.tools??{})))].sort();return createAgentFactory({runtimeDefinitions,registeredToolIds}).projectBlueprint({blueprintId:"static-runtime-shadow"})}function diffHarnessBlueprints(left,right){let changes={};for(let key2 of[...new Set([...Object.keys(left),...Object.keys(right)])].sort())if(canonicalJson6(left[key2])!==canonicalJson6(right[key2]))changes[key2]={before:left[key2],after:right[key2]};return{changes,summary:{changeCount:Object.keys(changes).length,changedKeys:Object.keys(changes).sort()}}}var harnessMutationV1=Object.freeze(Object.assign(function(){return harnessMutationV1},{validateBlueprint:parseHarnessBlueprint,projectStaticBlueprint:projectStaticBlueprint2,applyPatchSet:applyBlueprintPatch,validateSourceCandidate,saveCandidate:recordHarnessCandidate,saveVersion:saveHarnessVersion,activate:activateHarnessCandidate,rollback:rollbackHarnessVersion,current:loadHarnessCurrent,history:listHarnessHistory,diff:diffHarnessBlueprints,auditLedger:auditHarnessLedger,recoverCorruptTail:recoverHarnessCorruptTail}));markStartupImportComplete();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500,_architectCompactionPending=new Map,MAX_TRACKED_ARCHITECT_COMPACTIONS=500,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS=250;function capSessionMap(map3,max,justInserted){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0||oldest===justInserted)break;map3.delete(oldest)}}function resolveSoundingBoardCallerCategory(args2){if(!args2||typeof args2!=="object"||Array.isArray(args2))return{supplied:!1};let record3=args2;if(Object.hasOwn(record3,"category"))return{supplied:!0,value:record3.category};return{supplied:!1}}function applySoundingBoardResponsePolicy(rawResponse,args2){let callerCategory=resolveSoundingBoardCallerCategory(args2),parsed=parseSoundingBoardResponse(rawResponse,callerCategory.supplied?{category:callerCategory.value}:void 0);if(!parsed)return null;let guarded=applyAlwaysSurfacePolicy(parsed);if(guarded.protocolError&&guarded.verdict==="UNNECESSARY")return{...guarded,verdict:"APPROVED",warning:guarded.warning??"Invalid or missing Category metadata; verdict was surfaced as APPROVED."};return guarded}var instanceExitCleanups=new Map,instanceExitCleanupCounter=0,processExitCleanupRegistered=!1,processSignalCleanupHandlers=[],signalExitCleanupInFlight=!1;function runInstanceExitCleanups(){for(let cleanup of instanceExitCleanups.values())try{cleanup()}catch{}}function makeSignalExitCleanupHandler(signal2){let handler=()=>{if(signalExitCleanupInFlight)return;signalExitCleanupInFlight=!0;try{runInstanceExitCleanups()}catch{}finally{process.off(signal2,handler),process.kill(process.pid,signal2)}};return handler}function registerProcessExitCleanupDispatcher(){if(processExitCleanupRegistered)return;processExitCleanupRegistered=!0,process.on("exit",runInstanceExitCleanups),processSignalCleanupHandlers=[{signal:"SIGINT",handler:makeSignalExitCleanupHandler("SIGINT")},{signal:"SIGTERM",handler:makeSignalExitCleanupHandler("SIGTERM")}];for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.on(signal2,handler)}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear(),pendingCostCorrectionByChildSession.clear(),scheduledCostCorrectionRecoveryBySession.clear(),latestAssistantUsageBySession.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path383.resolve(path383.dirname(fileURLToPath8(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS=1e4,TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS=1e4,RETENTION_SWEEP_INIT_TIMEOUT_MS=5000,LOAD_PLUGIN_CONFIG_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents,options={}){let surface=options.surface??"system";return async(input,output)=>{let{sessionID,agent,expectedGeneration}=input,activeAgentName=sessionID?surface==="messages"?agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName:swarmState.activeAgent.get(sessionID)??agent??swarmState.agentSessions.get(sessionID)?.agentName:agent;if(surface==="system"&&isSessionBoundArchitect(sessionID,activeAgentName))return;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG)))return;let banner=[SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
7876
7876
  `);if(system.push(banner),sessionID)if(surface==="messages"&&output.deliveryBudgetReceipts){let receipt=recordProducerEmissionWithReceipt(sessionID,"swarm-command-banner",estimateTokens(banner),surface,{expectedGeneration});if(receipt)output.deliveryBudgetReceipts.push(receipt)}else recordProducerEmission(sessionID,"swarm-command-banner",estimateTokens(banner),0,surface,{expectedGeneration})}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;noteQueueScheduled();let timer=setTimeout(()=>{for(let task2 of tasks){let wrapped=wrapPostResolutionTask(task2);try{Promise.resolve(wrapped()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig,regenerateMemoryReflectionForInit=async(directory,config3)=>{let{regenerateMemoryReflection:regenerateMemoryReflection2}=await Promise.resolve().then(() => (init_reflection_service(),exports_reflection_service));return regenerateMemoryReflection2(directory,config3)};function overrideIndexInternalsForTest(overrides2){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit,previousRegenerateMemoryReflection=regenerateMemoryReflectionForInit;if(overrides2.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides2.createRepoGraphBuilderHook;if(overrides2.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides2.schedulePostResolutionTasks;if(overrides2.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides2.loadPluginConfigWithMetaAsync;if(overrides2.loadSnapshot)loadSnapshotForInit=overrides2.loadSnapshot;if(overrides2.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides2.ensureSwarmGitExcluded;if(overrides2.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides2.resolveAutoReviewConfig;if(overrides2.regenerateMemoryReflection)regenerateMemoryReflectionForInit=overrides2.regenerateMemoryReflection;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig,regenerateMemoryReflectionForInit=previousRegenerateMemoryReflection}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}async function recoverPendingCostCorrectionForTest(directory,parentSessionId,childSessionId,pricing){return recoverPendingCostCorrection(directory,parentSessionId,childSessionId,pricing)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var serverInitInvocations=0,runServerInit=async(ctx)=>{if(serverInitInvocations+=1,serverInitInvocations>1)log("[opencode-swarm] WARNING: plugin initialization invoked more than once in this process; module-level swarm state is shared between invocations (dual host load?)");beginStartupServerInterval();let postResolutionTasks=[];try{let hooks2=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),endStartupServerInterval(),hooks2}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},OpenCodeSwarm=async(ctx)=>runServerInit(ctx),MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map,pendingCostCorrectionByChildSession=new Map,scheduledCostCorrectionRecoveryBySession=new Set;function trackPendingCostCorrection(childSessionId,pending){pendingCostCorrectionByChildSession.delete(childSessionId),pendingCostCorrectionByChildSession.set(childSessionId,pending);while(pendingCostCorrectionByChildSession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=pendingCostCorrectionByChildSession.keys().next().value;if(oldest===void 0)break;pendingCostCorrectionByChildSession.delete(oldest)}}function emitPendingCostCorrection(sessionId,raw){let pending=pendingCostCorrectionByChildSession.get(sessionId);if(!pending)return!1;let fields=buildDelegationCostFields({raw,model:pending.model,gate:pending.gate,retry_index:pending.retryIndex,pricing:pending.pricing});if(fields.evidence_status!=="complete")return!0;if(!isCostUpgrade(pending.currentFields.cost_evidence??[],fields.cost_evidence??[]))return!0;let nextVersion=pending.version+1;return emit("delegation_cost_correction",{sessionId:pending.parentSessionId,agentName:pending.agentName,taskId:pending.taskId,record_id:pending.recordId,identity_fingerprint:pending.identityFingerprint,parent_session_digest:pending.parentSessionDigest,version:nextVersion,...fields}),pending.version=nextVersion,pending.currentFields=fields,!0}async function recoverPendingCostCorrection(directory,parentSessionId,childSessionId,pricing){let events=await readTelemetryEventsAsync(directory),folded=foldTelemetryEvents(events),parentSessionDigest=createHash119("sha256").update(`delegation-cost-parent-v1\x00${parentSessionId}`).digest("hex").slice(0,32),childSessionDigest=createHash119("sha256").update(`delegation-cost-child-v1\x00${childSessionId}`).digest("hex").slice(0,32),candidates=folded.events.filter((event2)=>event2.event==="delegation_end"&&event2.parent_session_digest===parentSessionDigest&&event2.cost_source!=="reported"&&typeof event2.record_id==="string"&&typeof event2.identity_fingerprint==="string"),exactCandidates=candidates.filter((event2)=>event2.child_session_digest===childSessionDigest),selectedCandidates=exactCandidates.length>0?exactCandidates:candidates;if(selectedCandidates.length===0)return null;if(selectedCandidates.length!==1)return;let event=selectedCandidates[0],effective=event;if(effective.cost_source==="reported")return null;let currentFields={tokens_input:typeof effective.tokens_input==="number"?effective.tokens_input:null,tokens_output:typeof effective.tokens_output==="number"?effective.tokens_output:null,tokens_reasoning:typeof effective.tokens_reasoning==="number"?effective.tokens_reasoning:null,tokens_cache:typeof effective.tokens_cache==="number"?effective.tokens_cache:null,cost_usd:typeof effective.cost_usd==="number"?effective.cost_usd:null,cost_source:effective.cost_source==="reported"||effective.cost_source==="estimated"?effective.cost_source:"unavailable",cost_evidence:Array.isArray(effective.cost_evidence)?effective.cost_evidence:void 0};return{recordId:event.record_id,identityFingerprint:event.identity_fingerprint,parentSessionId,parentSessionDigest,agentName:typeof event.agentName==="string"?event.agentName:"unknown",taskId:typeof event.taskId==="string"?event.taskId:"",model:typeof event.model==="string"?event.model:"unknown",gate:typeof event.gate==="string"?event.gate:void 0,retryIndex:typeof event.retry_index==="number"?event.retry_index:void 0,pricing,version:folded.versions[event.record_id]??1,currentFields}}function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")return rememberAssistantUsage(info.sessionID,info),typeof info.sessionID==="string"?{sessionId:info.sessionID,raw:info}:void 0;return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")return rememberAssistantUsage(part.sessionID,part),typeof part.sessionID==="string"?{sessionId:part.sessionID,raw:part}:void 0}return}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(_parentSessionID,taskOutput){let sessionIDs=collectSessionIDs(taskOutput);for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key2 of["sessionID","sessionId","session_id"]){let candidate2=value[key2];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key2 of["metadata","data","info","message","response","output"])visit(value[key2],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function writeBootstrapRootRedirectRecord(bootstrapRoot,openedDirectory){try{let advisoriesDir=path383.join(bootstrapRoot,".swarm","advisories");mkdirSync101(advisoriesDir,{recursive:!0}),writeFileSync66(path383.join(advisoriesDir,"bootstrap-root-redirect.json"),JSON.stringify({kind:"bootstrap-root-redirect",opened_directory:openedDirectory,project_root:bootstrapRoot,note:"Runtime state, project config, and telemetry for the opened workspace are owned by the project root."}))}catch{}}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){console.warn(`[opencode-swarm] running v${package_default.version}`),clearDeferredWarnings(),resetConfigAdvisoryDedup(),resetArchitectPromptBudgetAdvisories();let rootDecision=resolveProjectRootDecision(ctx.directory),bootstrapRoot=rootDecision.kind==="redirect"?rootDecision.owningRoot:ctx.directory,bootstrapStateWritesEnabled=rootDecision.kind!=="fail-closed",__initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(bootstrapRoot),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=bootstrapStateWritesEnabled&&hasSwarmState(bootstrapRoot)?withTimeout(loadSnapshotForInit(bootstrapRoot),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}):Promise.resolve(),gitExcludeP=bootstrapStateWritesEnabled&&hasGitMarkerAncestor(bootstrapRoot)?withTimeout(ensureSwarmGitExcludedForInit(bootstrapRoot),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})}):Promise.resolve(),projectContextP=hasManifestAncestor(ctx.directory)?(()=>{let timeoutError2=Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels");return withTimeoutSignal(async(signal2)=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory,signal2)},300,timeoutError2).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null})})():Promise.resolve(null);await Promise.all([configLoadP,snapshotP,gitExcludeP,projectContextP]);let{config:config3,loadedFromFile}=await configLoadP;if(rootDecision.kind==="redirect"){let redirectHint=`[opencode-swarm] project-root ownership: "${ctx.directory}" is an ordinary subdirectory — runtime state, project config, and telemetry for this workspace are owned by the project root "${bootstrapRoot}". Open the project root (or add a .git/.opencode marker in "${ctx.directory}") to make this directory independent.`;console.warn(redirectHint),addDeferredWarning(redirectHint),advisoryWarn(redirectHint),writeBootstrapRootRedirectRecord(bootstrapRoot,ctx.directory)}else if(rootDecision.kind==="fail-closed"){let failClosedHint=`[opencode-swarm] project-root ownership: cannot verify "${ctx.directory}" (${rootDecision.reason}) — runtime state is disabled for this session. Reopen the project from its verified root.`;console.warn(failClosedHint),addDeferredWarning(failClosedHint),advisoryWarn(failClosedHint)}if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),setGitBinaryOverride(config3.git?.binary),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}if(swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:bootstrapRoot,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),bootstrapStateWritesEnabled)registerObservabilityEventSink(bootstrapRoot),initTelemetry(bootstrapRoot);startHeartbeatTracking();let otlpExportConfig=config3.observability?.export;if(otlpExportConfig!==void 0&&bootstrapStateWritesEnabled){if(registerOtlpExporter(bootstrapRoot,otlpExportConfig),isOtlpExporterActive())postResolutionTasks.push(()=>{flushOtlpExporterForTesting(bootstrapRoot).catch(()=>{})})}let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled&&bootstrapStateWritesEnabled?repoGraphHookFactory(bootstrapRoot,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null,repoGraphInitPromise;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphInitPromise=repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();return startSnapshotCoordinationInitialization(bootstrapRoot)}),postResolutionTasks.push(()=>{runModelPreflight(config3,swarmState.opencodeClient,{generatedAgentNames:swarmState.generatedAgentNames}).then((result)=>{let msg=formatModelPreflightWarning(result);if(!msg)return;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of result.resolutions)if(resolution.status==="unresolved"||resolution.status==="missing-selection")telemetry.modelUnresolved(resolution.agent,resolution.model||"(no final selection)",resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{if(bootstrapStateWritesEnabled)runInitOrphanRecovery(bootstrapRoot).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),postResolutionTasks.push(function(){return withTimeout(bootstrapStateWritesEnabled?cleanupOldTrajectoryFiles(bootstrapRoot):Promise.resolve(),TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS,Error(`trajectory cleanup exceeded ${TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (lazy per-session cleanup remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init trajectory cleanup timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})}),postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();let retentionConfig=config3?.retention,retentionDaysValue=config3?.summaries?.retention_days,sweepCancelled=!1;return withTimeout(runRetentionSweep(bootstrapRoot,{enabled:retentionConfig?.enabled!==!1,dryRun:retentionConfig?.dry_run===!0,summariesRetentionDays:typeof retentionDaysValue==="number"&&retentionDaysValue>=1?retentionDaysValue:void 0,shouldContinue:()=>!sweepCancelled}),RETENTION_SWEEP_INIT_TIMEOUT_MS,Error(`retention sweep exceeded ${RETENTION_SWEEP_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (close-time sweeps remain a backstop)`)).catch((err2)=>{sweepCancelled=!0;let msg=err2 instanceof Error?err2.message:String(err2);log("post-init retention sweep timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})}),config3.hooks?.background_subagents===!0)postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();return withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(bootstrapRoot,{lockTimeoutMs:5000,reason:"post-init",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})),BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS,Error(`background maintenance exceeded ${BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (other maintenance points remain)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init background maintenance timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})});if(bootstrapStateWritesEnabled)writeSwarmConfigExampleIfNew(bootstrapRoot);if(postResolutionTasks.push(()=>{if(!bootstrapStateWritesEnabled)return;withTimeout(syncBundledProjectSkillsIfMissingAsync(bootstrapRoot,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await projectContextP,autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{},{preset:config3.preset})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,bootstrapRoot,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,bootstrapRoot),systemEnhancerHook=createSystemEnhancerHook(config3,bootstrapRoot),architectMessagesEnhancerHook=createSystemEnhancerHook(config3,bootstrapRoot,{surface:"messages",deferRealtimeLearningNudgeState:!0,reservedEnvelopeTokens:guidanceCarrierEnvelopeTokens("architect-session")}),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,bootstrapRoot),compactionHook=createCompactionCustomizerHook(config3,bootstrapRoot),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmID=extractSwarmIdFromAgentName(trimmedAgentName)||void 0,swarmAgents=getSwarmAgents(swarmID);return{exactAgentName:trimmedAgentName,role,swarmID,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key2 of["message","reason","code","status","statusCode","error","cause","detail","details","data","name"])parts.push(...extractBoundedErrorSignal(record3[key2],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:bootstrapRoot}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}},schedulePendingCostCorrectionRecovery=(rememberedUsage)=>{if(scheduledCostCorrectionRecoveryBySession.has(rememberedUsage.sessionId))return;scheduledCostCorrectionRecoveryBySession.add(rememberedUsage.sessionId);while(scheduledCostCorrectionRecoveryBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=scheduledCostCorrectionRecoveryBySession.values().next().value;if(oldest===void 0)break;scheduledCostCorrectionRecoveryBySession.delete(oldest)}(async()=>{let parentSessionId=await withTimeout(lookupParentSessionIDForTaskRoute(rememberedUsage.sessionId),1000,Error("late cost parent lookup exceeded 1000ms")).catch(()=>{return});if(!parentSessionId)return;let recovered=await recoverPendingCostCorrection(bootstrapRoot,parentSessionId,rememberedUsage.sessionId,config3.pricing),corrected=!1;if(recovered)trackPendingCostCorrection(rememberedUsage.sessionId,recovered),emit("delegation_cost_binding",{sessionId:parentSessionId,parent_session_digest:recovered.parentSessionDigest,record_id:recovered.recordId,identity_fingerprint:recovered.identityFingerprint,child_session_digest:createHash119("sha256").update(`delegation-cost-child-v1\x00${rememberedUsage.sessionId}`).digest("hex").slice(0,32)}),corrected=emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw);if(recovered===null)corrected=!0;if(!corrected)emit("delegation_cost_join",{sessionId:parentSessionId,reason:"join_miss"})})().catch(()=>{return}).finally(()=>{scheduledCostCorrectionRecoveryBySession.delete(rememberedUsage.sessionId)})};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel,bootstrapRoot),finalContextAccountingStep=createFinalContextAccountingStep({config:config3,directory:bootstrapRoot,resolveAgentModelFn:resolveIncomingAgentModel}),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client,config3.pricing),reviewModelDispatcher=createReviewModelDispatcher(ctx.client,config3.pricing),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),systemRenderBoundaryHook=createSystemRenderBoundaryHook(),commandHandler=createSwarmCommandHandler(bootstrapRoot,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,config:config3,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),architectMessagesCommandRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents,{surface:"messages"}),activityHooks=createAgentActivityHooks(config3,bootstrapRoot),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmConfig=config3.prm??PrmConfigSchema.parse({}),prmHook=createPrmHook(prmConfig,bootstrapRoot,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:prmConfig.max_trajectory_lines},bootstrapRoot),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,bootstrapRoot,agents),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:bootstrapRoot,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,pendingDelegationsModulePromise=null,maintainBackgroundDelegationsOnSessionEvent=async()=>{let modulePromise=pendingDelegationsModulePromise;if(modulePromise===null)modulePromise=Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).catch((err2)=>{throw pendingDelegationsModulePromise=null,err2}),pendingDelegationsModulePromise=modulePromise;await(await modulePromise).maintainBackgroundDelegations(bootstrapRoot,{lockTimeoutMs:2000,reason:"session-close",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})},delegationSanitizerHook=createDelegationSanitizerHook(bootstrapRoot),trainingCaptureObserver=createTrainingCaptureObserver(bootstrapRoot),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:bootstrapRoot,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(bootstrapStateWritesEnabled?regenerateMemoryReflectionForInit(bootstrapRoot,reflectionConfig):Promise.resolve(),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback),dispatchProtectionConfig=DispatchProtectionConfigSchema.parse(config3.dispatch_protection??{});if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled,bootstrapRoot),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,guardrailsHooks=createGuardrailsHooks(bootstrapRoot,void 0,guardrailsConfig,authorityConfig,worktreeDirOverride?[worktreeDirOverride]:[],resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,bootstrapRoot),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:bootstrapRoot}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:bootstrapRoot}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:bootstrapRoot}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,bootstrapRoot),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard},bootstrapRoot,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:bootstrapRoot,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:bootstrapRoot,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},bootstrapRoot,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(bootstrapRoot),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:bootstrapRoot,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,bootstrapRoot),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:bootstrapRoot,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(bootstrapRoot,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(bootstrapRoot,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(bootstrapRoot,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(bootstrapRoot,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(bootstrapRoot),coChangeSuggesterHook=createCoChangeSuggesterHook(bootstrapRoot),darkMatterDetectorHook=createDarkMatterDetectorHook(bootstrapRoot),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=bootstrapStateWritesEnabled?createSnapshotWriterHook(bootstrapRoot):async()=>{},automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){if(automationManager=createAutomationManager(automationConfig),bootstrapStateWritesEnabled)automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{getSharedAutomationStatusArtifact:getSharedAutomationStatusArtifact2}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path383.resolve(bootstrapRoot,".swarm"),automationStatusArtifactPostInitTask=async()=>{try{getSharedAutomationStatusArtifact2(swarmDir).updateConfig(automationConfig.mode,automationConfig.capabilities)}catch(err2){log("automation status artifact init failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}};if(bootstrapStateWritesEnabled)postResolutionTasks.push(automationStatusArtifactPostInitTask);if(automationConfig.capabilities?.evidence_auto_summaries===!0&&bootstrapStateWritesEnabled){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:bootstrapRoot,projectDir:bootstrapRoot,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:bootstrapRoot})}if(automationConfig.capabilities?.phase_preflight===!0&&bootstrapStateWritesEnabled){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:bootstrapRoot,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:bootstrapRoot})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0&&bootstrapStateWritesEnabled)try{planSyncWorker=new PlanSyncWorker({directory:bootstrapRoot}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:bootstrapRoot})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}ensurePrSubscriptionDispatcherInstalled(),registerPrMonitorWorkerHandler(bootstrapRoot,ensurePrMonitorWorkerRunning);let prEventCleanup=null,prFeedbackLoopRuntimeCleanup=null;if(isPrFeedbackLoopEnabled(config3))try{let registration=registerPrFeedbackLoopRuntime({client:ctx.client,directory:ctx.directory,config:config3,agentNames:instanceGeneratedAgentNames,resolveSessionAgent:(sessionID)=>swarmState.activeAgent.get(sessionID)??getAgentSession(sessionID)?.agentName});prFeedbackLoopRuntimeCleanup=registration,postResolutionTasks.push(()=>registration.promote())}catch(err2){log("[pr-feedback-loop] Runtime registration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}let prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:bootstrapRoot,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery)),registration=deliveryModule.registerPrEventDelivery({client:ctx.client,directory:bootstrapRoot,config:prMonitorConfig});postResolutionTasks.push(()=>registration.promote()),prEventDelivery={noteSessionIdle:(sessionID,directory)=>deliveryModule.noteSessionIdle(sessionID,directory),unregister:registration}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(bootstrapRoot,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(bootstrapRoot).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(bootstrapRoot)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let automationCleaned=!1,cleanupAutomation=()=>{if(automationCleaned)return;automationCleaned=!0,automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),dashboardDisposed=!0;try{closeDashboardServerForRootIfOwner(bootstrapRoot,dashboardHandleRef.current)}catch{}removePrMonitorWorkerHandler(bootstrapRoot,ensurePrMonitorWorkerRunning),prEventCleanup?.(),prEventDelivery?.unregister(),prFeedbackLoopRuntimeCleanup?.(),markSnapshotCoordinationClosing(bootstrapRoot);try{if(closeGroupCommitWriter(bootstrapRoot),getSnapshotCoordinationStatus(bootstrapRoot).settled)closeProjectDb(bootstrapRoot)}catch{}},instanceExitCleanupToken=`${bootstrapRoot}#${++instanceExitCleanupCounter}`;if(registerProcessExitCleanupDispatcher(),instanceExitCleanups.set(instanceExitCleanupToken,cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(bootstrapRoot,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}let dashboardPort=config3.dashboard?.port??0,dashboardHandleRef={current:null},dashboardDisposed=!1;if(dashboardPort>0)postResolutionTasks.push(async function(){try{let{startDashboardServer:startDashboardServer2}=await Promise.resolve().then(() => (init_dashboard(),exports_dashboard)),handle=await startDashboardServer2({port:dashboardPort,host:"127.0.0.1",directory:bootstrapRoot});if(!handle.listening){advisoryWarn(`Swarm dashboard disabled: port ${dashboardPort} is unavailable (in use or bind failed). Free the port or change dashboard.port in opencode-swarm.json.`);return}if(dashboardDisposed){handle.close();return}dashboardHandleRef.current=handle,log("swarm dashboard listening (loopback, token-protected)",{port:handle.port})}catch(err2){log("dashboard startup failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}});log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}});let messagesTransformTrainingCaptureStep=(_input,output)=>{return trainingCaptureObserver.observeMessages(output)},messagesTransformDelegationLedgerStep=(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},stagedArchitectGuidanceByMessages=new WeakMap,settleDeliveryBudgetReceipts=(receipts,action2)=>{for(let receipt of receipts)if(action2==="commit")commitInjectionBudgetReceipt(receipt);else refundInjectionBudgetReceipt(receipt)},messagesTransformArchitectEnhancerStage=async(_input,output)=>{let messages=output?.messages;if(!Array.isArray(messages))return;let mctx=resolveMessageTransformContext(output),sessionID=mctx.sessionID;if(!sessionID)return;let compactionPending=_architectCompactionPending.delete(sessionID);if(!isSessionBoundArchitect(sessionID,mctx.agent)||compactionPending)return;let identity=getLiveContextModelIdentity(sessionID),context=identity?getLiveContextWindow(sessionID,identity):void 0,model=identity?{id:identity.modelID,providerID:identity.providerID,limit:context===void 0?void 0:{context}}:void 0,stagedOutput={system:[],deliveryBudgetReceipts:[],deferredRealtimeLearningNudges:[]},enhancer=architectMessagesEnhancerHook["experimental.chat.system.transform"];try{if(typeof enhancer==="function")await enhancer({sessionID,model},stagedOutput);let stagedAgent=mctx.agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName??"architect";stagedArchitectGuidanceByMessages.set(messages,{sessionID,agent:stagedAgent,system:stagedOutput.system,deferredRealtimeLearningNudges:stagedOutput.deferredRealtimeLearningNudges??[],turnLedgerGeneration:stagedOutput.turnLedgerGeneration,systemEnhancerBudgetReceipt:stagedOutput.systemEnhancerBudgetReceipt,fenceBudgetReceipt:stagedOutput.fenceBudgetReceipt,deliveryBudgetReceipts:stagedOutput.deliveryBudgetReceipts})}catch{if(settleDeliveryBudgetReceipts(stagedOutput.deliveryBudgetReceipts,"refund"),stagedOutput.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(stagedOutput.systemEnhancerBudgetReceipt);if(stagedOutput.fenceBudgetReceipt)refundInjectionBudgetReceipt(stagedOutput.fenceBudgetReceipt)}},messagesTransformArchitectEnhancerDeliveryStep=async(_input,output)=>{let messages=output?.messages;if(!Array.isArray(messages))return;let staged=stagedArchitectGuidanceByMessages.get(messages);if(!staged)return;stagedArchitectGuidanceByMessages.delete(messages);let deliveryConfirmed=!1;try{let stagedOutput={system:staged.system,deliveryBudgetReceipts:staged.deliveryBudgetReceipts};await roleFilterSystemHook["experimental.chat.system.transform"]({sessionID:staged.sessionID,agent:staged.agent,expectedGeneration:staged.turnLedgerGeneration},stagedOutput),await architectMessagesCommandRuleHook({sessionID:staged.sessionID,agent:staged.agent,expectedGeneration:staged.turnLedgerGeneration},stagedOutput);let text=stagedOutput.system.filter((entry)=>entry.trim()).join(`
7877
7877
 
7878
- `),carrier=appendGuidanceCarrier(messages,"architect-session",text,{sessionID:staged.sessionID});if(!deliveredGuidanceDelta(carrier,text)){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt);return}if(staged.systemEnhancerBudgetReceipt)commitInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)commitInjectionBudgetReceipt(staged.fenceBudgetReceipt);settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"commit"),deliveryConfirmed=!0;for(let sessionID of staged.deferredRealtimeLearningNudges)recordRealtimeLearningNudge(sessionID);let carrierTokens=estimateTokens(messageTextOf(carrier)),stagedTokens=estimateTokens(text),fenceOverheadTokens=Math.max(0,carrierTokens-stagedTokens);if(fenceOverheadTokens>0){if(staged.sessionID&&staged.turnLedgerGeneration!==void 0)recordProducerEmission(staged.sessionID,"guidance-carrier-fence",fenceOverheadTokens,0,"messages",{expectedGeneration:staged.turnLedgerGeneration})}}catch{if(!deliveryConfirmed){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt)}}},messagesTransformKnowledgeApplicationScanStep=(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(bootstrapRoot,output,mctx.sessionID)}catch{return Promise.resolve()}},messagesTransformSkillPropagationScanStep=(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(bootstrapRoot,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},messagesTransformSystemGuidanceMaterializeStep=(_input,output)=>{if(Array.isArray(output.messages))materializeSystemGuidanceInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()},messagesTransformGuidanceCarrierOrderStep=(_input,output)=>{if(Array.isArray(output?.messages))moveGuidanceCarriersToEnd(output.messages);return Promise.resolve()},systemTransformStartDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemTransformEnhancerDoneDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},systemTransformHeartbeatStep=(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS,sessionID),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()};return{name:"opencode-swarm",dispose:async()=>{try{cancelDeferredMaintenanceScans(bootstrapRoot)}catch(err2){log("dispose deferred-scan cancellation failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(cleanupAutomation(),instanceExitCleanups.delete(instanceExitCleanupToken),instanceExitCleanups.size===0&&processExitCleanupRegistered){process.off("exit",runInstanceExitCleanups);for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.off(signal2,handler);processSignalCleanupHandlers=[],processExitCleanupRegistered=!1}evictAndClose(bootstrapRoot);try{await closeSnapshotCoordinationInitialization(bootstrapRoot),closeGroupCommitWriter(bootstrapRoot),closeProjectDb(bootstrapRoot)}catch(err2){log("dispose durable-state close failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{let rememberedUsage=rememberAssistantUsageEvent(input);if(rememberedUsage){if(!emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw))schedulePendingCostCorrectionRecovery(rememberedUsage)}let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&typeof part?.tool==="string"&&isTaskToolId(part.tool)&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(bootstrapRoot,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:resolveSessionChatAgent(childSessionID)??swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels});else if(!route&&routeModel&&routeModel.fallbackModels.length>0&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal))){let advanced=advanceSessionFallbackSelection({sessionID:childSessionID,role:routeModel.role,swarmID:routeModel.swarmID,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels}),reason=isQuotaError(errorSignal)?"quota":"transient";telemetry.modelFallback(childSessionID,routeModel.role,routeModel.primaryModel??"unknown",advanced.modelString??"exhausted",reason);let session=swarmState.agentSessions.get(childSessionID);if(session){if(advanced.exhausted)pushAdvisory(session,`MODEL FALLBACK: [primary-model-fallback-exhausted:${routeModel.role}] all configured fallback models for ${routeModel.role} failed after a provider ${reason} error; staying on the session's selected model.`,{dedupeKey:`[primary-model-fallback-exhausted:${routeModel.role}]`});else if(advanced.accepted&&advanced.modelString)pushAdvisory(session,`MODEL FALLBACK: [primary-model-fallback:${routeModel.role}] switching ${routeModel.role} from configured primary ${routeModel.primaryModel??"unknown"} to ${advanced.modelString} after a provider ${reason} error; the next message uses the fallback.`,{dedupeKey:`[primary-model-fallback:${routeModel.role}]`})}}}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"){_architectCompactionPending.delete(sessionID);try{await terminalizePrWorkflowGateForSession2(bootstrapRoot,sessionID)}catch{warn("PR workflow gate terminalization on session deletion failed (non-fatal)")}try{let reconciliation=reconcilePrWorkflowCheckoutReceipts(bootstrapRoot,sessionID),summary=await withTimeout(reconciliation,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS,Error("PR workflow checkout receipt reconciliation exceeded the session-deletion event budget"));log("PR workflow checkout receipts reconciled on session deletion",{inspected:summary.inspectedReceiptCount,collected:summary.collectedStashOids.length,retiredMissing:summary.retiredMissingStashOids.length,preserved:summary.preservedStashOids.length,failures:summary.failures.length})}catch{warn("PR workflow checkout receipt reconciliation on session deletion failed or exceeded its event budget (non-fatal)")}if(bootstrapStateWritesEnabled)deleteSnapshotSessionRows(bootstrapRoot,sessionID);clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID)}if(backgroundSubagentsEnabled&&bootstrapStateWritesEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}try{let{recoverTerminalLaneReceipts:recoverTerminalLaneReceipts2}=await Promise.resolve().then(() => (init_delegation_lifecycle(),exports_delegation_lifecycle));await recoverTerminalLaneReceipts2(bootstrapRoot)}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID,ctx.directory)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan (runs the canonical command)"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-harness-opt":{template:"/swarm harness-opt $ARGUMENTS",description:"Use /swarm harness-opt to govern harness optimization rounds (plan|run|status|stop|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-report":{template:"/swarm report $ARGUMENTS",description:"Use /swarm report to query swarm observability events (--task/--session/--trace/--run/--since/--json)"},"swarm-dashboard":{template:"/swarm dashboard",description:"Use /swarm dashboard to show the opt-in local mission-control dashboard URL and status"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-dataset-consent":{template:"/swarm dataset consent $ARGUMENTS",description:"Use /swarm dataset consent to grant or revoke the training-content consent (human-only, confirm token)"},"swarm-dataset-export":{template:"/swarm dataset export $ARGUMENTS",description:"Use /swarm dataset export to preview/write the deterministic governed dataset export (human-only, confirm token)"},"swarm-dataset-withdraw":{template:"/swarm dataset withdraw $ARGUMENTS",description:"Use /swarm dataset withdraw to purge vault content, tombstone, and revoke exports (human-only, confirm token)"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop; cancel an armed PR_FEEDBACK without publication with PR_FEEDBACK --cancel-publication <reason...> (human-only escape hatch)"},"swarm-pr-feedback-loop":{template:"/swarm pr-feedback-loop $ARGUMENTS",description:"Use /swarm pr-feedback-loop stop <reason...> to stop the autonomous PR babysitting settling loop for this session (human-only)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-approve-write":{template:"/swarm approve-write $ARGUMENTS",description:"Use /swarm approve-write to issue one exact, session-bound, one-shot write approval (human-only)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-ci":{template:"/swarm ci $ARGUMENTS",description:shortcutDescription("ci")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-blueprint-validate":{template:"/swarm blueprint validate $ARGUMENTS",description:shortcutDescription("blueprint validate")},"swarm-blueprint-current":{template:"/swarm blueprint current",description:shortcutDescription("blueprint current")},"swarm-blueprint-history":{template:"/swarm blueprint history",description:shortcutDescription("blueprint history")},"swarm-blueprint-diff":{template:"/swarm blueprint diff $ARGUMENTS",description:shortcutDescription("blueprint diff")},"swarm-blueprint-export":{template:"/swarm blueprint export $ARGUMENTS",description:shortcutDescription("blueprint export")},"swarm-harness-candidate-validate":{template:"/swarm harness candidate validate $ARGUMENTS",description:shortcutDescription("harness candidate validate")},"swarm-harness-candidate-show":{template:"/swarm harness candidate show $ARGUMENTS",description:shortcutDescription("harness candidate show")},"swarm-harness-candidate-diff":{template:"/swarm harness candidate diff $ARGUMENTS",description:shortcutDescription("harness candidate diff")},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":withStartupFirstUseTracking("first_turn",void 0,composeHandlers(...[messagesTransformArchitectEnhancerStage,messagesTransformTrainingCaptureStep,messagesTransformDelegationLedgerStep,pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,messagesTransformKnowledgeApplicationScanStep,messagesTransformSkillPropagationScanStep,messagesTransformArchitectEnhancerDeliveryStep,messagesTransformSystemGuidanceMaterializeStep,messagesTransformGuidanceCarrierOrderStep,finalContextAccountingStep].filter((fn2)=>Boolean(fn2)))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[systemTransformStartDiagnostic,systemEnhancerHook["experimental.chat.system.transform"],systemTransformEnhancerDoneDiagnostic,contextCapsuleInjectHook["experimental.chat.system.transform"],systemTransformHeartbeatStep,automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(bootstrapRoot,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(bootstrapRoot,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"],systemRenderBoundaryHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":async(input,output)=>{let{sessionID}=input??{};if(sessionID)_architectCompactionPending.delete(sessionID),_architectCompactionPending.set(sessionID,!0),capSessionMap(_architectCompactionPending,MAX_TRACKED_ARCHITECT_COMPACTIONS,sessionID),advanceTurnGeneration(sessionID);let delegate=compactionHook["experimental.session.compacting"];if(typeof delegate==="function")await delegate(input,output)},"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME,bootstrapRoot)}}let failClosedRegionCompleted=!1;try{if(dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool)){let armed=armDispatchIdentity(input.callID,input.tool,output.args),invocationID=invocationIdForSession(input.sessionID);assertDispatchSpawnCircuitAdmits({sessionID:input.sessionID,invocationID,actionDigest:armed.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms}),await acquireDispatchToken({directory:bootstrapRoot,ratePerSecond:dispatchProtectionConfig.rate_per_second,burstCapacity:dispatchProtectionConfig.burst_capacity})}await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(bootstrapRoot,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames,input.callID),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{},skillAttributionPlanTaskOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(bootstrapRoot));if(injectSkillsIntoDelegation(bootstrapRoot,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet,...skillAttributionPlanTaskOptions}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(bootstrapRoot,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getFinalPromptPressure(input.sessionID)?.pct??getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE (estimated): ${pressurePct.toFixed(1)}% estimated prompt pressure of the model context window. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),isTaskToolId(input.tool)&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}if(resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs),isTaskToolId(input.tool)){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY,input.callID),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,bootstrapRoot,{maxLines:prmConfig.max_trajectory_lines})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(isTaskToolId(input.tool))try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID,input.sessionID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let isTaskTool8=isTaskToolId(input.tool),afterCtx=resolveToolAfterContext(input);if(await safeHook(()=>trainingCaptureObserver.observeToolExecution({tool:input.tool,sessionID:input.sessionID,input:afterCtx.args,output,error:output?.state==="error"?output:void 0}))(input,output),dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool))try{let identity=takeArmedDispatchIdentity(input.callID)??dispatchIdentityFor(input.tool,afterCtx.args),invocationID=invocationIdForSession(input.sessionID);if(output?.state==="error"){let{opened}=noteDispatchSpawnFailure({sessionID:input.sessionID,invocationID,actionDigest:identity.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms});if(opened)telemetry.loopDetected(input.sessionID,swarmState.activeAgent.get(input.sessionID)??"agent",`dispatch.spawn:${identity.pattern}`)}else if(output?.state==="completed")noteDispatchSpawnSuccess({sessionID:input.sessionID,invocationID,actionDigest:identity.digest})}catch{}try{let pushCommand=afterCtx.args?.command;if(typeof pushCommand==="string"&&/^\s*git\s+push/i.test(pushCommand)){let pushAttemptSessionID=await prWorkflowSessionResolver.resolve(input.sessionID);await recordPrFeedbackPushAttemptResult(bootstrapRoot,{sessionID:pushAttemptSessionID,callID:input.callID,tool:input.tool},pushCommand,output)}}catch{}if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(bootstrapRoot,input,output,createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(bootstrapRoot).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(_toolName,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(bootstrapRoot,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,bootstrapRoot),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",decisions:extractContextDecisionsFromContextMd(bootstrapRoot,{agent_role:resolveSessionChatAgent(input.sessionID)??swarmState.activeAgent.get(input.sessionID)??"unknown"}),directory:bootstrapRoot})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing}),childSessionID=collectSessionIDs(output)[0],recordMaterial=`${sessionId}\x00${input.callID}`;if(costFields.record_id=createHash119("sha256").update(`delegation-cost-id-v1\x00${recordMaterial}`).digest("hex").slice(0,32),costFields.identity_fingerprint=createHash119("sha256").update(`delegation-cost-identity-v1\x00${recordMaterial}\x00${agentName}\x00${configuredModel}`).digest("hex").slice(0,32),costFields.version=1,costFields.parent_session_digest=createHash119("sha256").update(`delegation-cost-parent-v1\x00${sessionId}`).digest("hex").slice(0,32),childSessionID)costFields.child_session_digest=createHash119("sha256").update(`delegation-cost-child-v1\x00${childSessionID}`).digest("hex").slice(0,32);swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME,bootstrapRoot);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){let costTaskId=beganDelegation?.taskId||taskSession.currentTaskId||"";if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,costTaskId,"completed",costFields),childSessionID&&costFields.evidence_status!=="complete"&&costFields.record_id&&costFields.identity_fingerprint)trackPendingCostCorrection(childSessionID,{recordId:costFields.record_id,identityFingerprint:costFields.identity_fingerprint,parentSessionId:sessionId,parentSessionDigest:costFields.parent_session_digest,agentName,taskId:costTaskId,model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retryIndex:activeWindow?.transientRetryCount,pricing:config3.pricing,version:1,currentFields:costFields});if(baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=applySoundingBoardResponsePolicy(rawResponse,afterCtx.args);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.category)verdictMsg+=` Category: ${parsed.category}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){recordSessionChatAgent(String(input.sessionID),input.agent);let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);try{if(input2?.sessionID&&typeof input2?.agent==="string"&&input2.agent.trim()!=="")maybeEmitNonArchitectAdvisory(String(input2.sessionID),String(input2.agent))}catch{}if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model;else if(resolution.status==="missing"){let sessionResolution=resolveSessionChatModelOverride({sessionID:String(input2.sessionID),role:routeModel.role,swarmID:routeModel.swarmID,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels});if(sessionResolution.status==="override"&&sessionResolution.model)output2.message.model=sessionResolution.model}}}if(input2?.sessionID){let messageModel=output2.message?.model;if(messageModel&&typeof messageModel==="object")setLiveContextWindow(String(input2.sessionID),void 0,{modelID:typeof messageModel.modelID==="string"?messageModel.modelID:typeof messageModel.id==="string"?messageModel.id:void 0,providerID:typeof messageModel.providerID==="string"?messageModel.providerID:void 0})}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(bootstrapRoot,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(bootstrapRoot,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm,setup:(ctx)=>openCodeSwarmV2Setup(ctx,{runInit:runServerInit})};export{schedulePostResolutionTasksForTest,recoverPendingCostCorrectionForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,applySoundingBoardResponsePolicy,_resetDelegationTelemetryPairingForTesting};
7878
+ `),carrier=appendGuidanceCarrier(messages,"architect-session",text,{sessionID:staged.sessionID});if(!deliveredGuidanceDelta(carrier,text)){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt);return}if(staged.systemEnhancerBudgetReceipt)commitInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)commitInjectionBudgetReceipt(staged.fenceBudgetReceipt);settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"commit"),deliveryConfirmed=!0;for(let sessionID of staged.deferredRealtimeLearningNudges)recordRealtimeLearningNudge(sessionID);let carrierTokens=estimateTokens(messageTextOf(carrier)),stagedTokens=estimateTokens(text),fenceOverheadTokens=Math.max(0,carrierTokens-stagedTokens);if(fenceOverheadTokens>0){if(staged.sessionID&&staged.turnLedgerGeneration!==void 0)recordProducerEmission(staged.sessionID,"guidance-carrier-fence",fenceOverheadTokens,0,"messages",{expectedGeneration:staged.turnLedgerGeneration})}}catch{if(!deliveryConfirmed){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt)}}},messagesTransformKnowledgeApplicationScanStep=(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(bootstrapRoot,output,mctx.sessionID)}catch{return Promise.resolve()}},messagesTransformSkillPropagationScanStep=(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(bootstrapRoot,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},messagesTransformSystemGuidanceMaterializeStep=(_input,output)=>{if(Array.isArray(output.messages))materializeSystemGuidanceInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()},messagesTransformGuidanceCarrierOrderStep=(_input,output)=>{if(Array.isArray(output?.messages))moveGuidanceCarriersToEnd(output.messages);return Promise.resolve()},systemTransformStartDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemTransformEnhancerDoneDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},systemTransformHeartbeatStep=(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS,sessionID),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()};return{name:"opencode-swarm",dispose:async()=>{try{cancelDeferredMaintenanceScans(bootstrapRoot)}catch(err2){log("dispose deferred-scan cancellation failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(cleanupAutomation(),instanceExitCleanups.delete(instanceExitCleanupToken),instanceExitCleanups.size===0&&processExitCleanupRegistered){process.off("exit",runInstanceExitCleanups);for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.off(signal2,handler);processSignalCleanupHandlers=[],processExitCleanupRegistered=!1}evictAndClose(bootstrapRoot);try{await closeSnapshotCoordinationInitialization(bootstrapRoot),closeGroupCommitWriter(bootstrapRoot),closeProjectDb(bootstrapRoot)}catch(err2){log("dispose durable-state close failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{let rememberedUsage=rememberAssistantUsageEvent(input);if(rememberedUsage){if(!emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw))schedulePendingCostCorrectionRecovery(rememberedUsage)}let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&typeof part?.tool==="string"&&isTaskToolId(part.tool)&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(bootstrapRoot,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:resolveSessionChatAgent(childSessionID)??swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal))){let routedAdvance=advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels});if(routedAdvance?.accepted&&!routedAdvance.exhausted){let stickyEligible=isStickyModelError(errorSignal),chainModel=routedAdvance.modelString;if(stickyEligible&&typeof chainModel==="string"&&chainModel.length>0)applyV2AgentModelOverride(routeModel.exactAgentName,chainModel)}}else if(!route&&routeModel&&routeModel.fallbackModels.length>0&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal))){let advanced=advanceSessionFallbackSelection({sessionID:childSessionID,role:routeModel.role,swarmID:routeModel.swarmID,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels}),reason=isQuotaError(errorSignal)?"quota":"transient";telemetry.modelFallback(childSessionID,routeModel.role,routeModel.primaryModel??"unknown",advanced.modelString??"exhausted",reason);let session=swarmState.agentSessions.get(childSessionID);if(session){if(advanced.exhausted)pushAdvisory(session,`MODEL FALLBACK: [primary-model-fallback-exhausted:${routeModel.role}] all configured fallback models for ${routeModel.role} failed after a provider ${reason} error; staying on the session's selected model.`,{dedupeKey:`[primary-model-fallback-exhausted:${routeModel.role}]`});else if(advanced.accepted&&advanced.modelString){if(pushAdvisory(session,`MODEL FALLBACK: [primary-model-fallback:${routeModel.role}] switching ${routeModel.role} from configured primary ${routeModel.primaryModel??"unknown"} to ${advanced.modelString} after a provider ${reason} error; the next message uses the fallback.`,{dedupeKey:`[primary-model-fallback:${routeModel.role}]`}),isStickyModelError(errorSignal))applyV2AgentModelOverride(routeModel.exactAgentName,advanced.modelString)}}}}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"){_architectCompactionPending.delete(sessionID);try{await terminalizePrWorkflowGateForSession2(bootstrapRoot,sessionID)}catch{warn("PR workflow gate terminalization on session deletion failed (non-fatal)")}try{let reconciliation=reconcilePrWorkflowCheckoutReceipts(bootstrapRoot,sessionID),summary=await withTimeout(reconciliation,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS,Error("PR workflow checkout receipt reconciliation exceeded the session-deletion event budget"));log("PR workflow checkout receipts reconciled on session deletion",{inspected:summary.inspectedReceiptCount,collected:summary.collectedStashOids.length,retiredMissing:summary.retiredMissingStashOids.length,preserved:summary.preservedStashOids.length,failures:summary.failures.length})}catch{warn("PR workflow checkout receipt reconciliation on session deletion failed or exceeded its event budget (non-fatal)")}if(bootstrapStateWritesEnabled)deleteSnapshotSessionRows(bootstrapRoot,sessionID);clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID)}if(backgroundSubagentsEnabled&&bootstrapStateWritesEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}try{let{recoverTerminalLaneReceipts:recoverTerminalLaneReceipts2}=await Promise.resolve().then(() => (init_delegation_lifecycle(),exports_delegation_lifecycle));await recoverTerminalLaneReceipts2(bootstrapRoot)}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID,ctx.directory)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan (runs the canonical command)"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-harness-opt":{template:"/swarm harness-opt $ARGUMENTS",description:"Use /swarm harness-opt to govern harness optimization rounds (plan|run|status|stop|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-report":{template:"/swarm report $ARGUMENTS",description:"Use /swarm report to query swarm observability events (--task/--session/--trace/--run/--since/--json)"},"swarm-dashboard":{template:"/swarm dashboard",description:"Use /swarm dashboard to show the opt-in local mission-control dashboard URL and status"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-dataset-consent":{template:"/swarm dataset consent $ARGUMENTS",description:"Use /swarm dataset consent to grant or revoke the training-content consent (human-only, confirm token)"},"swarm-dataset-export":{template:"/swarm dataset export $ARGUMENTS",description:"Use /swarm dataset export to preview/write the deterministic governed dataset export (human-only, confirm token)"},"swarm-dataset-withdraw":{template:"/swarm dataset withdraw $ARGUMENTS",description:"Use /swarm dataset withdraw to purge vault content, tombstone, and revoke exports (human-only, confirm token)"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop; cancel an armed PR_FEEDBACK without publication with PR_FEEDBACK --cancel-publication <reason...> (human-only escape hatch)"},"swarm-pr-feedback-loop":{template:"/swarm pr-feedback-loop $ARGUMENTS",description:"Use /swarm pr-feedback-loop stop <reason...> to stop the autonomous PR babysitting settling loop for this session (human-only)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-approve-write":{template:"/swarm approve-write $ARGUMENTS",description:"Use /swarm approve-write to issue one exact, session-bound, one-shot write approval (human-only)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-ci":{template:"/swarm ci $ARGUMENTS",description:shortcutDescription("ci")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-blueprint-validate":{template:"/swarm blueprint validate $ARGUMENTS",description:shortcutDescription("blueprint validate")},"swarm-blueprint-current":{template:"/swarm blueprint current",description:shortcutDescription("blueprint current")},"swarm-blueprint-history":{template:"/swarm blueprint history",description:shortcutDescription("blueprint history")},"swarm-blueprint-diff":{template:"/swarm blueprint diff $ARGUMENTS",description:shortcutDescription("blueprint diff")},"swarm-blueprint-export":{template:"/swarm blueprint export $ARGUMENTS",description:shortcutDescription("blueprint export")},"swarm-harness-candidate-validate":{template:"/swarm harness candidate validate $ARGUMENTS",description:shortcutDescription("harness candidate validate")},"swarm-harness-candidate-show":{template:"/swarm harness candidate show $ARGUMENTS",description:shortcutDescription("harness candidate show")},"swarm-harness-candidate-diff":{template:"/swarm harness candidate diff $ARGUMENTS",description:shortcutDescription("harness candidate diff")},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":withStartupFirstUseTracking("first_turn",void 0,composeHandlers(...[messagesTransformArchitectEnhancerStage,messagesTransformTrainingCaptureStep,messagesTransformDelegationLedgerStep,pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,messagesTransformKnowledgeApplicationScanStep,messagesTransformSkillPropagationScanStep,messagesTransformArchitectEnhancerDeliveryStep,messagesTransformSystemGuidanceMaterializeStep,messagesTransformGuidanceCarrierOrderStep,finalContextAccountingStep].filter((fn2)=>Boolean(fn2)))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[systemTransformStartDiagnostic,systemEnhancerHook["experimental.chat.system.transform"],systemTransformEnhancerDoneDiagnostic,contextCapsuleInjectHook["experimental.chat.system.transform"],systemTransformHeartbeatStep,automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(bootstrapRoot,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(bootstrapRoot,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"],systemRenderBoundaryHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":async(input,output)=>{let{sessionID}=input??{};if(sessionID)_architectCompactionPending.delete(sessionID),_architectCompactionPending.set(sessionID,!0),capSessionMap(_architectCompactionPending,MAX_TRACKED_ARCHITECT_COMPACTIONS,sessionID),advanceTurnGeneration(sessionID);let delegate=compactionHook["experimental.session.compacting"];if(typeof delegate==="function")await delegate(input,output)},"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME,bootstrapRoot)}}let failClosedRegionCompleted=!1;try{if(dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool)){let armed=armDispatchIdentity(input.callID,input.tool,output.args),invocationID=invocationIdForSession(input.sessionID);assertDispatchSpawnCircuitAdmits({sessionID:input.sessionID,invocationID,actionDigest:armed.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms}),await acquireDispatchToken({directory:bootstrapRoot,ratePerSecond:dispatchProtectionConfig.rate_per_second,burstCapacity:dispatchProtectionConfig.burst_capacity})}await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(bootstrapRoot,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames,input.callID),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{},skillAttributionPlanTaskOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(bootstrapRoot));if(injectSkillsIntoDelegation(bootstrapRoot,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet,...skillAttributionPlanTaskOptions}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(bootstrapRoot,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getFinalPromptPressure(input.sessionID)?.pct??getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE (estimated): ${pressurePct.toFixed(1)}% estimated prompt pressure of the model context window. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),isTaskToolId(input.tool)&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}if(resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs),isTaskToolId(input.tool)){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY,input.callID),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,bootstrapRoot,{maxLines:prmConfig.max_trajectory_lines})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(isTaskToolId(input.tool))try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID,input.sessionID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let isTaskTool8=isTaskToolId(input.tool),afterCtx=resolveToolAfterContext(input);if(await safeHook(()=>trainingCaptureObserver.observeToolExecution({tool:input.tool,sessionID:input.sessionID,input:afterCtx.args,output,error:output?.state==="error"?output:void 0}))(input,output),dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool))try{let identity=takeArmedDispatchIdentity(input.callID)??dispatchIdentityFor(input.tool,afterCtx.args),invocationID=invocationIdForSession(input.sessionID);if(output?.state==="error"){let{opened}=noteDispatchSpawnFailure({sessionID:input.sessionID,invocationID,actionDigest:identity.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms});if(opened)telemetry.loopDetected(input.sessionID,swarmState.activeAgent.get(input.sessionID)??"agent",`dispatch.spawn:${identity.pattern}`)}else if(output?.state==="completed")noteDispatchSpawnSuccess({sessionID:input.sessionID,invocationID,actionDigest:identity.digest})}catch{}try{let pushCommand=afterCtx.args?.command;if(typeof pushCommand==="string"&&/^\s*git\s+push/i.test(pushCommand)){let pushAttemptSessionID=await prWorkflowSessionResolver.resolve(input.sessionID);await recordPrFeedbackPushAttemptResult(bootstrapRoot,{sessionID:pushAttemptSessionID,callID:input.callID,tool:input.tool},pushCommand,output)}}catch{}if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(bootstrapRoot,input,output,createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(bootstrapRoot).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(_toolName,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(bootstrapRoot,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,bootstrapRoot),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",decisions:extractContextDecisionsFromContextMd(bootstrapRoot,{agent_role:resolveSessionChatAgent(input.sessionID)??swarmState.activeAgent.get(input.sessionID)??"unknown"}),directory:bootstrapRoot})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing}),childSessionID=collectSessionIDs(output)[0],recordMaterial=`${sessionId}\x00${input.callID}`;if(costFields.record_id=createHash119("sha256").update(`delegation-cost-id-v1\x00${recordMaterial}`).digest("hex").slice(0,32),costFields.identity_fingerprint=createHash119("sha256").update(`delegation-cost-identity-v1\x00${recordMaterial}\x00${agentName}\x00${configuredModel}`).digest("hex").slice(0,32),costFields.version=1,costFields.parent_session_digest=createHash119("sha256").update(`delegation-cost-parent-v1\x00${sessionId}`).digest("hex").slice(0,32),childSessionID)costFields.child_session_digest=createHash119("sha256").update(`delegation-cost-child-v1\x00${childSessionID}`).digest("hex").slice(0,32);swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME,bootstrapRoot);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){let costTaskId=beganDelegation?.taskId||taskSession.currentTaskId||"";if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,costTaskId,"completed",costFields),childSessionID&&costFields.evidence_status!=="complete"&&costFields.record_id&&costFields.identity_fingerprint)trackPendingCostCorrection(childSessionID,{recordId:costFields.record_id,identityFingerprint:costFields.identity_fingerprint,parentSessionId:sessionId,parentSessionDigest:costFields.parent_session_digest,agentName,taskId:costTaskId,model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retryIndex:activeWindow?.transientRetryCount,pricing:config3.pricing,version:1,currentFields:costFields});if(baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=applySoundingBoardResponsePolicy(rawResponse,afterCtx.args);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.category)verdictMsg+=` Category: ${parsed.category}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){recordSessionChatAgent(String(input.sessionID),input.agent);let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);try{if(input2?.sessionID&&typeof input2?.agent==="string"&&input2.agent.trim()!=="")maybeEmitNonArchitectAdvisory(String(input2.sessionID),String(input2.agent))}catch{}if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model;else if(resolution.status==="missing"){let sessionResolution=resolveSessionChatModelOverride({sessionID:String(input2.sessionID),role:routeModel.role,swarmID:routeModel.swarmID,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels});if(sessionResolution.status==="override"&&sessionResolution.model)output2.message.model=sessionResolution.model}}}if(input2?.sessionID){let messageModel=output2.message?.model;if(messageModel&&typeof messageModel==="object")setLiveContextWindow(String(input2.sessionID),void 0,{modelID:typeof messageModel.modelID==="string"?messageModel.modelID:typeof messageModel.id==="string"?messageModel.id:void 0,providerID:typeof messageModel.providerID==="string"?messageModel.providerID:void 0})}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(bootstrapRoot,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(bootstrapRoot,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm,setup:(ctx)=>openCodeSwarmV2Setup(ctx,{runInit:runServerInit})};export{schedulePostResolutionTasksForTest,recoverPendingCostCorrectionForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,applySoundingBoardResponsePolicy,_resetDelegationTelemetryPairingForTesting};