opencode-swarm 7.187.2 → 7.187.3
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.
- package/README.md +18 -1
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{auto-checkpoint-2xmptd5t.js → auto-checkpoint-521fehr3.js} +7 -7
- package/dist/cli/{checkpoint-2y7z19y5.js → checkpoint-czx5eken.js} +12 -12
- package/dist/cli/{coder-settlement-s4d28fa6.js → coder-settlement-skfkfgt7.js} +8 -8
- package/dist/cli/{config-doctor-312afzhr.js → config-doctor-t88fd5ra.js} +11 -11
- package/dist/cli/{core-2bywxc4w.js → core-fap9x47g.js} +1 -1
- package/dist/cli/{curation-policy-sr29thf5.js → curation-policy-e1ce7ha8.js} +5 -5
- package/dist/cli/{curator-dvhf6jex.js → curator-b7zzsv98.js} +35 -35
- package/dist/cli/{curator-drift-xx8pp4g9.js → curator-drift-ea11apaw.js} +5 -5
- package/dist/cli/{curator-llm-factory-4g2nvr76.js → curator-llm-factory-758hynyn.js} +35 -35
- package/dist/cli/{doctor-knowledge-receipt-phase-id-m239pgbz.js → doctor-knowledge-receipt-phase-id-5768wb0n.js} +6 -6
- package/dist/cli/{evidence-summary-service-9et04fjh.js → evidence-summary-service-z2yj87tn.js} +15 -15
- package/dist/cli/{gate-evidence-73vj3bgm.js → gate-evidence-m90ynftc.js} +5 -5
- package/dist/cli/{guardrail-explain-8n4fx9zv.js → guardrail-explain-y2g82gqv.js} +36 -36
- package/dist/cli/{guardrail-log-9gmfvnd7.js → guardrail-log-c50qd8sf.js} +6 -6
- package/dist/cli/{guardrail-reset-k3mrq25e.js → guardrail-reset-h7g9a90e.js} +35 -35
- package/dist/cli/{hive-promoter-bp3rz0q6.js → hive-promoter-wpcn3wyz.js} +35 -35
- package/dist/cli/{index-310h5192.js → index-02nzb100.js} +2 -2
- package/dist/cli/{index-exj7czz9.js → index-10h0jx4e.js} +4 -4
- package/dist/cli/{index-tkm2rj27.js → index-45d3vpry.js} +1 -1
- package/dist/cli/{index-m1vsqmyr.js → index-468s960k.js} +1 -1
- package/dist/cli/{index-b5tthmy2.js → index-4tmk29gc.js} +1 -1
- package/dist/cli/{index-w0bvez8c.js → index-5ktekhxk.js} +1 -1
- package/dist/cli/{index-3ckfawjf.js → index-5x8zhfsq.js} +3 -3
- package/dist/cli/{index-pqffq9mm.js → index-6551m2st.js} +2 -2
- package/dist/cli/{index-tq6sbcys.js → index-6rdajskg.js} +94 -81
- package/dist/cli/{index-v9y0230d.js → index-7ba0hdg4.js} +1 -1
- package/dist/cli/{index-z04d01pv.js → index-7fekgghd.js} +7 -7
- package/dist/cli/{index-f6pft90q.js → index-7t15ybzn.js} +3 -3
- package/dist/cli/{index-tngc1erw.js → index-a5pjm9zc.js} +2 -2
- package/dist/cli/{index-jyxgkp4a.js → index-bkcd3nwh.js} +1 -1
- package/dist/cli/{index-3y0nr248.js → index-by488z8m.js} +3 -3
- package/dist/cli/{index-9jafghwk.js → index-by7x4ty3.js} +35 -35
- package/dist/cli/{index-n55exns2.js → index-e3vbyy10.js} +1 -1
- package/dist/cli/{index-3g3n9fjq.js → index-ez4kkgcd.js} +3 -3
- package/dist/cli/{index-26zs9wsj.js → index-fk7s8btv.js} +2 -2
- package/dist/cli/{index-j5db3v56.js → index-h03j41jw.js} +4 -4
- package/dist/cli/{index-kc635w60.js → index-h7p78r0w.js} +4 -4
- package/dist/cli/{index-e9ry78z5.js → index-hrxr48p5.js} +2 -2
- package/dist/cli/{index-wpxy7099.js → index-japwz660.js} +1 -1
- package/dist/cli/{index-jh9nrshe.js → index-ksvm96bz.js} +1 -1
- package/dist/cli/{index-tmp07h7b.js → index-m3dcecc5.js} +37 -37
- package/dist/cli/{index-33345434.js → index-mdxrk3az.js} +3 -3
- package/dist/cli/{index-xs070yr9.js → index-mh3nsv7v.js} +2 -2
- package/dist/cli/{index-7fxy1s86.js → index-naxtsh2e.js} +4 -4
- package/dist/cli/{index-xv0t2sed.js → index-npkxp81s.js} +4 -4
- package/dist/cli/{index-n8kqhxay.js → index-nsvm2j4x.js} +1 -1
- package/dist/cli/{index-n45kz69m.js → index-q0am9gm3.js} +1 -1
- package/dist/cli/{index-dx6bhbd6.js → index-sec8fwf1.js} +3 -3
- package/dist/cli/{index-dqberkr3.js → index-v8ytrkrg.js} +4 -4
- package/dist/cli/{index-b308erem.js → index-w3xapqjq.js} +3 -3
- package/dist/cli/{index-efbhea00.js → index-w9p41945.js} +1 -1
- package/dist/cli/{index-rtdxyjrg.js → index-wvkbp1qr.js} +6 -6
- package/dist/cli/{index-6t7ygevg.js → index-xpj149rz.js} +1 -1
- package/dist/cli/{index-4g39nne8.js → index-yk9vs9pw.js} +2 -2
- package/dist/cli/{index-y81jjedn.js → index-zbv9t6p2.js} +6 -6
- package/dist/cli/{index-85cx1mmb.js → index-zzgv4jy6.js} +4 -4
- package/dist/cli/index.js +36 -36
- package/dist/cli/{knowledge-escalator-fnqctvxz.js → knowledge-escalator-wzsxp6yg.js} +12 -12
- package/dist/cli/{knowledge-events-mr1vh3nb.js → knowledge-events-dcchq50n.js} +10 -10
- package/dist/cli/{knowledge-link-93nzznwd.js → knowledge-link-zh9rzesj.js} +4 -4
- package/dist/cli/{knowledge-store-dxy4s9k6.js → knowledge-store-p27r8wa9.js} +5 -5
- package/dist/cli/{knowledge-validator-gy39attk.js → knowledge-validator-rmtymth5.js} +7 -7
- package/dist/cli/{mcp-bxb59wsq.js → mcp-jr1rr2zd.js} +1 -1
- package/dist/cli/{model-preflight-2kje0sp0.js → model-preflight-xzy5x4rt.js} +35 -35
- package/dist/cli/{pending-delegations-fm2nx2k0.js → pending-delegations-4k740a2c.js} +7 -7
- package/dist/cli/{pr-subscriptions-g4f9rehb.js → pr-subscriptions-515xdgjj.js} +7 -7
- package/dist/cli/{pr-workflow-gate-qtq1wq95.js → pr-workflow-gate-srpa0mds.js} +35 -35
- package/dist/cli/{runner-verr6er5.js → runner-tk1cmgzt.js} +5 -5
- package/dist/cli/{scan-cursor-8taj944f.js → scan-cursor-w89sck5y.js} +6 -6
- package/dist/cli/{schema-yxq3bjmd.js → schema-1mwgvrv7.js} +1 -1
- package/dist/cli/{scope-persistence-jppvjncr.js → scope-persistence-qen27qx7.js} +11 -11
- package/dist/cli/{server-2s7wqg9e.js → server-rhz44ye9.js} +35 -35
- package/dist/cli/{skill-generator-pyf95aqw.js → skill-generator-05mxym3d.js} +14 -14
- package/dist/cli/{snapshot-coordination-init-8gbxw9sa.js → snapshot-coordination-init-jjegs3v5.js} +35 -35
- package/dist/cli/{speckit-checkoff-x2z0jamv.js → speckit-checkoff-3m04ks95.js} +3 -3
- package/dist/cli/{telemetry-xwj899pd.js → telemetry-vwxbsnye.js} +1 -1
- package/dist/cli/{worktree-collision-ownership-455bdcnk.js → worktree-collision-ownership-0d73y8h0.js} +7 -7
- package/dist/cli/{worktree-isolation-8x4p7tvm.js → worktree-isolation-d0vn38wb.js} +35 -35
- package/dist/index.js +7 -7
- package/dist/models/model-override-state.d.ts +24 -1
- package/dist/models/task-model-routing.d.ts +58 -1
- 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.187.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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.187.3",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
|
|
|
@@ -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:282"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:669",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:673",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",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:737",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:785",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:967",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:975",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1000",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:681",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:691",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:724",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:959",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:2087",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:2107",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:818",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:832",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:746",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:763",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:750",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:773",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:1169",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:789",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:808",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1402",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:846",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:859",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:955",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:963",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:985",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:873",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:894",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:908",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:925",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:942",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1383",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1015",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1029",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1042",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1056",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1081",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}],["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:1118",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:1140",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:1184",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:1221",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:1247",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:1271",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:1294",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:1323",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:1367",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"]),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})}},_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:282"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:669",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:673",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",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:737",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:785",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:967",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:975",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1000",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:681",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:691",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:724",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:964",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:2093",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:2113",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:818",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:832",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:746",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:763",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:750",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:773",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:1169",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:789",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:808",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1402",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:846",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:859",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:955",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:963",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:985",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:873",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:894",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:908",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:925",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:942",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1383",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1015",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1029",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1042",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1056",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1081",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}],["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:1118",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:1140",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:1184",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:1221",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:1247",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:1271",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:1294",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:1323",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:1367",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"]),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})}},_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(`
|
|
@@ -1271,7 +1271,7 @@ ${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else
|
|
|
1271
1271
|
Rule 3: ONE task per coder call. Split this into separate delegations.
|
|
1272
1272
|
${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
1273
1273
|
`)}`,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(`
|
|
1274
|
-
`)}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&¤t.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function clearScopedModelSelectionsForSession(sessionID){let normalizedSessionID=normalizeText2(sessionID);for(let[key2,entry]of scopedModelOverrides)if(key2.startsWith(`${normalizedSessionID}␟`))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 clearPendingTaskModelRoutesForSession(sessionID){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)}clearScopedModelSelectionsForSession(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,routesByParentCall,routeKeyByChildSession;var init_task_model_routing=__esm(()=>{init_model_override_state();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&¤t.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}
|
|
1274
|
+
`)}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&¤t.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&¤t.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
1275
|
`,{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(`
|
|
1276
1276
|
`),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&¤tOwner2&¤tOwner2!==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(`
|
|
1277
1277
|
`))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(`
|
|
@@ -1288,7 +1288,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
|
1288
1288
|
`).filter((line)=>line.trim().length>0).length,bytes:stat9.size}}catch{return{lines:0,bytes:0}}}function compactTerminalRecords(view,checkpoint2){let now=Date.now(),terminals=Object.entries(view).filter(([,rec])=>rec.status!=="active").sort((a,b)=>b[1].updatedAt-a[1].updatedAt);if(terminals.length===0)return null;if(!terminals.some(([,rec])=>now-rec.updatedAt>PR_SUBSCRIPTION_LIMITS.terminalMaxAgeMs)&&terminals.length<=PR_SUBSCRIPTION_LIMITS.terminalRecordsHigh)return null;let kept=0;for(let[key2,rec]of terminals)if(now-rec.updatedAt>PR_SUBSCRIPTION_LIMITS.terminalMaxAgeMs||kept>=PR_SUBSCRIPTION_LIMITS.terminalRecordsLow){if(rec.status==="removed")checkpoint2.terminalSummary.removed+=1;else checkpoint2.terminalSummary.expired+=1;checkpoint2.terminalSummary.lastTerminalAt=Math.max(checkpoint2.terminalSummary.lastTerminalAt??0,rec.updatedAt),delete view[key2]}else kept+=1;return checkpoint2.maintenance.compactions+=1,checkpoint2.maintenance.lastCompactedAt=now,{kind:"compact"}}function maybeArchiveLegacy(directory,checkpoint2){let migration=checkpoint2.migration;if(!migration||!migration.done||migration.archived)return null;let legacy=storePath3(directory),stat9;try{stat9=_internals85.archiveStatSync(legacy)}catch(err){if(err.code==="ENOENT")migration.archived=!0;else log(`[pr-monitor] legacy archive inspection deferred: ${storageErrorCode(err)}`);return null}if(stat9.size!==migration.sourceBytes||stat9.mtimeMs!==migration.sourceMtimeMs)return null;_internals85.beforeArchiveLegacy(directory);try{stat9=_internals85.archiveStatSync(legacy)}catch{return null}if(stat9.size!==migration.sourceBytes||stat9.mtimeMs!==migration.sourceMtimeMs)return null;let archive=legacyArchivePath(directory),next=legacyArchiveNextPath(directory),previous=legacyArchivePreviousPath(directory);try{_internals85.beforeArchiveRename(directory);try{fs61.unlinkSync(next)}catch{}_internals85.renameWithRetry(legacy,next);let archivedStat=_internals85.archiveStatSync(next);if(archivedStat.size!==migration.sourceBytes||archivedStat.mtimeMs!==migration.sourceMtimeMs)return _internals85.renameWithRetry(next,legacy),null;let archivedAt=new Date;fs61.utimesSync(next,archivedAt,archivedAt);let movedPrevious=!1;try{fs61.unlinkSync(previous)}catch{}try{_internals85.renameWithRetry(archive,previous),movedPrevious=!0}catch(err){if(err.code!=="ENOENT")throw err}try{_internals85.renameWithRetry(next,archive)}catch(err){if(movedPrevious)_internals85.renameWithRetry(previous,archive);throw _internals85.renameWithRetry(next,legacy),err}if(movedPrevious)try{fs61.unlinkSync(previous)}catch{}}catch(err){try{if(fs61.existsSync(next)&&!fs61.existsSync(legacy))_internals85.renameWithRetry(next,legacy)}catch{}return log(`[pr-monitor] legacy archive deferred: ${storageErrorCode(err)}`),null}try{let now=Date.now()/1000;fs61.utimesSync(legacyArchivePath(directory),now,now)}catch{}return migration.archived=!0,{kind:"archive"}}function reconcileLegacyArchiveStaging(directory,migration){let legacy=storePath3(directory),archive=legacyArchivePath(directory),next=legacyArchiveNextPath(directory),previous=legacyArchivePreviousPath(directory),legacyExists=fileExistsStrict(legacy),archiveExists=fileExistsStrict(archive),nextExists=fileExistsStrict(next),previousExists=fileExistsStrict(previous);if(!nextExists&&!previousExists)return;if(legacyExists){if(!archiveExists&&previousExists)_internals85.renameWithRetry(previous,archive),archiveExists=!0,previousExists=!1;if(!archiveExists&&nextExists){let candidate=fs61.statSync(next);if(migration.done&&candidate.size===migration.sourceBytes&&candidate.mtimeMs===migration.sourceMtimeMs)_internals85.renameWithRetry(next,archive),archiveExists=!0,nextExists=!1}if(archiveExists&&previousExists)fs61.unlinkSync(previous);if(nextExists)fs61.unlinkSync(next);return}if(archiveExists){if(nextExists)_internals85.renameWithRetry(next,legacy),migration.archived=!1,legacyExists=!0,nextExists=!1;if(previousExists)fs61.unlinkSync(previous);return}if(previousExists){if(_internals85.renameWithRetry(previous,archive),archiveExists=!0,previousExists=!1,nextExists)fs61.unlinkSync(next),legacyExists=!0,nextExists=!1;return}if(nextExists){let candidate=fs61.statSync(next);if(migration.done&&candidate.size===migration.sourceBytes&&candidate.mtimeMs===migration.sourceMtimeMs)_internals85.renameWithRetry(next,archive);else _internals85.renameWithRetry(next,legacy),migration.archived=!1}}function cleanupStaleLegacyArchive(directory){try{let stat9=fs61.statSync(legacyArchivePath(directory));if(Date.now()-stat9.mtimeMs>PR_SUBSCRIPTION_LIMITS.legacyArchiveTtlMs)fs61.unlinkSync(legacyArchivePath(directory))}catch{}}function emitHealthTelemetry(directory,trigger,checkpoint2){let records=Object.values(checkpoint2.records),healthPayload={trigger,active_count:records.filter((r)=>r.status==="active").length,terminal_count:records.filter((r)=>r.status!=="active").length,compactions:checkpoint2.maintenance.compactions,corrupt_count:checkpoint2.maintenance.corruptLegacyRecords,dropped_audit_count:checkpoint2.maintenance.droppedAuditTransitions,checkpoint_bytes:Buffer.byteLength(`${JSON.stringify(checkpoint2)}
|
|
1289
1289
|
`,"utf-8"),limit_bytes:PR_SUBSCRIPTION_LIMITS.maxCheckpointBytes,recovery_resets:checkpoint2.maintenance.resets};telemetry.prSubscriptionHealth(healthPayload),observeStoreHealth({directory,kind:"pr_subscription_health",payload:healthPayload})}function warnLegacyOverLimit(directory,size){let key2=canonicalRootKey(directory);if(legacyOverLimitWarned.has(key2))return;if(legacyOverLimitWarned.size>=32)legacyOverLimitWarned.delete(legacyOverLimitWarned.keys().next().value);legacyOverLimitWarned.set(key2,!0),log(`[pr-monitor] legacy subscriptions.jsonl is ${size} bytes (>${PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes}); refusing to fold it — archive or split the file so its subscriptions can be re-subscribed, then remove it (reported via /swarm pr status)`)}function warnMigrationCapacity(directory,records){let key2=canonicalRootKey(directory);if(migrationCapacityWarned.has(key2))return;if(migrationCapacityWarned.size>=32)migrationCapacityWarned.delete(migrationCapacityWarned.keys().next().value);migrationCapacityWarned.set(key2,!0),log(`[pr-monitor] legacy subscriptions.jsonl folds to ${records} records (>checkpoint capacity ${PR_SUBSCRIPTION_LIMITS.maxCheckpointRecords}); migration refused — archive or split the file so its subscriptions can be re-subscribed, then remove it`)}function overlayLegacy(directory,checkpoint2){let view={...checkpoint2.records},legacy=storePath3(directory),stat9=null;try{stat9=fs61.statSync(legacy)}catch{}if(stat9===null)return{view,usedLegacy:!1,absorbed:0,corruptLines:0,overLimit:!1,aborted:!1};if(stat9.size>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes)return warnLegacyOverLimit(directory,stat9.size),{view,usedLegacy:!1,absorbed:0,corruptLines:0,overLimit:!0,aborted:!1};let migration=checkpoint2.migration;if(migration===null||!migration.done){let baselineRecords=migration?.baselineRecords??{...checkpoint2.records},sameGeneration=migration!==null&&stat9.size===migration.sourceBytes&&stat9.mtimeMs===migration.sourceMtimeMs,cursor=sameGeneration?migration.scannedBytes:0,discardingOversizeLine=sameGeneration?migration.discardingOversizeLine:!1;if(!sameGeneration&&migration!==null)view={...baselineRecords};let fold2=foldLegacyRegion(legacy,cursor,Number.MAX_SAFE_INTEGER,discardingOversizeLine);if(fold2.ioError)return{view,usedLegacy:!1,absorbed:0,corruptLines:0,overLimit:!1,aborted:!0};let absorbed2=mergeFoldedRecords(view,fold2.folded);return{view,usedLegacy:!0,absorbed:absorbed2,corruptLines:fold2.corruptLines,overLimit:!1,aborted:fold2.aborted}}if(stat9.size===migration.sourceBytes&&stat9.mtimeMs===migration.sourceMtimeMs)return{view,usedLegacy:!1,absorbed:0,corruptLines:0,overLimit:!1,aborted:!1};let fold=foldLegacyRegion(legacy,0,Number.MAX_SAFE_INTEGER);if(fold.ioError)return{view,usedLegacy:!1,absorbed:0,corruptLines:0,overLimit:!1,aborted:!0};let absorbed=mergeFoldedRecords(view,fold.folded);return{view,usedLegacy:!0,absorbed,corruptLines:fold.corruptLines,overLimit:!1,aborted:fold.aborted}}async function loadViewForRead(directory){if(ensurePrSubscriptionCoordinationImported(directory,!1)){let coordinationView=readCoordinationSubscriptions(directory)??{},checkpointRead=readCheckpoint(directory);if(checkpointRead.kind==="ok"&&sameProjectRoot(checkpointRead.value.rootPath,directory)&&checkpointRead.value.migration?.done===!1){let pendingCheckpoint=cloneCheckpoint(checkpointRead.value);pendingCheckpoint.records={...pendingCheckpoint.records,...coordinationView};let overlaid=overlayLegacy(directory,pendingCheckpoint);return{view:overlaid.view,recoverySource:overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}}return{view:coordinationView,recoverySource:"checkpoint"}}let read=readCheckpoint(directory),pendingCoordination=readCoordinationSubscriptions(directory);if(read.kind==="ok"&&sameProjectRoot(read.value.rootPath,directory)&&read.value.migration?.done===!1&&pendingCoordination!==null&&Object.keys(pendingCoordination).length>0){let pendingCheckpoint=cloneCheckpoint(read.value);pendingCheckpoint.records={...pendingCheckpoint.records,...pendingCoordination};let overlaid=overlayLegacy(directory,pendingCheckpoint);return{view:overlaid.view,recoverySource:overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}}if(read.kind==="ok"){if(!sameProjectRoot(read.value.rootPath,directory))return{view:{},recoverySource:"foreign"};if(read.value.migration?.done===!0){if(!legacyProjectionFingerprintMatches(directory,read.value)){if(fileExistsStrict(legacyArchivePath(directory)))return retireAuthoritativeLegacyShadow(directory),{view:{...read.value.records},recoverySource:"checkpoint"};let overlaid2=overlayLegacy(directory,read.value);if(overlaid2.usedLegacy&&!overlaid2.aborted)return{view:overlaid2.view,recoverySource:"checkpoint+legacy"}}return{view:{...read.value.records},recoverySource:"checkpoint"}}let overlaid=overlayLegacy(directory,read.value);return{view:overlaid.view,recoverySource:overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}}if(read.kind==="invalid"){let legacy=storePath3(directory),view2={},size=fileSizeOrNull(legacy);if(size!==null&&size<=PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes){let fold2=foldLegacyRegion(legacy,0,Number.MAX_SAFE_INTEGER);if(!fold2.ioError)mergeFoldedRecords(view2,fold2.folded)}else if(size!==null)warnLegacyOverLimit(directory,size);return{view:view2,recoverySource:"corrupt-recovered"}}let legacyPath=storePath3(directory),legacyStat;try{legacyStat=fs61.statSync(legacyPath)}catch{return{view:{},recoverySource:"empty"}}let legacySize=legacyStat.size;if(legacySize>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes)return warnLegacyOverLimit(directory,legacySize),{view:{},recoverySource:"legacy-log"};let fold=foldLegacyRegion(legacyPath,0,Number.MAX_SAFE_INTEGER),view={};if(fold.ioError)return{view,recoverySource:"legacy-log"};if(mergeFoldedRecords(view,fold.folded),!fold.aborted)_internals85.beforeBootstrapLock(directory),await bootstrapCheckpointFromLegacy(directory);return{view,recoverySource:"legacy-log"}}async function bootstrapCheckpointFromLegacy(directory){let key2=canonicalRootKeyFresh(directory);if(bootstrapAttempted.has(key2))return;if(bootstrapAttempted.size>=32)bootstrapAttempted.delete(bootstrapAttempted.keys().next().value);bootstrapAttempted.set(key2,!0);try{await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(readCheckpoint(directory).kind!=="absent")return;let beforeFold;try{beforeFold=fs61.statSync(storePath3(directory))}catch{return}let lockedFold=foldLegacyRegion(storePath3(directory),0,PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes);if(lockedFold.ioError)return;let afterFold;try{afterFold=fs61.statSync(storePath3(directory))}catch{return}if(afterFold.size!==beforeFold.size||afterFold.mtimeMs!==beforeFold.mtimeMs)return;let foldedView={};mergeFoldedRecords(foldedView,lockedFold.folded);let checkpoint2=freshCheckpoint(directory);checkpoint2.records={...foldedView};let terminals=Object.values(foldedView).filter((rec)=>rec.status!=="active");checkpoint2.terminalSummary.lastTerminalAt=terminals.length?Math.max(...terminals.map((rec)=>rec.updatedAt)):null,checkpoint2.maintenance.corruptLegacyRecords=lockedFold.corruptLines,checkpoint2.migration={scannedBytes:lockedFold.nextByte,sourceBytes:beforeFold.size,sourceMtimeMs:beforeFold.mtimeMs,corruptLines:lockedFold.corruptLines,discardingOversizeLine:!1,baselineRecords:{},baselineTerminalSummary:{removed:0,expired:0,lastTerminalAt:null},done:!0,archived:!1,startedAt:Date.now()},checkpoint2.sequence=1,checkpoint2.updatedAt=Date.now();let auditCompaction=prepareAuditCompaction(directory);persistCheckpointWithAuditCompaction(directory,checkpoint2,auditCompaction);let archiveEvent=maybeArchiveLegacy(directory,checkpoint2);if(archiveEvent)checkpoint2.sequence+=1,checkpoint2.updatedAt=Date.now(),_internals85.writeCheckpointFile(directory,checkpoint2);if(flushAuditEvents(directory,[{kind:"migrate-complete"},...archiveEvent?[archiveEvent]:[]],checkpoint2.sequence,checkpoint2.maintenance),emitHealthTelemetry(directory,"migrate-complete",checkpoint2),archiveEvent)emitHealthTelemetry(directory,"archive",checkpoint2)},PR_SUBSCRIPTION_LIMITS.bootstrapLockTimeoutMs)}catch(err){log(`[pr-monitor] read-bootstrap skipped: ${storageErrorCode(err)}`)}}function loadViewForWrite(directory){let audit=[],dirty=!1,reboundForeign=!1,checkpoint2,read=readCheckpoint(directory),archiveDeferredForExternalRewrite=!1;if(read.kind==="ok"&&sameProjectRoot(read.value.rootPath,directory))checkpoint2=cloneCheckpoint(read.value);else if(read.kind==="ok"){let displaced=Object.keys(read.value.records).length,legacy2=storePath3(directory),foreignLegacyExists=!1;try{_internals85.statSync(legacy2),foreignLegacyExists=!0}catch(err){if(err.code!=="ENOENT")throw Error(`PR subscription foreign legacy log could not be inspected; refusing to rebind (${storageErrorCode(err)})`)}if(foreignLegacyExists){let foreignLegacy=foreignLegacySlotPath(directory);try{try{fs61.unlinkSync(foreignLegacy)}catch{}_internals85.renameWithRetry(legacy2,foreignLegacy)}catch(err){throw Error(`PR subscription foreign legacy log could not be quarantined; refusing to rebind (${storageErrorCode(err)})`)}}if(!quarantineCheckpoint(directory,"foreign"))throw Error("PR subscription foreign checkpoint could not be quarantined; refusing to rebind");checkpoint2=freshCheckpoint(directory),checkpoint2.maintenance.resets+=read.value.maintenance.resets+1,audit.push({kind:"foreign-rebind"}),dirty=!0,log(`[pr-monitor] foreign checkpoint quarantined (${displaced} displaced records, recorded root ${read.value.rootPath}); store rebound to ${directory}`),reboundForeign=!0}else if(read.kind==="invalid")quarantineCheckpoint(directory,"corrupt"),checkpoint2=freshCheckpoint(directory),checkpoint2.maintenance.resets+=1,audit.push({kind:"corrupt-quarantine"}),dirty=!0,log(`[pr-monitor] corrupt checkpoint quarantined; store rebound to ${directory}`);else checkpoint2=freshCheckpoint(directory);if(!reboundForeign&&checkpoint2.migration!==null)try{reconcileLegacyArchiveStaging(directory,checkpoint2.migration)}catch(err){throw Error(`PR subscription legacy archive staging could not be reconciled; refusing mutation (${storageErrorCode(err)})`)}let legacy=storePath3(directory),legacyStat=null;try{legacyStat=_internals85.statSync(legacy)}catch(err){if(err.code!=="ENOENT")throw Error(`PR subscription legacy store could not be inspected; refusing mutation (${storageErrorCode(err)})`)}let view;if(reboundForeign)legacyStat=null;if(legacyStat===null){view={...checkpoint2.records};let importedShadowExists=fileExistsStrict(importedShadowPath(legacy)),archiveExists=fileExistsStrict(legacyArchivePath(directory));if(checkpoint2.migration?.done&&!checkpoint2.migration.archived&&(archiveExists||!importedShadowExists))checkpoint2.migration.archived=!0,dirty=!0;return{checkpoint:checkpoint2,view,audit,dirty}}if(legacyStat.size>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes)throw warnLegacyOverLimit(directory,legacyStat.size),Error(`PR subscription legacy store exceeds the ${PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes}-byte migration ceiling; refusing mutation until the file is archived or split`);if(checkpoint2.migration?.done===!0&&checkpoint2.migration.archived&&legacyProjectionFingerprintMatches(directory,checkpoint2))checkpoint2.migration.archived=!1,dirty=!0;if(checkpoint2.migration?.done===!0&&!legacyProjectionFingerprintMatches(directory,checkpoint2)){try{fs61.unlinkSync(projectionMarkerPath(legacy))}catch(error93){if(error93.code!=="ENOENT")throw error93}checkpoint2.migration=null,dirty=!0,archiveDeferredForExternalRewrite=!0}let{size:legacySize,mtimeMs:legacyMtime}=legacyStat,migration=checkpoint2.migration;if(migration===null||!migration.done){let baselineRecords=migration?.baselineRecords??{...checkpoint2.records},baselineTerminalSummary=migration?.baselineTerminalSummary??{...checkpoint2.terminalSummary},sameGeneration=migration!==null&&legacySize===migration.sourceBytes&&legacyMtime===migration.sourceMtimeMs,cursor=sameGeneration?migration.scannedBytes:0,startedAt=sameGeneration?migration.startedAt:Date.now(),corruptTotal=sameGeneration?migration.corruptLines:0,discardingOversizeLine=sameGeneration?migration.discardingOversizeLine:!1;if(!sameGeneration&&migration!==null)checkpoint2.records={...baselineRecords},checkpoint2.terminalSummary={...baselineTerminalSummary},checkpoint2.maintenance.corruptLegacyRecords=Math.max(0,checkpoint2.maintenance.corruptLegacyRecords-migration.corruptLines);view={...checkpoint2.records};let capacityRefused=!1,foldedThisOperation=0;while(!0){let chunkStart=cursor,remainingOperationBytes=Math.max(1,PR_SUBSCRIPTION_LIMITS.migrationMaxBytesPerOperation-foldedThisOperation),fold=foldLegacyRegion(legacy,cursor,Math.min(PR_SUBSCRIPTION_LIMITS.migrationChunkBytes,remainingOperationBytes),discardingOversizeLine);if(fold.ioError)throw Error("PR subscription legacy migration read failed (I/O error)");if(mergeFoldedRecords(view,fold.folded),checkpoint2.maintenance.corruptLegacyRecords+=fold.corruptLines,corruptTotal+=fold.corruptLines,discardingOversizeLine=fold.discardingOversizeLine,cursor=fold.nextByte,foldedThisOperation+=Math.max(0,cursor-chunkStart),fold.aborted){let progress=cloneCheckpoint(checkpoint2);return progress.records={...view},progress.migration={scannedBytes:cursor,sourceBytes:legacySize,sourceMtimeMs:legacyMtime,corruptLines:corruptTotal,discardingOversizeLine,baselineRecords:{...baselineRecords},baselineTerminalSummary:{...baselineTerminalSummary},done:!1,archived:!1,startedAt},progress.updatedAt=Date.now(),progress.sequence+=1,writeCheckpointFile(directory,progress),checkpoint2.sequence=progress.sequence,log(`[pr-monitor] legacy scan aborted by an I/O error after ${cursor} bytes — migration stays incomplete and will retry`),dirty=!0,{checkpoint:checkpoint2,view,audit,dirty}}let compactEvent=compactTerminalRecords(view,checkpoint2);if(compactEvent)audit.push(compactEvent);if(Object.keys(view).length>PR_SUBSCRIPTION_LIMITS.maxCheckpointRecords){capacityRefused=!0,warnMigrationCapacity(directory,Object.keys(view).length);break}let deferLargeInitialGeneration=!sameGeneration&&legacySize>PR_SUBSCRIPTION_LIMITS.migrationMaxBytesPerOperation&&foldedThisOperation>=PR_SUBSCRIPTION_LIMITS.migrationMaxBytesPerOperation;if(!fold.eof||deferLargeInitialGeneration){let progress=cloneCheckpoint(checkpoint2);if(progress.records={...view},progress.migration={scannedBytes:cursor,sourceBytes:legacySize,sourceMtimeMs:legacyMtime,corruptLines:corruptTotal,discardingOversizeLine,baselineRecords:{...baselineRecords},baselineTerminalSummary:{...baselineTerminalSummary},done:!1,archived:!1,startedAt},progress.updatedAt=Date.now(),progress.sequence+=1,writeCheckpointFile(directory,progress),checkpoint2.sequence=progress.sequence,dirty=!0,foldedThisOperation>=PR_SUBSCRIPTION_LIMITS.migrationMaxBytesPerOperation)throw Error(`PR subscription legacy migration is in progress (${cursor}/${legacySize} bytes); retry the operation to continue`);continue}checkpoint2.migration={scannedBytes:cursor,sourceBytes:legacySize,sourceMtimeMs:legacyMtime,corruptLines:corruptTotal,discardingOversizeLine:!1,baselineRecords:{},baselineTerminalSummary:{removed:0,expired:0,lastTerminalAt:null},done:!0,archived:archiveDeferredForExternalRewrite,startedAt},audit.push({kind:"migrate-complete"}),dirty=!0;break}if(capacityRefused)return{checkpoint:checkpoint2,view,audit,dirty:!1};return{checkpoint:checkpoint2,view,audit,dirty}}if(!legacyProjectionFingerprintMatches(directory,checkpoint2)){let legacyPath=storePath3(directory);if(fileExistsStrict(projectionMarkerPath(legacyPath))){let overlaid=overlayLegacy(directory,checkpoint2);return{checkpoint:checkpoint2,view:overlaid.view,audit,dirty}}retireAuthoritativeLegacyShadow(directory)}return{checkpoint:checkpoint2,view:{...checkpoint2.records},audit,dirty}}function finalizeWrite(directory,loaded,opAudit){let{checkpoint:checkpoint2}=loaded,events=[...loaded.audit,...opAudit],compactEvent=compactTerminalRecords(loaded.view,checkpoint2);if(compactEvent)events.push(compactEvent);if(!loaded.dirty&&events.length===0){let archiveEvent2=maybeArchiveLegacy(directory,checkpoint2);if(!archiveEvent2)return;checkpoint2.updatedAt=Date.now(),checkpoint2.sequence+=1;let auditCompaction2=prepareAuditCompaction(directory);persistCheckpointWithAuditCompaction(directory,checkpoint2,auditCompaction2),flushAuditEvents(directory,[archiveEvent2],checkpoint2.sequence,checkpoint2.maintenance),cleanupStaleLegacyArchive(directory),emitHealthTelemetry(directory,"archive",checkpoint2);return}checkpoint2.records=loaded.view,checkpoint2.updatedAt=Date.now(),checkpoint2.rootPath=path99.resolve(directory),checkpoint2.sequence+=1;let auditCompaction=prepareAuditCompaction(directory);if(persistCheckpointWithAuditCompaction(directory,checkpoint2,auditCompaction),checkpoint2.migration?.done===!0){let legacyPath=storePath3(directory);try{let legacyStat=fs61.statSync(legacyPath);if(legacyStat.size!==checkpoint2.migration.sourceBytes||legacyStat.mtimeMs!==checkpoint2.migration.sourceMtimeMs){let legacyPayload=Object.values(checkpoint2.records).map((entry)=>JSON.stringify(entry)).join(`
|
|
1290
1290
|
`)+(Object.keys(checkpoint2.records).length>0?`
|
|
1291
|
-
`:"");writeLegacyStoreFile(legacyPath,legacyPayload),fs61.writeFileSync(projectionMarkerPath(legacyPath),"","utf-8"),legacyStat=fs61.statSync(legacyPath)}checkpoint2.migration.sourceBytes=legacyStat.size,checkpoint2.migration.scannedBytes=legacyStat.size,checkpoint2.migration.sourceMtimeMs=legacyStat.mtimeMs}catch{}}flushAuditEvents(directory,events,checkpoint2.sequence,checkpoint2.maintenance);let archiveEvent=maybeArchiveLegacy(directory,checkpoint2);if(archiveEvent)events.push(archiveEvent),checkpoint2.sequence+=1,_internals85.writeCheckpointFile(directory,checkpoint2),flushAuditEvents(directory,[archiveEvent],checkpoint2.sequence,checkpoint2.maintenance);cleanupStaleLegacyArchive(directory);let coordinationView=readCoordinationSubscriptions(directory);if(coordinationView!==null&&!isDeepStrictEqualByJson(coordinationView,loaded.view))persistCoordinationSubscriptions(directory,{...loaded.view});for(let kind of["compact","migrate-complete","archive","foreign-rebind","corrupt-quarantine"])if(events.some((event)=>event.kind===kind))emitHealthTelemetry(directory,kind,checkpoint2)}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match2)return onSubscriptionCreated?.(directory,match2),match2;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record4={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,...input.forge?{forge:input.forge}:{},lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record4),view[correlationId]=record4,persistCoordinationSubscriptions(directory,view,!0,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record4),record4}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),finalizeWrite(directory,loaded,[]),match;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(loaded.view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record3={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,...input.forge?{forge:input.forge}:{},lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record3),loaded.view[correlationId]=record3,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record3),record3})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;let removed2={...match2,status:"removed",isWatching:!1,updatedAt:Date.now()};return view[correlationId]=removed2,persistCoordinationSubscriptions(directory,view,!0,[{kind:"unsubscribe",correlationId}]),removed2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return loaded.view[correlationId]=removed,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"unsubscribe",correlationId}]),removed})}async function listActive(directory){let{view}=await loadViewForRead(directory);return Object.values(view).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){let{view}=await loadViewForRead(directory);for(let record3 of Object.values(view))if(record3.status==="active"&&record3.repoFullName===repoFullName&&record3.prNumber===prNumber)return record3;return null}async function findSubscriptionRecordForPrUrl(directory,key2){if(key2.repoFullName!==void 0&&key2.prNumber!==void 0){let record3=await lookupByPr(directory,key2.repoFullName,key2.prNumber);if(record3&&(!key2.sessionID||record3.sessionID===key2.sessionID)&&(key2.prUrl===void 0||record3.prUrl===key2.prUrl||subscriptionPrUrlMatches(record3,key2.prUrl)))return record3;if(!key2.sessionID)return null}if(key2.prUrl===void 0&&key2.repoFullName===void 0)return null;if(key2.prUrl===void 0){let active2=await listActive(directory);for(let record3 of active2){if(key2.sessionID&&record3.sessionID!==key2.sessionID)continue;if(record3.repoFullName===key2.repoFullName&&record3.prNumber===key2.prNumber)return record3}return null}let active=await listActive(directory);for(let record3 of active){if(key2.sessionID&&record3.sessionID!==key2.sessionID)continue;if(record3.prUrl===key2.prUrl||subscriptionPrUrlMatches(record3,key2.prUrl))return record3}return null}function subscriptionPrUrlMatches(record3,prUrl){let left=canonicalForgePrUrl(record3.prUrl,record3.forge),right=canonicalForgePrUrl(prUrl,record3.forge);return left!==null&&left===right}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let existingCoordination=readCoordinationSubscriptions(directory);if(existingCoordination!==null&&!fileExistsStrict(storePath3(directory))&&!hasLegacyReconciliationArtifacts(directory)){let match2=Object.values(existingCoordination).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),existingCoordination[correlationId]=updated2,persistCoordinationSubscriptions(directory,existingCoordination),updated2}if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),view[correlationId]=updated2,persistCoordinationSubscriptions(directory,view),updated2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;if(!snapshotUpdateHasChanges(match,updates))return finalizeWrite(directory,loaded,[]),match;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return validateRecord3(updated),loaded.view[correlationId]=updated,loaded.dirty=!0,finalizeWrite(directory,loaded,[]),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},swept2=0,expiredCorrelationIds=[],now2=Date.now();for(let record3 of Object.values(view)){if(record3.status!=="active")continue;let prKey=`${record3.repoFullName}::${record3.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now2-record3.updatedAt>ttlMs;if(isMerged||isStale&&!record3.hasUnaddressedEvents)view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now2},expiredCorrelationIds.push(record3.correlationId),swept2+=1}if(swept2>0)persistCoordinationSubscriptions(directory,view,!0,expiredCorrelationIds.map((correlationId)=>({kind:"expired",correlationId})));return swept2}let loaded=loadViewForWrite(directory),opAudit=[],swept=0;for(let record3 of Object.values(loaded.view)){if(record3.status!=="active")continue;let prKey=`${record3.repoFullName}::${record3.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record3.updatedAt>ttlMs;if(isMerged){loaded.view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record3.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record3.hasUnaddressedEvents)loaded.view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record3.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return finalizeWrite(directory,loaded,opAudit),swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}async function getPrSubscriptionHealth(directory){try{let coordinationView=readCoordinationSubscriptions(directory),read=readCheckpoint(directory),migrationPending=read.kind==="ok"&&sameProjectRoot(read.value.rootPath,directory)&&read.value.migration?.done===!1;if(coordinationView!==null&&Object.keys(coordinationView).length>0&&!migrationPending){let audit2=auditStats(directory),archiveBytes2=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes2=fileSizeOrNull(checkpointPath(directory))??0,health2=healthFromView(coordinationView,buildCoordinationProjectionCheckpoint(directory,coordinationView));return health2.recoverySource="checkpoint",applyFileStats(health2,checkpointBytes2,audit2,archiveBytes2),health2}let audit=auditStats(directory),archiveBytes=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes=fileSizeOrNull(checkpointPath(directory))??0,legacySize=fileSizeOrNull(storePath3(directory)),legacyOverLimit=legacySize!==null&&legacySize>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes,health;if(read.kind==="ok"&&!sameProjectRoot(read.value.rootPath,directory))health=emptyHealth2(),health.recoverySource="foreign";else if(read.kind==="invalid"){if(legacySize!==null&&!legacyOverLimit){let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}else health=emptyHealth2();health.recoverySource="corrupt-recovered"}else if(read.kind==="absent"){if(legacySize===null||legacyOverLimit)health=emptyHealth2();else{let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}health.recoverySource=legacySize===null?"empty":"legacy-log"}else{let pendingCheckpoint=migrationPending&&coordinationView!==null?(()=>{let merged=cloneCheckpoint(read.value);return merged.records={...merged.records,...coordinationView},merged})():read.value,overlaid=overlayLegacy(directory,pendingCheckpoint);health=healthFromView(overlaid.view,read.value),health.recoverySource=overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}return health.legacyOverLimit=legacyOverLimit,applyFileStats(health,checkpointBytes,audit,archiveBytes),health}catch(err){return log(`[pr-monitor] getPrSubscriptionHealth failed: ${storageErrorCode(err)}`),emptyHealth2()}}function applyFileStats(health,checkpointBytes,audit,archiveBytes){health.checkpointBytes=checkpointBytes,health.pressurePct=checkpointBytes===0?0:Math.round(checkpointBytes/health.checkpointLimitBytes*1000)/10,health.auditLines=audit.lines,health.auditBytes=audit.bytes,health.legacyArchiveBytes=archiveBytes}function emptyHealth2(){return{schemaVersion:1,sequence:0,checkpointAgeMs:null,checkpointBytes:0,checkpointLimitBytes:PR_SUBSCRIPTION_LIMITS.maxCheckpointBytes,pressurePct:0,activeCount:0,removedCount:0,expiredCount:0,terminalSummary:{removed:0,expired:0,lastTerminalAt:null},auditLines:0,auditBytes:0,auditLimitBytes:PR_SUBSCRIPTION_LIMITS.auditMaxBytesHigh,compactions:0,corruptLegacyRecords:0,droppedAuditTransitions:0,resets:0,recoverySource:"empty",migration:null,legacyArchiveBytes:0,legacyOverLimit:!1}}function healthFromView(view,checkpoint2){let records=Object.values(view),health=emptyHealth2();return health.sequence=checkpoint2.sequence,health.checkpointAgeMs=checkpoint2.sequence>0?Date.now()-checkpoint2.updatedAt:null,health.activeCount=records.filter((r)=>r.status==="active").length,health.removedCount=records.filter((r)=>r.status==="removed").length,health.expiredCount=records.filter((r)=>r.status==="expired").length,health.terminalSummary={...checkpoint2.terminalSummary},health.compactions=checkpoint2.maintenance.compactions,health.corruptLegacyRecords=checkpoint2.maintenance.corruptLegacyRecords,health.droppedAuditTransitions=checkpoint2.maintenance.droppedAuditTransitions,health.resets=checkpoint2.maintenance.resets,health.migration=checkpoint2.migration?{done:checkpoint2.migration.done,scannedBytes:checkpoint2.migration.scannedBytes,sourceBytes:checkpoint2.migration.sourceBytes}:null,health}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",PR_SUBSCRIPTIONS_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.json",PR_SUBSCRIPTIONS_AUDIT_FILE="pr-monitor/subscriptions.audit.jsonl",LEGACY_ARCHIVE_FILE="pr-monitor/subscriptions.legacy.jsonl",FOREIGN_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.foreign.json",CORRUPT_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.corrupt.json",FOREIGN_LEGACY_FILE="pr-monitor/subscriptions.legacy.foreign.jsonl",PR_SUBSCRIPTION_COORDINATION_NAMESPACE="background.pr-subscription",STORE_LOCK_AGENT="pr-monitor",STORE_LOCK_TASK="pr-subscriptions",PR_SUBSCRIPTION_LIMITS,onSubscriptionCreated=null,prMonitorWorkerHandlers,MAX_PR_MONITOR_WORKER_HANDLERS=64,RecordSchema,TerminalSummarySchema,MigrationSchema,MaintenanceSchema,CheckpointSchema,PrSubscriptionCapacityError,legacyOverLimitWarned,migrationCapacityWarned,bootstrapAttempted,_internals85;var init_pr_subscriptions=__esm(()=>{init_zod();init_db();init_lock();init_learning_health();init_utils2();init_forge_provider();init_telemetry();init_utils();init_atomic_write();init_canonical_root();PR_SUBSCRIPTION_LIMITS={readChunkBytes:65536,maxRecordBytes:65536,migrationChunkBytes:1048576,migrationMaxBytesPerOperation:8388608,legacySourceMaxBytes:67108864,defaultMaxActiveSubscriptions:20,maxCheckpointRecords:512,maxCheckpointBytes:262144,checkpointHardReadBytes:1048576,terminalRecordsHigh:60,terminalRecordsLow:30,terminalMaxAgeMs:2592000000,auditMaxLinesHigh:500,auditMaxLinesLow:250,auditMaxBytesHigh:131072,auditMaxBytesLow:65536,legacyArchiveTtlMs:604800000,bootstrapLockTimeoutMs:5000};prMonitorWorkerHandlers=new Map;RecordSchema=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/\s]+(?:\/[^/\s]+)+$/,"Must be owner/repo format (GitLab nested namespaces allowed)"),prUrl:exports_external.string().min(1),forge:exports_external.object({provider:exports_external.literal("gitlab"),host:exports_external.string().min(1)}).optional(),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict().superRefine((record3,ctx)=>{if(isForgePrUrl(record3.prUrl))return;if(record3.forge&&isForgePrUrl(record3.prUrl,{provider:record3.forge.provider,host:record3.forge.host}))return;ctx.addIssue({code:exports_external.ZodIssueCode.custom,path:["prUrl"],message:"Must be a valid PR URL (GitHub /pull/N or GitLab /-/merge_requests/N)"})}),TerminalSummarySchema=exports_external.object({removed:exports_external.number().int().min(0),expired:exports_external.number().int().min(0),lastTerminalAt:exports_external.number().int().nullable()}).strict(),MigrationSchema=exports_external.object({scannedBytes:exports_external.number().int().nonnegative(),sourceBytes:exports_external.number().int().nonnegative(),sourceMtimeMs:exports_external.number().nonnegative(),corruptLines:exports_external.number().int().nonnegative(),discardingOversizeLine:exports_external.boolean().optional().default(!1),baselineRecords:exports_external.record(exports_external.string(),RecordSchema).optional().default({}),baselineTerminalSummary:TerminalSummarySchema.optional().default({removed:0,expired:0,lastTerminalAt:null}),done:exports_external.boolean(),archived:exports_external.boolean(),startedAt:exports_external.number().int().nonnegative()}).strict(),MaintenanceSchema=exports_external.object({compactions:exports_external.number().int().nonnegative(),droppedAuditTransitions:exports_external.number().int().nonnegative(),corruptLegacyRecords:exports_external.number().int().nonnegative(),lastCompactedAt:exports_external.number().int().nullable(),resets:exports_external.number().int().nonnegative()}).strict(),CheckpointSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative(),records:exports_external.record(exports_external.string(),RecordSchema),terminalSummary:TerminalSummarySchema,migration:MigrationSchema.nullable(),maintenance:MaintenanceSchema}).strict();PrSubscriptionCapacityError=class PrSubscriptionCapacityError extends Error{constructor(message){super(message);this.name="PrSubscriptionCapacityError"}};legacyOverLimitWarned=new Map;migrationCapacityWarned=new Map;bootstrapAttempted=new Map;_internals85={afterCheckpointFstat:(_filePath)=>{},archiveStatSync:fs61.statSync,auditCompactionWrite:atomicWriteSwarmFileSync,beforeBootstrapLock:(_directory2)=>{},beforeArchiveLegacy:(_directory2)=>{},beforeArchiveRename:(_directory2)=>{},foldLegacyRegion,legacyCloseSync:fs61.closeSync,legacyFstatSync:fs61.fstatSync,mergeFoldedRecords,readSync:fs61.readSync,renameWithRetry:renameWithRetry5,sameProjectRoot,statSync:fs61.statSync,writeCheckpointFile}});var exports_state={};__export(exports_state,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,settleReviewerScopeMergeback:()=>settleReviewerScopeMergeback,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setFinalPromptPressure:()=>setFinalPromptPressure,setFinalAccountingWarningBand:()=>setFinalAccountingWarningBand,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resolveInitialTurboMode:()=>resolveInitialTurboMode,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,reserveStageBRouteEvidence:()=>reserveStageBRouteEvidence,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBRouteEvidence:()=>recordStageBRouteEvidence,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordReviewerScopeGenerationCaptureFailure:()=>recordReviewerScopeGenerationCaptureFailure,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReviewerScopeGenerationByStatus:()=>peekReviewerScopeGenerationByStatus,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markStageBRouteRequired:()=>markStageBRouteRequired,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,markReviewerScopeGenerationNoChange:()=>markReviewerScopeGenerationNoChange,markReviewerScopeGenerationMergebackPending:()=>markReviewerScopeGenerationMergebackPending,isStageBRouteRequired:()=>isStageBRouteRequired,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasModifiedFilesForTask:()=>hasModifiedFilesForTask,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getStageBRouteEvidence:()=>getStageBRouteEvidence,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getRehydrationCache:()=>getRehydrationCache,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getFinalPromptPressure:()=>getFinalPromptPressure,getFinalAccountingWarningBand:()=>getFinalAccountingWarningBand,getDisplayFinalPromptPressure:()=>getDisplayFinalPromptPressure,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearStageBRouteRequired:()=>clearStageBRouteRequired,clearStageBRouteEvidence:()=>clearStageBRouteEvidence,clearGateDenialCount:()=>clearGateDenialCount,clearFinalAccountingWarningBands:()=>clearFinalAccountingWarningBands,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals86,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID13}from"node:crypto";import*as fs62 from"node:fs/promises";import*as path100 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),captureFailures:generation.captureFailures.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetBySession.clear(),swarmState.finalPromptPressureBySession.clear(),clearAllTurnLedgers(),swarmState.finalAccountingWarningBandsBySession.clear(),swarmState.liveContextWindows.clear(),swarmState.agentSessions.clear(),clearSnapshotSessionOwnerships(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],clearHydrationOwnershipState(),swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearAllActionCircuits(),clearAllTaskModelRoutingState(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID13(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations){if(entry.status==="claimed"||entry.status==="mergeback_pending"||entry.status==="mergeback_mismatch")continue;if(!Number.isFinite(entry.createdAt)||now<entry.createdAt||now-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key2)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512)||!input.captureDirectory.trim()||!input.workspaceIdentity.trim())return null;let now=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key3,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key3);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,captureDirectory:input.captureDirectory,workspaceIdentity:input.workspaceIdentity,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],captureFailures:[],status:"collecting",createdAt:now};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key2,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key2),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;generation.captureFailures=generation.captureFailures.filter((entry)=>entry.file!==input.fingerprint.file);let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function recordReviewerScopeGenerationCaptureFailure(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096))return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0],now=input.at??Date.now();generation.modifiedFileFingerprints=generation.modifiedFileFingerprints.filter((entry)=>entry.file!==input.file);let existingIndex=generation.captureFailures.findIndex((entry)=>entry.file===input.file);if(existingIndex>=0){let existing=generation.captureFailures[existingIndex];return generation.captureFailures[existingIndex]={...existing,code:input.code,retryable:input.retryable,attempts:existing.attempts+1,at:now},!0}if(generation.captureFailures.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)generation.captureFailures.shift();return generation.captureFailures.push({file:input.file,code:input.code,retryable:input.retryable,attempts:1,at:now}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;let generation=matches[0];if(generation.status==="ready")return!0;if(input.primaryWorkspaceIdentity&&generation.workspaceIdentity!==input.primaryWorkspaceIdentity)return!1;if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file3)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file3))))return!1;return generation.status="ready",generation.readyAt=now,!0}function markReviewerScopeGenerationNoChange(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.at??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.length!==0)return!1;return generation.status="no_change",generation.readyAt=now,!0}function markReviewerScopeGenerationMergebackPending(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="mergeback_pending")return!0;return matches[0].status="mergeback_pending",!0}function settleReviewerScopeMergeback(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status==="mergeback_pending");if(matches.length!==1)return!1;let generation=matches[0],now=input.outcome.at??Date.now();if(input.outcome.verified){if(generation.status="ready",generation.readyAt===void 0)generation.readyAt=now;return generation.mergeback={verifiedAt:now,primaryWorkspaceIdentity:input.outcome.primaryWorkspaceIdentity},generation.captureDirectory=input.outcome.primaryDirectory,generation.workspaceIdentity=input.outcome.primaryWorkspaceIdentity,!0}return generation.status="mergeback_mismatch",generation.mergeback={failedAt:now,reason:input.outcome.reason},!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReviewerScopeGenerationByStatus(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status===input.status);return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key2,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,captureDirectory:generation.captureDirectory,workspaceIdentity:generation.workspaceIdentity,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2})),createdAt:generation.createdAt,readyAt:generation.readyAt??input.now??Date.now(),consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key2),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file3)=>declared.has(file3)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs){if(directory&&isSnapshotSessionOwnedLocally(id)&&!isSnapshotSessionAuthoritativelyStale(directory,id,staleDurationMs,now))continue;staleIds.push(id)}for(let id of staleIds){if(directory&&isSnapshotSessionOwnedLocally(id)){try{deleteSnapshotSessionRows(directory,id,"stale")}catch(error93){warn("[state] durable stale-session teardown failed:",error93 instanceof Error?error93.message:String(error93))}try{clearOverrideForSession(directory,id)}catch(error93){warn("[state] durable stale-session override teardown failed:",error93 instanceof Error?error93.message:String(error93))}}releaseSnapshotSessionOwnership(id),swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),swarmState.activeAgent.delete(id)}return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now,directory)}function resolveInitialTurboMode(directory){if(!directory)return!1;try{return _internals86.loadPluginConfigWithMeta(directory).config.turbo_mode===!0}catch{return!1}}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let owningProjectKey=directory?hydrationProjectKey(directory):void 0,hydrationAuthority=owningProjectKey?captureCurrentHydrationAuthority(owningProjectKey):void 0,hydrationStamp=owningProjectKey?nextSessionHydrationStamp(owningProjectKey):void 0,hydrationAuthorityEpoch2=hydrationAuthority?.authorityEpoch;sweepStaleSessions(staleDurationMs,now,directory);let initialTurboMode=resolveInitialTurboMode(directory),sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,taskWorkflowCache:new Map,stageBCompletion:new Map,stageBRouteEvidence:new Map,stageBRouteRequiredTasks:new Set,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID13(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,turboMode:initialTurboMode,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,owningProjectKey,hydrationStamp,hydrationAuthorityEpoch:hydrationAuthorityEpoch2,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,prmEpisodes:new Map,prmEpisodeGeneration:0,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals86.applyRehydrationCache(sessionState),directory){let liveSession=sessionState,shouldCommitRehydration=()=>hydrationAuthority!==void 0&&isHydrationAuthorityCurrent(hydrationAuthority)&&swarmState.agentSessions.get(sessionId)===liveSession,rehydrationPromise;rehydrationPromise=_internals86.rehydrateSessionFromDisk(directory,sessionState,shouldCommitRehydration).then(async()=>{if(!shouldCommitRehydration())return;try{let subscriptions=await _internals86.rehydratePrSubscriptions(sessionId,directory);if(!shouldCommitRehydration())return;sessionState.prSubscriptions=subscriptions}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId,directory){if(directory){try{deleteSnapshotSessionRows(directory,sessionId)}catch(error93){warn("[state] durable snapshot session teardown failed:",error93 instanceof Error?error93.message:String(error93))}try{clearOverrideForSession(directory,sessionId)}catch(error93){warn("[state] durable session override teardown failed:",error93 instanceof Error?error93.message:String(error93))}}releaseSnapshotSessionOwnership(sessionId);let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(!session.completionGateWarnedForTask)session.completionGateWarnedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(!(session.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID13();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(session.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(STALE_SESSION_TTL_MS,now,directory),session}if(_internals86.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName),lastId=session.lastInvocationIdByAgent[stripped]||0;if(lastId>0)clearInvocationActionCircuits(sessionId,lastId),clearPendingTaskModelRoutesForSession(sessionId);let newId=lastId+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key2=`${stripped}:${newId}`;return session.windows[key2]=window2,pruneOldWindows(sessionId,86400000,50),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key2=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key2]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files,workspaceDirectory){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.map((file3)=>canonicalAttributionPath(file3,workspaceDirectory)).filter((file3)=>file3!==null))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file3,workspaceDirectory){if(typeof file3!=="string"||file3.trim().length===0)return!1;if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let canonical=canonicalAttributionPath(file3,workspaceDirectory);if(canonical===null)return!0;let entries=ensureModifiedFilesByTask(session),current=entries.get(taskId)??[];if(current.includes(canonical))return!0;if(entries.set(taskId,[...current,canonical]),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function hasModifiedFilesForTask(session,taskId){if(!session)return!1;if(!isValidTaskId2(taskId))return!1;if(!(session.modifiedFilesByTask instanceof Map))return!1;return session.modifiedFilesByTask.has(taskId)}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides2){let cache2=ensureTaskWorkflowCache(session),existing=cache2.get(taskId);cache2.set(taskId,{generation:overrides2.generation??existing?.generation??0,retryCount:overrides2.retryCount??existing?.retryCount??0,lastOutcome:overrides2.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides2.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides2.updatedAt??existing?.updatedAt??""})}function advanceTaskState(session,taskId,newState2,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState2}`);if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState2),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState2==="complete")session.stageBCompletion?.delete(taskId),clearStageBRouteEvidence(session,taskId),clearStageBRouteRequired(session,taskId),completeModifiedFilesForTask(session,taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState2,current)}function canAdvanceTaskState(session,taskId,newState2,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)return!1;if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState2,_directory2,options,councilConfig){if(newState2==="coder_delegated"||newState2==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState2} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState2,options,councilConfig)}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function reserveStageBRouteEvidence(session,taskId,evidence){if(!isValidTaskId2(taskId))return null;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;let entries=session.stageBRouteEvidence.get(taskId)??[],dispatchIdentity=(entry)=>{if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")},incomingDispatchIdentity=dispatchIdentity(evidence),existingIndex=entries.findIndex((entry)=>entry.role===evidence.role&&(incomingDispatchIdentity!==null&&dispatchIdentity(entry)===incomingDispatchIdentity||incomingDispatchIdentity===null&&dispatchIdentity(entry)===null&&entry.identity===evidence.identity));if(existingIndex>=0){let previousEntry=entries[existingIndex],reservedEntry2={...evidence};return entries[existingIndex]=reservedEntry2,session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry2);if(reservedIndex<0)return;entries[reservedIndex]=previousEntry}}if(entries.length>=32)return null;let reservedEntry={...evidence};return entries.push(reservedEntry),session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry);if(reservedIndex<0)return;if(entries.splice(reservedIndex,1),entries.length===0)session.stageBRouteEvidence?.delete(taskId)}}function recordStageBRouteEvidence(session,taskId,evidence){return reserveStageBRouteEvidence(session,taskId,evidence)!==null}function getStageBRouteEvidence(session,taskId){return(session.stageBRouteEvidence?.get(taskId)??[]).map((entry)=>({...entry}))}function clearStageBRouteEvidence(session,taskId){session.stageBRouteEvidence?.delete(taskId)}function markStageBRouteRequired(session,taskId){if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;session.stageBRouteRequiredTasks.add(taskId)}function isStageBRouteRequired(session,taskId){return session.stageBRouteRequiredTasks?.has(taskId)===!0}function clearStageBRouteRequired(session,taskId){session.stageBRouteRequiredTasks?.delete(taskId)}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence){let snapshot=getTaskWorkflowSnapshot(evidence);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path100.join(directory,".swarm","plan.json"),content=await fs62.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path100.join(directory,".swarm","evidence"),entries=await fs62.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path100.join(evidenceDir,entry.name),content=await fs62.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory,options){let projectKey=hydrationProjectKey(directory),buildAuthority=captureCurrentHydrationAuthority(projectKey),planTaskStates=new Map,plan=options&&Object.hasOwn(options,"planOverride")?options.planOverride:await readPlanFromDisk(directory),cachePlan=plan??null;if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory),councilConfig;try{councilConfig=loadPluginConfig(directory).council}catch{councilConfig=void 0}if(options?.shouldCommit&&!options.shouldCommit()||!isHydrationAuthorityCurrent(buildAuthority))return{committed:!1,reason:"superseded"};return setRehydrationCache(projectKey,{planTaskStates,evidenceMap,taskIdentityContext:{plan:cachePlan,councilConfig}},buildAuthority)?{committed:!0}:{committed:!1,reason:"superseded"}}function applyRehydrationCache(session,projectKey){let resolvedKey=projectKey??session.owningProjectKey;if(!resolvedKey)return;let cache2=getRehydrationCache(resolvedKey);if(!cache2)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap,taskIdentityContext}=cache2;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedWorkflow=evidenceToWorkflowState(evidence);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){let council=evidence.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let rawIdentityDigest=council.identity_digest;if(typeof rawIdentityDigest!=="string"||!/^[a-f0-9]{64}$/.test(rawIdentityDigest)){session.taskCouncilApproved.delete(taskId);continue}let expectedIdentity=computeCouncilReviewIdentity({level:"task",scope:{kind:"task",taskId},plan:taskIdentityContext.plan,config:taskIdentityContext.councilConfig});if(rawIdentityDigest!==expectedIdentity.identityDigest){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);continue}let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session,shouldCommit){let cacheBuild=shouldCommit?await _internals86.buildRehydrationCache(directory,{shouldCommit}):await _internals86.buildRehydrationCache(directory);if(cacheBuild&&!cacheBuild.committed)return;if(shouldCommit&&!shouldCommit())return;_internals86.applyRehydrationCache(session,hydrationProjectKey(directory))}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map3=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map3.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map3.has(sessionID))map3.delete(sessionID);map3.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map3,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map3.has(sessionID))map3.delete(sessionID);map3.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map3,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached3=swarmState.liveContextWindows.get(sessionID);if(!cached3)return;if(identity&&!liveContextIdentityMatches(cached3,identity))return;return cached3.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached3=swarmState.liveContextWindows.get(sessionID);if(!cached3)return;return{modelID:cached3.modelID,providerID:cached3.providerID}}function evictOldestLiveContextWindow(map3,sessionID){if(map3.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map3=swarmState.lastBudgetBySession;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,{pct,tokens}),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function setFinalPromptPressure(sessionID,snapshot){let map3=swarmState.finalPromptPressureBySession;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,snapshot),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function getFinalPromptPressure(sessionID){if(!sessionID)return;return swarmState.finalPromptPressureBySession.get(sessionID)}function setFinalAccountingWarningBand(sessionID,band){let map3=swarmState.finalAccountingWarningBandsBySession,entry=map3.get(sessionID)??{warn:!1,critical:!1};if(map3.has(sessionID))map3.delete(sessionID);if(band==="critical")entry.critical=!0;else entry.warn=!0;if(map3.set(sessionID,entry),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function getFinalAccountingWarningBand(sessionID,band){if(!sessionID)return!1;let entry=swarmState.finalAccountingWarningBandsBySession.get(sessionID);if(!entry)return!1;return band==="critical"?entry.critical:entry.warn}function clearFinalAccountingWarningBands(){swarmState.finalAccountingWarningBandsBySession.clear()}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function getDisplayFinalPromptPressure(){let best=null;for(let entry of swarmState.finalPromptPressureBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function setCriticalShownIds(sessionID,value){let map3=swarmState.currentCriticalShownIds;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,value),map3.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map3=swarmState.gateDenialCounts,existing=map3.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,{count,directiveKey}),map3.size>MAX_TRACKED_GATE_DENIALS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.delete(sessionID)}function addKnowledgeAckDedup(key2){let set3=swarmState.knowledgeAckDedup;if(set3.has(key2))return;if(set3.add(key2),set3.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set3.values().next().value;if(oldest!==void 0)set3.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map3=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record3 of records){if(record3.sessionID!==sessionID)continue;let key2=`${record3.repoFullName}::${record3.prNumber}`;map3.set(key2,{prNumber:record3.prNumber,repoFullName:record3.repoFullName,prUrl:record3.prUrl,lastKnownStatus:record3.mergeableState??"unknown",lastPollTime:record3.lastCheckedAt,errorCount:record3.errorCount,isWatching:record3.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map3}var _councilDisagreementWarned,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals86;var init_state2=__esm(()=>{init_constants();init_loader();init_plan_schema();init_schema();init_council_review_identity();init_qa_gate_profile();init_qa_gate_session_override();init_action_circuit();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_task_model_routing();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_injection_budget();init_hydration_ownership();init_session_start_store();init_snapshot_store();init_worktree_link_suggestion();init_telemetry();init_logger();init_path();_councilDisagreementWarned=new Set,LINEAR_STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"];_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,finalPromptPressureBySession:new Map,finalAccountingWarningBandsBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals86={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,loadPluginConfigWithMeta,resolveInitialTurboMode,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,rehydratePrSubscriptions,isCouncilGateActive,defaultRunContext}});async function boundedSessionCall(call,timeoutMs,timeoutLabel,failureLabel,sessionId){let timer;try{await Promise.race([call(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(`${timeoutLabel} after ${timeoutMs}ms`)),Math.max(1,timeoutMs))})])}catch(error93){_internals87.log(`${failureLabel} for ephemeral session`,{sessionId,error:error93 instanceof Error?error93.message:String(error93)})}finally{if(timer)clearTimeout(timer)}}async function boundedAbortEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS){if(typeof session.abort!=="function")return;await _internals87.boundedSessionCall(()=>session.abort({path:{id:sessionId}}),timeoutMs,"ephemeral session abort timed out","ephemeral session abort failed",sessionId)}async function boundedDeleteEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS){await _internals87.boundedSessionCall(()=>session.delete({path:{id:sessionId}}),timeoutMs,"ephemeral session delete timed out","ephemeral session delete failed",sessionId)}async function teardownEphemeralSession(session,sessionId,options={}){let abortTimeoutMs=options.abortTimeoutMs??DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS,deleteTimeoutMs=options.deleteTimeoutMs??DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS;if(!(options.skipAbort??!1))await _internals87.boundedAbort(session,sessionId,abortTimeoutMs);await _internals87.boundedDelete(session,sessionId,deleteTimeoutMs)}async function sessionExists(session,sessionId,verifyTimeoutMs){if(typeof session.get!=="function")return!0;try{let body=(await withTimeout(session.get({path:{id:sessionId}}),verifyTimeoutMs,Error(`ephemeral session verify timed out after ${verifyTimeoutMs}ms`)))?.data;if(body===void 0||body===null)return!1;return!0}catch{return!1}}async function teardownEphemeralSessionVerified(session,sessionId,options={}){let verifyTimeoutMs=options.verifyTimeoutMs??DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS,attempts=Math.min(6,Math.max(2,options.maxDeleteAttempts??DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS));if(typeof session.get!=="function")return await teardownEphemeralSession(session,sessionId,options),{ok:!1,sessionId,attempts:1,kind:"ephemeral-session-teardown-unverified",reason:"get-unavailable"};let deleteAttempts=0;for(;;){if(await teardownEphemeralSession(session,sessionId,{...options,skipAbort:deleteAttempts>0?!0:options.skipAbort}),deleteAttempts+=1,!await _internals87.sessionExists(session,sessionId,verifyTimeoutMs))return{ok:!0,sessionId,attempts:deleteAttempts};if(deleteAttempts>=attempts)return{ok:!1,sessionId,attempts:deleteAttempts,kind:"ephemeral-session-teardown-unverified",reason:"session-survived-bounded-retries"}}}var DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS=5000,DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS=3,_internals87;var init_ephemeral_session_teardown=__esm(()=>{init_logger();init_timeout();_internals87={boundedSessionCall,boundedAbort:boundedAbortEphemeralSession,boundedDelete:boundedDeleteEphemeralSession,sessionExists,log}});var init_worktree=__esm(()=>{init_core3();init_merge2()});function verifyReviewerScopeGenerationMergeBack(input){try{let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,now:input.now});if(!generation||generation.modifiedFiles.length===0)return;if(generation.status!=="collecting"&&generation.status!=="mergeback_pending")return;if(generation.status==="collecting"){if(!markReviewerScopeGenerationMergebackPending({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,at:input.now}))return}let session=ensureAgentSession(input.parentSessionID),deadlineAt=(input.now??Date.now())+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let file3 of generation.modifiedFiles){let stored=generation.modifiedFileFingerprints.find((entry)=>entry.file===file3);if(!stored){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`incomplete fingerprints: ${file3} has no stored capture`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification found no stored fingerprint for ${file3}. ACTION[architect]: re-dispatch the coder for this task`);return}let captured=captureReviewerScopeFileFingerprint(input.primaryDirectory,file3,{deadlineAt});if(captured.kind==="capture_failed"){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`capture ${captured.code} on ${captured.file}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout capture failed for ${captured.file} (${captured.code}). ACTION[architect]: verify the primary checkout, then re-dispatch the reviewer`);return}let capturedFingerprint=reviewerScopeCaptureToFingerprint(captured);if(!capturedFingerprint||!reviewerScopeFileFingerprintsEqual(stored,capturedFingerprint)){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`primary bytes differ from lane manifest on ${file3}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout bytes differ from the lane manifest on ${file3}; lane evidence retained. ACTION[architect]: resolve the merge conflict or re-dispatch the coder`);return}}let primaryIdentity=canonicalWorkspaceIdentity(input.primaryDirectory);settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!0,primaryWorkspaceIdentity:primaryIdentity??input.primaryDirectory,primaryDirectory:input.primaryDirectory,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_VERIFIED: task ${input.taskId}: primary checkout matches the lane manifest exactly; reviewer dispatch is enabled`)}catch(error93){try{let session=ensureAgentSession(input.parentSessionID);pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification errored (${String(error93).slice(0,200)}). ACTION[architect]: re-dispatch the reviewer to retry verification`),settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:"verification error",at:input.now}})}catch{}}}var init_reviewer_scope_mergeback=__esm(()=>{init_scope_binding();init_state2();init_reviewer_scope_file_fingerprint()});import{createHash as createHash45,randomBytes as randomBytes7}from"node:crypto";import*as fs63 from"node:fs";import*as path101 from"node:path";function nowMs2(input){return input??Date.now()}function sha2565(input){return createHash45("sha256").update(input).digest("hex")}function storePath4(directory){return path101.join(directory,STORE_RELATIVE_PATH)}function journalPath2(directory){return path101.join(directory,JOURNAL_RELATIVE_PATH)}function credentialPath(directory,authorityDigest){return path101.join(directory,CREDENTIAL_DIRECTORY,`${authorityDigest}.json`)}function readAuthorityLockRecord(lockPath){try{let parsed=JSON.parse(fs63.readFileSync(lockPath,"utf8"));if(typeof parsed?.nonce==="string"&&typeof parsed?.acquiredAt==="number"&&Number.isFinite(parsed.acquiredAt)&&typeof parsed?.pid==="number"&&Number.isInteger(parsed.pid))return{nonce:parsed.nonce,acquiredAt:parsed.acquiredAt,pid:parsed.pid}}catch{}return}function writeAuthorityLockRecord(lockPath,record3){try{return fs63.writeFileSync(lockPath,JSON.stringify(record3,null,2),{flag:"wx"}),!0}catch{return!1}}function isProcessAlive2(pid){if(!Number.isSafeInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch{return!1}}function acquireAuthorityLock(directory){let lockPath=path101.join(directory,AUTHORITY_LOCK_RELATIVE_PATH);fs63.mkdirSync(path101.dirname(lockPath),{recursive:!0});let nonce=randomBytes7(16).toString("hex"),acquiredAt=Date.now(),attempt=()=>writeAuthorityLockRecord(lockPath,{nonce,acquiredAt,pid:process.pid});if(!attempt())try{let observed=readAuthorityLockRecord(lockPath);if(!observed)return;if(Date.now()-fs63.statSync(lockPath).mtimeMs>AUTHORITY_LOCK_STALE_MS){if(isProcessAlive2(observed.pid))return;let reread=readAuthorityLockRecord(lockPath);if(reread&&reread.nonce===observed.nonce&&reread.acquiredAt===observed.acquiredAt&&reread.pid===observed.pid){if(fs63.unlinkSync(lockPath),!attempt())return}}}catch{return}let acquired=readAuthorityLockRecord(lockPath);if(!acquired||acquired.nonce!==nonce)return;let released=!1;return()=>{if(released)return;released=!0;try{if(readAuthorityLockRecord(lockPath)?.nonce===nonce)fs63.unlinkSync(lockPath)}catch{}}}function taskKey(parentSessionId,taskId){return`${parentSessionId}::${taskId}`}function stableStringify(value){if(Array.isArray(value))return`[${value.map((item)=>stableStringify(item)).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key2,item])=>`${JSON.stringify(key2)}:${stableStringify(item)}`).join(",")}}`;return JSON.stringify(value)}function digestAuthorityIdentity(input){return sha2565(stableStringify({originalCallID:input.originalCallID,parentSessionId:input.parentSessionId,taskId:input.taskId,reservationId:input.reservationId,generation:input.generation,canonicalBranch:input.canonicalBranch,canonicalPath:input.canonicalPath,laneBranch:input.laneBranch,lanePath:input.lanePath,expectedPrimaryHead:input.expectedPrimaryHead,sourceBaseOid:input.sourceBaseOid,sourceHeadOid:input.sourceHeadOid,targetHeadOid:input.targetHeadOid,strategy:input.strategy,declaredConflictFiles:input.declaredConflictFiles??[]}))}function nonEmpty(value){return typeof value==="string"&&value.length>0&&value.length<=4096}function isHex40(value){return typeof value==="string"&&HEX_40_RE.test(value)}function isOidArray(value){return Array.isArray(value)&&value.length<=4096&&value.every(isHex40)}function isSettlementEvidence(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return isOidArray(candidate.sourceCommitOrder)&&isOidArray(candidate.rewrittenCommitOrder)&&candidate.sourceCommitOrder.length===candidate.rewrittenCommitOrder.length}function isStrategy(value){return value==="merge"||value==="rebase"||value==="cherry-pick"}function isImmutableIdentity(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.originalCallID)&&nonEmpty(candidate.parentSessionId)&&nonEmpty(candidate.taskId)&&nonEmpty(candidate.reservationId)&&typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0&&nonEmpty(candidate.canonicalBranch)&&nonEmpty(candidate.canonicalPath)&&nonEmpty(candidate.laneBranch)&&nonEmpty(candidate.lanePath)&&isHex40(candidate.expectedPrimaryHead)&&isHex40(candidate.sourceBaseOid)&&isHex40(candidate.sourceHeadOid)&&isHex40(candidate.targetHeadOid)&&isStrategy(candidate.strategy)&&(candidate.declaredConflictFiles===void 0||Array.isArray(candidate.declaredConflictFiles)&&candidate.declaredConflictFiles.every((item)=>nonEmpty(item)))&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function isClaimState(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.claimedAt==="number"&&Number.isFinite(candidate.claimedAt)&&candidate.claimedAt>=0}function isAuthority(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,claimCursor=candidate.claimCursor&&typeof candidate.claimCursor==="object"?candidate.claimCursor:void 0,validStatus=candidate.status==="preserved"||candidate.status==="claimed"||candidate.status==="released"||candidate.status==="finalized";return candidate.schemaVersion===2&&nonEmpty(candidate.authorityDigest)&&isImmutableIdentity(candidate.immutable)&&validStatus&&(candidate.claim===void 0||isClaimState(candidate.claim))&&(claimCursor===void 0||typeof claimCursor.lastClaimRevision==="number"&&Number.isInteger(claimCursor.lastClaimRevision)&&claimCursor.lastClaimRevision>0&&typeof claimCursor.lastAttempt==="number"&&Number.isInteger(claimCursor.lastAttempt)&&claimCursor.lastAttempt>0)&&(candidate.status!=="claimed"||candidate.claim!==void 0)&&(candidate.finalizedAt===void 0||typeof candidate.finalizedAt==="number"&&Number.isFinite(candidate.finalizedAt)&&candidate.finalizedAt>=0)&&(candidate.settlement===void 0||isSettlementEvidence(candidate.settlement))}function isJournalEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,validState=candidate.state==="PREPARED"||candidate.state==="COMMITTED"||candidate.state==="CLAIM_RENEWED"||candidate.state==="ABORTED"||candidate.state==="RELEASED"||candidate.state==="FINALIZED";return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&validState&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&(candidate.childSessionId===void 0||nonEmpty(candidate.childSessionId))&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.preparedAt==="number"&&Number.isFinite(candidate.preparedAt)&&candidate.preparedAt>=0&&(candidate.credentialInstalledAt===void 0||typeof candidate.credentialInstalledAt==="number"&&Number.isFinite(candidate.credentialInstalledAt)&&candidate.credentialInstalledAt>=0)&&(candidate.committedAt===void 0||typeof candidate.committedAt==="number"&&Number.isFinite(candidate.committedAt)&&candidate.committedAt>=0)&&(candidate.abortedAt===void 0||typeof candidate.abortedAt==="number"&&Number.isFinite(candidate.abortedAt)&&candidate.abortedAt>=0)&&(candidate.reason===void 0||nonEmpty(candidate.reason))}function isCredential(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&nonEmpty(candidate.rawToken)&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function rebuildIndex(authorities){let bySessionTask={};for(let authority of[...authorities].sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)){let key2=taskKey(authority.immutable.parentSessionId,authority.immutable.taskId),digests=bySessionTask[key2]??[];digests.push(authority.authorityDigest),bySessionTask[key2]=digests}return{bySessionTask}}function emptyJournal(){return{schemaVersion:1,entries:[]}}function readBoundedJsonFile2(filePath,maxBytes){try{if(fs63.statSync(filePath).size>maxBytes)return{ok:!1,reason:`${path101.basename(filePath)} exceeds the ${maxBytes}-byte safety bound`};let raw=fs63.readFileSync(filePath,"utf8");if(Buffer.byteLength(raw,"utf8")>maxBytes)return{ok:!1,reason:`${path101.basename(filePath)} changed beyond the ${maxBytes}-byte safety bound`};return{ok:!0,value:JSON.parse(raw)}}catch(error93){if(error93.code==="ENOENT")return{ok:!0,value:void 0};return{ok:!1,reason:`${path101.basename(filePath)} is unreadable or malformed: ${error93 instanceof Error?error93.message:String(error93)}`}}}function loadStoreStrict(directory){let loaded=readBoundedJsonFile2(storePath4(directory),MAX_STORE_BYTES);if(!loaded.ok)return{status:"uncertain",reason:loaded.reason};if(loaded.value===void 0)return{status:"ok",authorities:[]};let parsed=loaded.value;if(parsed.schemaVersion===1)return{status:"unsupported-legacy",reason:"worktree recovery v1 records are unsupported for claim mutation"};if(parsed.schemaVersion!==2)return{status:"uncertain",reason:`unknown worktree recovery schema version: ${String(parsed.schemaVersion)}`};if(!Array.isArray(parsed.authorities))return{status:"uncertain",reason:"worktree recovery store does not contain an authorities array"};if(parsed.authorities.length>MAX_STORE_AUTHORITIES)return{status:"uncertain",reason:`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`};for(let authority of parsed.authorities)if(!isAuthority(authority))return{status:"uncertain",reason:"worktree recovery store contains an invalid authority record"};return{status:"ok",authorities:[...parsed.authorities]}}function loadStoreWritable(directory){let scanned=loadStoreStrict(directory);if(scanned.status==="unsupported-legacy")return{ok:!1,code:"unsupported_legacy",reason:scanned.reason};if(scanned.status==="uncertain")return{ok:!1,code:"uncertain_store",reason:scanned.reason};return{schemaVersion:2,authorities:scanned.authorities,index:rebuildIndex(scanned.authorities)}}function loadJournal(directory){let loaded=readBoundedJsonFile2(journalPath2(directory),MAX_JOURNAL_BYTES2);if(!loaded.ok||loaded.value===void 0)return emptyJournal();let parsed=loaded.value;if(parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return emptyJournal();let entries=[];for(let entry of parsed.entries)if(isJournalEntry(entry))entries.push(entry);return{schemaVersion:1,entries:entries.slice(-MAX_JOURNAL_ENTRIES)}}function updateStore(store,authorities){return store.authorities=authorities,store.index=rebuildIndex(authorities),store}function currentClaimMatches(authority,request){if(!authority.claim)return!1;return authority.claim.claimantCallID===request.claimantCallID&&authority.claim.claimRevision===request.claimRevision&&authority.claim.claimTokenDigest===sha2565(request.rawToken)}function latestJournalEntriesByAuthority(journal){let latest=new Map;for(let entry of journal.entries)latest.set(entry.authorityDigest,entry);return[...latest.values()]}function recordJournalEntry(directory,entry){let journal=loadJournal(directory);if(journal.entries.push(entry),journal.entries.length>MAX_JOURNAL_ENTRIES)journal.entries=journal.entries.slice(-MAX_JOURNAL_ENTRIES);return _internals88.writeClaimJournal(journalPath2(directory),journal),journal}function writeCredential(directory,credential){let targetPath=credentialPath(directory,credential.authorityDigest);_internals88.writeCredentialFile(targetPath,credential);try{fs63.chmodSync(targetPath,384)}catch{}return targetPath}function readCredential(directory,authorityDigest){let loaded=readBoundedJsonFile2(credentialPath(directory,authorityDigest),MAX_CREDENTIAL_BYTES);if(!loaded.ok||loaded.value===void 0)return;return isCredential(loaded.value)?loaded.value:void 0}function removeCredentialIfMatch(directory,entry){let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID)try{fs63.unlinkSync(credentialPath(directory,entry.authorityDigest))}catch{}}function baseMutationFailure(code,reason){return{ok:!1,code,reason}}function publishWorktreeRecoveryAuthorityUnlocked(directory,input){let store=loadStoreWritable(directory);if("ok"in store)return store;let immutable={...input,createdAt:nowMs2()};if(!isImmutableIdentity(immutable))return baseMutationFailure("uncertain_store","invalid immutable recovery authority input");let authorityDigest=digestAuthorityIdentity(input),existing=store.authorities.find((authority2)=>authority2.authorityDigest===authorityDigest);if(existing)return{ok:!0,authority:existing};let authority={schemaVersion:2,authorityDigest,immutable,status:"preserved"},nextAuthorities=[...store.authorities,authority];if(nextAuthorities.length>MAX_STORE_AUTHORITIES)return baseMutationFailure("uncertain_store",`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`);return _internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"publish"),{ok:!0,authority}}function publishWorktreeRecoveryAuthority(directory,input){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return publishWorktreeRecoveryAuthorityUnlocked(directory,input)}finally{release()}}function scanWorktreeRecoveryAuthoritiesForRecovery(directory){return loadStoreStrict(directory)}function lookupWorktreeRecoveryAuthoritiesByTask(directory,query){let scanned=loadStoreStrict(directory);if(scanned.status!=="ok")return scanned;return{status:"ok",authorities:scanned.authorities.filter((authority)=>authority.immutable.parentSessionId===query.parentSessionId&&authority.immutable.taskId===query.taskId).sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)}}async function claimWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let authorityIndex=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(authorityIndex===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[authorityIndex];if(authority.status==="finalized")return baseMutationFailure("finalized","finalized worktree recovery authority cannot be claimed again");let currentTime=nowMs2(request.now),previousClaim=authority.claim;if(previousClaim&&previousClaim.leaseExpiresAt>currentTime)return baseMutationFailure("busy","worktree recovery authority is already claimed");if(previousClaim&&previousClaim.leaseExpiresAt<=currentTime){if(!request.revalidateExpiredClaim)return baseMutationFailure("revalidation_required","expired worktree recovery claims require full revalidation before transfer");let verdict=await request.revalidateExpiredClaim({authority,previousClaim});if(!verdict.ok)return baseMutationFailure("revalidation_failed",verdict.reason)}let nextAttempt=(previousClaim?.attempt??authority.claimCursor?.lastAttempt??0)+1,maxAttempts=request.maxAttempts??DEFAULT_MAX_ATTEMPTS;if(nextAttempt>maxAttempts)return baseMutationFailure("retry_cap_exceeded",`worktree recovery claim attempt ${nextAttempt} exceeds the ${maxAttempts}-attempt safety cap`);let nextRevision=(previousClaim?.claimRevision??authority.claimCursor?.lastClaimRevision??0)+1,rawToken=_internals88.generateRawToken(),claimTokenDigest=sha2565(rawToken);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let childSessionId=await request.createChildSession(),refreshedStore=loadStoreWritable(directory);if("ok"in refreshedStore)throw Error(`worktree recovery authority could not be revalidated: ${refreshedStore.reason}`);let refreshedAuthority=refreshedStore.authorities.find((candidate)=>candidate.authorityDigest===request.authorityDigest);if(!refreshedAuthority||stableStringify({status:refreshedAuthority.status,claim:refreshedAuthority.claim,claimCursor:refreshedAuthority.claimCursor,immutable:refreshedAuthority.immutable})!==stableStringify({status:authority.status,claim:authority.claim,claimCursor:authority.claimCursor,immutable:authority.immutable}))throw recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"ABORTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,abortedAt:nowMs2(),reason:"authority changed while child session was being created"}),Error("worktree recovery authority changed while child session was being created");recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let credential={schemaVersion:1,authorityDigest:authority.authorityDigest,claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,rawToken,leaseExpiresAt:currentTime+request.leaseMs,createdAt:currentTime},writtenCredentialPath=writeCredential(directory,credential);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime});let claimedAuthority={...authority,status:"claimed",claim:{claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,claimedAt:currentTime},claimCursor:{lastClaimRevision:nextRevision,lastAttempt:nextAttempt}},nextAuthorities=[...store.authorities];return nextAuthorities[authorityIndex]=claimedAuthority,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-commit"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"COMMITTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime,committedAt:currentTime}),{ok:!0,authority:claimedAuthority,rawToken,credentialPath:writtenCredentialPath}}async function claimWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return await claimWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function renewWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let renewed={...authority,claim:{...authority.claim,leaseExpiresAt:nowMs2(request.now)+request.leaseMs}},nextAuthorities=[...store.authorities];return nextAuthorities[index]=renewed,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-renew"),writeCredential(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,rawToken:request.rawToken,leaseExpiresAt:renewed.claim.leaseExpiresAt,createdAt:renewed.claim.claimedAt}),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,state:"CLAIM_RENEWED",claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,attempt:renewed.claim.attempt,leaseExpiresAt:renewed.claim.leaseExpiresAt,claimTokenDigest:renewed.claim.claimTokenDigest,preparedAt:renewed.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim lease renewed"}),{ok:!0,authority:renewed}}function renewWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return renewWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function releaseWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let released={...authority,status:"preserved",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor},nextAuthorities=[...store.authorities];return nextAuthorities[index]=released,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-release"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"RELEASED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim released after preserved settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:released}}function releaseWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return releaseWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function finalizeWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let finalized={...authority,status:"finalized",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor,finalizedAt:nowMs2(request.now),settlement:request.settlement},nextAuthorities=[...store.authorities];return nextAuthorities[index]=finalized,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-finalize"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"FINALIZED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim finalized after landed settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:finalized}}function finalizeWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return finalizeWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function replayWorktreeRecoveryClaimJournalUnlocked(directory,options){let outcomes=[],storeScan=loadStoreStrict(directory),authorities=new Map((storeScan.status==="ok"?storeScan.authorities:[]).map((authority)=>[authority.authorityDigest,authority]));for(let entry of latestJournalEntriesByAuthority(loadJournal(directory))){if(entry.state==="ABORTED"||entry.state==="CLAIM_RENEWED"||entry.state==="RELEASED"||entry.state==="FINALIZED"){outcomes.push({authorityDigest:entry.authorityDigest,outcome:"noop"});continue}if(entry.state==="COMMITTED"){let current2=authorities.get(entry.authorityDigest);if(current2&&!current2.claim&¤t2.claimCursor?.lastClaimRevision===entry.claimRevision&&(current2.status==="preserved"||current2.status==="finalized")){recordJournalEntry(directory,{...entry,state:current2.status==="finalized"?"FINALIZED":"RELEASED",reason:"repaired terminal claim journal after interrupted settlement"}),removeCredentialIfMatch(directory,entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"repaired_terminal_claim"});continue}if(current2?.claim&¤t2.claim.claimRevision===entry.claimRevision&¤t2.claim.claimTokenDigest===entry.claimTokenDigest){let credential2=readCredential(directory,entry.authorityDigest),released=credential2?releaseWorktreeRecoveryClaimUnlocked(directory,{authorityDigest:entry.authorityDigest,claimantCallID:entry.claimantCallID,claimRevision:entry.claimRevision,rawToken:credential2.rawToken}):void 0;outcomes.push({authorityDigest:entry.authorityDigest,outcome:released?.ok?"released_orphaned_committed_claim":"uncertain_committed_without_authority"})}else outcomes.push({authorityDigest:entry.authorityDigest,outcome:"uncertain_committed_without_authority"});continue}let current=authorities.get(entry.authorityDigest);if(current?.claim&¤t.claim.claimRevision===entry.claimRevision&¤t.claim.claimTokenDigest===entry.claimTokenDigest){recordJournalEntry(directory,{...entry,state:"COMMITTED",committedAt:nowMs2()}),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"committed_claim_stable"});continue}let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID){removeCredentialIfMatch(directory,entry),recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"removed uncommitted credential during replay"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"removed_uncommitted_credential"});continue}recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"prepared claim never reached credential install or commit"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"aborted_prepared_claim"})}return outcomes}function replayWorktreeRecoveryClaimJournal(directory,options){let release=acquireAuthorityLock(directory);if(!release)throw Error("worktree recovery authority store is locked");try{return replayWorktreeRecoveryClaimJournalUnlocked(directory,options)}finally{release()}}var STORE_RELATIVE_PATH,JOURNAL_RELATIVE_PATH,CREDENTIAL_DIRECTORY,AUTHORITY_LOCK_RELATIVE_PATH,AUTHORITY_LOCK_STALE_MS=600000,MAX_STORE_BYTES=2097152,MAX_STORE_AUTHORITIES=512,MAX_JOURNAL_BYTES2=2097152,MAX_JOURNAL_ENTRIES=512,MAX_CREDENTIAL_BYTES=16384,DEFAULT_MAX_ATTEMPTS=8,HEX_40_RE,_internals88;var init_worktree_recovery_authority=__esm(()=>{init_atomic_write();STORE_RELATIVE_PATH=path101.join(".swarm","worktree-merge-recovery-v2.json"),JOURNAL_RELATIVE_PATH=path101.join(".swarm","worktree-merge-recovery-v2-journal.json"),CREDENTIAL_DIRECTORY=path101.join(".swarm","worktree-recovery-claims"),AUTHORITY_LOCK_RELATIVE_PATH=path101.join(".swarm","locks","worktree-recovery-authority.lock"),HEX_40_RE=/^[0-9a-f]{40}$/i;_internals88={generateRawToken:()=>randomBytes7(32).toString("hex"),writeRecoveryStore:(targetPath,store,_phase)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(store,null,2))},writeClaimJournal:(targetPath,journal)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(journal,null,2))},writeCredentialFile:(targetPath,credential)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(credential,null,2),{mode:384})},getRecoveryStorePath:storePath4,getClaimJournalPath:journalPath2,getCredentialPath:credentialPath,acquireAuthorityLock,readClaimJournal(directory){return loadJournal(directory)},resetForTest(){}}});import*as fs64 from"node:fs";import*as path102 from"node:path";function decodeTagPart(value){if(!value||!/^[A-Za-z0-9_-]+$/.test(value))return null;let decoded=Buffer.from(value,"base64url").toString("utf8");return decoded&&Buffer.from(decoded,"utf8").toString("base64url")===value?decoded:null}async function scanBackgroundWorktreeOwnershipTagsForRecovery(directory){try{fs64.statSync(path102.join(directory,".git"))}catch(error93){if(error93.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`Git metadata could not be inspected: ${error93 instanceof Error?error93.message:String(error93)}`}}let proc;try{proc=bunSpawn([resolveGitExecutable(),"-C",directory,"for-each-ref",`--count=${MAX_OWNERSHIP_TAGS+1}`,"--format=%(refname:strip=2)%00%(objectname)","refs/tags/swarm-preserved-owner/"],{stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:OWNERSHIP_TAG_SCAN_TIMEOUT_MS});let exitCode=await proc.exited;if(exitCode!==0)return{status:"uncertain",reason:`ownership tag scan exited ${exitCode}`};let lines=(await proc.stdout.text()).split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);if(lines.length>MAX_OWNERSHIP_TAGS)return{status:"uncertain",reason:`ownership tag scan exceeded the ${MAX_OWNERSHIP_TAGS}-tag safety bound`};let owners=[];for(let line of lines){let[tag,ref,...extra]=line.split("\x00"),segments=tag?.split("/")??[],sessionId=decodeTagPart(segments[1]??""),laneId=decodeTagPart(segments[2]??""),callDigest=segments[3];if(extra.length>0||segments.length!==4||segments[0]!=="swarm-preserved-owner"||!sessionId||!laneId||!callDigest||!/^[0-9a-f]{12}$/.test(callDigest)||!ref||!/^[0-9a-f]{40,64}$/i.test(ref))return{status:"uncertain",reason:`malformed background ownership tag entry "${tag??""}"`};owners.push({sessionId,laneId,callDigest,ref})}return{status:"ok",owners}}catch(error93){return{status:"uncertain",reason:`ownership tag scan failed: ${error93 instanceof Error?error93.message:String(error93)}`}}finally{try{proc?.kill()}catch{}}}var OWNERSHIP_TAG_SCAN_TIMEOUT_MS=2000,MAX_OWNERSHIP_TAGS=512;var init_worktree_ownership_tag=__esm(()=>{init_bun_compat();init_git_executable()});var exports_worktree_collision_ownership={};__export(exports_worktree_collision_ownership,{inspectStandardWorktreeCollisionOwnership:()=>inspectStandardWorktreeCollisionOwnership,_internals:()=>_internals89});import*as fs65 from"node:fs";function descriptorCoordinateMatch(descriptor,identity){let branchMatches=descriptor.branchName===identity.branchName,pathMatches2=canonicalRootKeyFresh(descriptor.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)return"none";if(!branchMatches||!pathMatches2||descriptor.parentSessionId!==identity.parentSessionId||descriptor.taskId!==identity.taskId)return"uncertain";return"exact"}function isProvenSettled(record3){let settlement=record3.coderSettlement;return settlement?.state==="settled"&&settlement.outcome?.kind==="standard-worktree"&&(settlement.outcome.result==="merged"||settlement.outcome.result==="unchanged")}function classifyRecord(record3,identity,ownerKind){if(!record3.worktree)return null;let coordinates=descriptorCoordinateMatch(record3.worktree,identity);if(coordinates==="none")return null;if(coordinates==="uncertain")return{status:"uncertain",reason:`${ownerKind} background owner has conflicting identity for branch "${identity.branchName}"`};if(isProvenSettled(record3))return null;let lifecycle=record3.coderSettlement?.state==="preserved"?"preserved":"active";return{status:"protected",ownerKind,lifecycle,reason:`${ownerKind} background owner ${record3.correlationId} is ${record3.status}`+(record3.coderSettlement?` with coder settlement ${record3.coderSettlement.state}`:" without a settled workspace outcome")}}async function inspectStandardWorktreeCollisionOwnership(identity){let provisioning=scanWorktreeProvisioningOwnersForRecovery(identity.directory);if(provisioning.status==="uncertain")return provisioning;let now=Date.now();for(let owner of provisioning.owners){if(!(owner.parentSessionId===identity.parentSessionId||owner.worktreeSessionId===identity.parentSessionId))continue;if(owner.schemaVersion===1||owner.taskId===identity.taskId){let leaseIsLive=now-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS;if(!leaseIsLive)try{_internals89.statSync(identity.worktreePath)}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} lane liveness is unreadable: ${error93 instanceof Error?error93.message:String(error93)}`};if(!_internals89.removeWorktreeProvisioningOwner(identity.directory,owner.callID,owner.schemaVersion===3?{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}:void 0))return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} could not be removed`};continue}return{status:"protected",ownerKind:"provisioning",lifecycle:"active",reason:!leaseIsLive?`provisioning owner ${owner.callID} lease expired, but its exact lane path still exists`:owner.schemaVersion===1?`legacy provisioning owner ${owner.callID} cannot disprove ownership of this same-session lane`:`provisioning owner ${owner.callID} is active for task ${identity.taskId}`}}}let fallback=await scanDelegationFallbacksForRecovery(identity.directory);if(fallback.status==="uncertain")return fallback;for(let artifact of fallback.owners){let classified=classifyRecord(artifact.record,identity,"fallback");if(classified)return classified}let primary=scanDelegationsForRecovery(identity.directory);if(primary.status==="uncertain")return primary;for(let record3 of primary.owners){let classified=classifyRecord(record3,identity,"primary");if(classified)return classified}let tags=await scanBackgroundWorktreeOwnershipTagsForRecovery(identity.directory);if(tags.status==="uncertain")return tags;for(let owner of tags.owners)if(owner.sessionId===identity.parentSessionId&&owner.laneId===identity.taskId)return{status:"protected",ownerKind:"ownership-tag",lifecycle:"preserved",reason:`durable ownership tag ${owner.callDigest} preserves this same-session lane`};let mergeStatus=scanWorktreeMergeFailuresForRecovery(identity.directory);if(mergeStatus.status==="uncertain")return mergeStatus;for(let[,failure]of mergeStatus.failures){let branchMatches=failure.branch===identity.branchName,pathMatches2=typeof failure.worktreePath==="string"&&canonicalRootKeyFresh(failure.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)continue;if(!branchMatches||!pathMatches2)return{status:"uncertain",reason:`merge-status owner has conflicting identity for branch "${identity.branchName}"`};return{status:"protected",ownerKind:"merge-status",lifecycle:"preserved",reason:`merge-status records ${failure.outcome} at stage ${failure.stage}`}}return{status:"unowned"}}var _internals89;var init_worktree_collision_ownership=__esm(()=>{init_pending_delegations();init_canonical_root();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();_internals89={statSync:fs65.statSync,removeWorktreeProvisioningOwner}});var exports_worktree_isolation={};__export(exports_worktree_isolation,{standardWorktreeSerializationSessions:()=>standardWorktreeSerializationSessions,standardWorktreeByCallID:()=>standardWorktreeByCallID,sanitizeWorktreeTaskId:()=>sanitizeWorktreeTaskId,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resetStandardWorktreeIsolationState:()=>resetStandardWorktreeIsolationState,readLaneEnvFileFromDisk:()=>readLaneEnvFileFromDisk,preserveDirtyWorktreeForCallId:()=>preserveDirtyWorktreeForCallId,preserveDirtyWorktreeAtPath:()=>preserveDirtyWorktreeAtPath,preserveBackgroundWorktreeOwnershipForCallId:()=>preserveBackgroundWorktreeOwnershipForCallId,precreateStandardWorktreeSession:()=>precreateStandardWorktreeSession,preProvisionCollisionCheck:()=>preProvisionCollisionCheck,parseLeanLaneIndex:()=>parseLeanLaneIndex,isLaneOwnedByCurrentSession:()=>isLaneOwnedByCurrentSession,getStandardWorktreeDegradationReason:()=>getStandardWorktreeDegradationReason,finishStandardWorktreeDispatch:()=>finishStandardWorktreeDispatch,computeLaneRuntimeProfile:()=>computeLaneRuntimeProfile,cleanupStandardWorktreeForCallId:()=>cleanupStandardWorktreeForCallId,checkStandardWorktreeSerializationRelease:()=>checkStandardWorktreeSerializationRelease,awaitingMergeByCallID:()=>awaitingMergeByCallID,abortStandardWorktreeDispatch:()=>abortStandardWorktreeDispatch,_internals:()=>_internals83,MAX_TRACKED_STANDARD_WORKTREE_CALLS:()=>MAX_TRACKED_STANDARD_WORKTREE_CALLS});import{createHash as createHash46}from"node:crypto";import*as fs66 from"node:fs/promises";import*as path103 from"node:path";function parseLeanLaneIndex(laneId){let match=/^lane-(\d+)$/.exec(laneId);if(match){let n=parseInt(match[1],10);return Number.isNaN(n)?0:n-1}return 0}function computeLaneRuntimeProfile(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects)){let laneSuffix=path103.join(basePath,`lane-${laneIndex}`);envOverrides[envName]=laneSuffix}return{laneIndex,worktreePath,envOverrides}}function allocateStandardLaneIndex(parentSessionID){let current=standardWorktreeLaneIndexBySession.get(parentSessionID)??0;return standardWorktreeLaneIndexBySession.set(parentSessionID,current+1),current}async function createSessionWithinBudget(promise3,label,onLateResolve,timeoutMs=_internals83.worktreeSessionCreateTimeoutMs){let settled=new Promise((resolveState)=>{promise3.then((result)=>resolveState({status:"fulfilled",result}),()=>resolveState({status:"rejected"}))});try{return await withTimeout(promise3,timeoutMs,Error(`${label} deadline expired after ${timeoutMs}ms (worktree.session_create_timeout_ms)`))}catch(error93){let teardown=settled.then(async(state2)=>{if(state2.status==="fulfilled")await onLateResolve?.(state2.result)},()=>{}).catch((teardownError)=>{log(`[worktree-isolation] ${label} late-settle teardown failed: ${teardownError instanceof Error?teardownError.message:String(teardownError)}`)});throw await withTimeout(teardown,_internals83.worktreeSessionCreateSettleGraceMs,Error(`${label} settle grace expired`)).catch(()=>{}),error93}}function resolveSessionCreateTimeoutMs(args2){return args2.config?.worktree?.session_create_timeout_ms??_internals83.worktreeSessionCreateTimeoutMs}async function handleStrandedLane(lane){recordDeadLaneReclaim(lane.directory,{lanePath:lane.lanePath,branchName:lane.branchName,parentSessionId:lane.parentSessionID,taskId:lane.taskId,reason:lane.reason});let session=ensureAgentSession(lane.parentSessionID);pushAdvisory(session,`WORKTREE_LANE_STRANDED: lane ${lane.lanePath} could not be removed (${lane.reason}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`)}function rememberStandardWorktreeDispatch(dispatch){standardWorktreeByCallID.set(dispatch.callID,dispatch)}function resolveRecoveryTaskId(input){return input.planTaskId??input.taskId}function toRecoveryStrategy(strategy){return strategy}function hasStandardWorktreeDispatchCapacity(){return standardWorktreeByCallID.size<MAX_TRACKED_STANDARD_WORKTREE_CALLS}function hasInFlightStandardWorktreeDispatch(parentSessionID){for(let dispatch of standardWorktreeByCallID.values())if(dispatch.parentSessionID===parentSessionID)return!0;for(let record3 of awaitingMergeByCallID.values())if(record3.parentSessionID===parentSessionID)return!0;return!1}function handleStandardWorktreeFailure(parentSessionID,policy,message){if(policy==="required")throw new StandardWorktreeLifecycleError(message);if(hasInFlightStandardWorktreeDispatch(parentSessionID))throw new StandardWorktreeLifecycleError(`STANDARD_WORKTREE_ISOLATION_UNSAFE: ${message} Sibling coder task(s) are isolated in worktrees for this session, so dispatching this coder un-isolated in the main tree would risk a merge-back collision. Wait for in-flight coder task(s) to be reviewed and merged, then retry.`);serializeStandardWorktreeDispatches(parentSessionID,message)}function hardStopStandardWorktreeLifecycle(parentSessionID,message){let session=ensureAgentSession(parentSessionID);throw pushAdvisory(session,message),new StandardWorktreeLifecycleError(message)}function serializeStandardWorktreeDispatches(sessionID,message){if(!rememberStandardWorktreeSerializationSession(sessionID)){let session2=ensureAgentSession(sessionID);pushAdvisory(session2,`${message} Serialization tracking is at capacity (256 sessions active); continuing in normal parallel mode.`);return}standardWorktreeDegradationReasonBySession.set(sessionID,{reason:message,at:Date.now()});let session=ensureAgentSession(sessionID);session.maxConcurrencyOverride=1,pushAdvisory(session,`${message} Serializing standard coder dispatches for this session.`)}function getStandardWorktreeDegradationReason(sessionID){return standardWorktreeDegradationReasonBySession.get(sessionID)}function resetStandardWorktreeIsolationState(){standardWorktreeByCallID.clear(),standardWorktreeSerializationSessions.clear(),serializationStateBySessionID.clear(),standardWorktreeDegradationReasonBySession.clear(),awaitingMergeByCallID.clear(),standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession.clear()}function releaseStandardWorktreeSerialization(sessionID){if(!standardWorktreeSerializationSessions.has(sessionID))return!1;standardWorktreeSerializationSessions.delete(sessionID),serializationStateBySessionID.delete(sessionID),standardWorktreeDegradationReasonBySession.delete(sessionID);let session=ensureAgentSession(sessionID);return session.maxConcurrencyOverride=void 0,pushAdvisory(session,`WORKTREE_SERIALIZATION_RELEASED: ${sessionID} regains parallel dispatch eligibility (release-after-dispatches or TTL).`),!0}function checkStandardWorktreeSerializationRelease(sessionID,config3){let state2=serializationStateBySessionID.get(sessionID);if(!state2)return;let count=config3.serialization_release_after_dispatches??5,ttl=config3.serialization_release_after_ms??60000;if(state2.successfulDispatchesSince>=count){releaseStandardWorktreeSerialization(sessionID);return}if(Date.now()-state2.serializedAt>=ttl)releaseStandardWorktreeSerialization(sessionID)}function rememberStandardWorktreeSerializationSession(sessionID){if(standardWorktreeSerializationSessions.size>=MAX_TRACKED_STANDARD_WORKTREE_CALLS){let evicted=!1;for(let key2 of serializationStateBySessionID.keys())if(!hasInFlightStandardWorktreeDispatch(key2)){standardWorktreeSerializationSessions.delete(key2),serializationStateBySessionID.delete(key2),standardWorktreeDegradationReasonBySession.delete(key2),evicted=!0;break}if(!evicted)return log(`[worktree-isolation] serialization set at cap with all sessions active; refusing eviction for ${sessionID}`),!1}if(standardWorktreeSerializationSessions.add(sessionID),!serializationStateBySessionID.has(sessionID))serializationStateBySessionID.set(sessionID,{sessionID,serializedAt:Date.now(),successfulDispatchesSince:0});return!0}function sanitizeWorktreeTaskId(raw){return raw.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)||"task"}async function preProvisionCollisionCheck(taskId,directory,_sessionId){let proc;try{proc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",directory,"worktree","list","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:WORKTREE_LIST_TIMEOUT_MS})}catch(error93){let detail=`git worktree list could not start in ${directory}: ${error93 instanceof Error?error93.message:String(error93)}`;return log(`[swarm] preProvisionCollisionCheck: ${detail}`),{collision:!1,uncertainty:detail}}let stdout="",stderr="";try{let exitCode=await proc.exited;if(stdout=await proc.stdout.text(),stderr=await proc.stderr.text(),exitCode!==0){if(stderr.toLowerCase().includes("not a git repository"))return{collision:!1};return log(`[swarm] preProvisionCollisionCheck: git worktree list failed (exit ${exitCode}): ${stderr}`),{collision:!1,uncertainty:stderr.trim()||`git worktree list exited ${exitCode}`}}}finally{try{proc.kill()}catch{}}let entries=[],current={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
|
|
1291
|
+
`:"");writeLegacyStoreFile(legacyPath,legacyPayload),fs61.writeFileSync(projectionMarkerPath(legacyPath),"","utf-8"),legacyStat=fs61.statSync(legacyPath)}checkpoint2.migration.sourceBytes=legacyStat.size,checkpoint2.migration.scannedBytes=legacyStat.size,checkpoint2.migration.sourceMtimeMs=legacyStat.mtimeMs}catch{}}flushAuditEvents(directory,events,checkpoint2.sequence,checkpoint2.maintenance);let archiveEvent=maybeArchiveLegacy(directory,checkpoint2);if(archiveEvent)events.push(archiveEvent),checkpoint2.sequence+=1,_internals85.writeCheckpointFile(directory,checkpoint2),flushAuditEvents(directory,[archiveEvent],checkpoint2.sequence,checkpoint2.maintenance);cleanupStaleLegacyArchive(directory);let coordinationView=readCoordinationSubscriptions(directory);if(coordinationView!==null&&!isDeepStrictEqualByJson(coordinationView,loaded.view))persistCoordinationSubscriptions(directory,{...loaded.view});for(let kind of["compact","migrate-complete","archive","foreign-rebind","corrupt-quarantine"])if(events.some((event)=>event.kind===kind))emitHealthTelemetry(directory,kind,checkpoint2)}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match2)return onSubscriptionCreated?.(directory,match2),match2;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record4={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,...input.forge?{forge:input.forge}:{},lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record4),view[correlationId]=record4,persistCoordinationSubscriptions(directory,view,!0,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record4),record4}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),finalizeWrite(directory,loaded,[]),match;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(loaded.view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record3={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,...input.forge?{forge:input.forge}:{},lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record3),loaded.view[correlationId]=record3,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record3),record3})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;let removed2={...match2,status:"removed",isWatching:!1,updatedAt:Date.now()};return view[correlationId]=removed2,persistCoordinationSubscriptions(directory,view,!0,[{kind:"unsubscribe",correlationId}]),removed2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return loaded.view[correlationId]=removed,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"unsubscribe",correlationId}]),removed})}async function listActive(directory){let{view}=await loadViewForRead(directory);return Object.values(view).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){let{view}=await loadViewForRead(directory);for(let record3 of Object.values(view))if(record3.status==="active"&&record3.repoFullName===repoFullName&&record3.prNumber===prNumber)return record3;return null}async function findSubscriptionRecordForPrUrl(directory,key2){if(key2.repoFullName!==void 0&&key2.prNumber!==void 0){let record3=await lookupByPr(directory,key2.repoFullName,key2.prNumber);if(record3&&(!key2.sessionID||record3.sessionID===key2.sessionID)&&(key2.prUrl===void 0||record3.prUrl===key2.prUrl||subscriptionPrUrlMatches(record3,key2.prUrl)))return record3;if(!key2.sessionID)return null}if(key2.prUrl===void 0&&key2.repoFullName===void 0)return null;if(key2.prUrl===void 0){let active2=await listActive(directory);for(let record3 of active2){if(key2.sessionID&&record3.sessionID!==key2.sessionID)continue;if(record3.repoFullName===key2.repoFullName&&record3.prNumber===key2.prNumber)return record3}return null}let active=await listActive(directory);for(let record3 of active){if(key2.sessionID&&record3.sessionID!==key2.sessionID)continue;if(record3.prUrl===key2.prUrl||subscriptionPrUrlMatches(record3,key2.prUrl))return record3}return null}function subscriptionPrUrlMatches(record3,prUrl){let left=canonicalForgePrUrl(record3.prUrl,record3.forge),right=canonicalForgePrUrl(prUrl,record3.forge);return left!==null&&left===right}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let existingCoordination=readCoordinationSubscriptions(directory);if(existingCoordination!==null&&!fileExistsStrict(storePath3(directory))&&!hasLegacyReconciliationArtifacts(directory)){let match2=Object.values(existingCoordination).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),existingCoordination[correlationId]=updated2,persistCoordinationSubscriptions(directory,existingCoordination),updated2}if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),view[correlationId]=updated2,persistCoordinationSubscriptions(directory,view),updated2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;if(!snapshotUpdateHasChanges(match,updates))return finalizeWrite(directory,loaded,[]),match;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return validateRecord3(updated),loaded.view[correlationId]=updated,loaded.dirty=!0,finalizeWrite(directory,loaded,[]),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},swept2=0,expiredCorrelationIds=[],now2=Date.now();for(let record3 of Object.values(view)){if(record3.status!=="active")continue;let prKey=`${record3.repoFullName}::${record3.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now2-record3.updatedAt>ttlMs;if(isMerged||isStale&&!record3.hasUnaddressedEvents)view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now2},expiredCorrelationIds.push(record3.correlationId),swept2+=1}if(swept2>0)persistCoordinationSubscriptions(directory,view,!0,expiredCorrelationIds.map((correlationId)=>({kind:"expired",correlationId})));return swept2}let loaded=loadViewForWrite(directory),opAudit=[],swept=0;for(let record3 of Object.values(loaded.view)){if(record3.status!=="active")continue;let prKey=`${record3.repoFullName}::${record3.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record3.updatedAt>ttlMs;if(isMerged){loaded.view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record3.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record3.hasUnaddressedEvents)loaded.view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record3.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return finalizeWrite(directory,loaded,opAudit),swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}async function getPrSubscriptionHealth(directory){try{let coordinationView=readCoordinationSubscriptions(directory),read=readCheckpoint(directory),migrationPending=read.kind==="ok"&&sameProjectRoot(read.value.rootPath,directory)&&read.value.migration?.done===!1;if(coordinationView!==null&&Object.keys(coordinationView).length>0&&!migrationPending){let audit2=auditStats(directory),archiveBytes2=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes2=fileSizeOrNull(checkpointPath(directory))??0,health2=healthFromView(coordinationView,buildCoordinationProjectionCheckpoint(directory,coordinationView));return health2.recoverySource="checkpoint",applyFileStats(health2,checkpointBytes2,audit2,archiveBytes2),health2}let audit=auditStats(directory),archiveBytes=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes=fileSizeOrNull(checkpointPath(directory))??0,legacySize=fileSizeOrNull(storePath3(directory)),legacyOverLimit=legacySize!==null&&legacySize>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes,health;if(read.kind==="ok"&&!sameProjectRoot(read.value.rootPath,directory))health=emptyHealth2(),health.recoverySource="foreign";else if(read.kind==="invalid"){if(legacySize!==null&&!legacyOverLimit){let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}else health=emptyHealth2();health.recoverySource="corrupt-recovered"}else if(read.kind==="absent"){if(legacySize===null||legacyOverLimit)health=emptyHealth2();else{let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}health.recoverySource=legacySize===null?"empty":"legacy-log"}else{let pendingCheckpoint=migrationPending&&coordinationView!==null?(()=>{let merged=cloneCheckpoint(read.value);return merged.records={...merged.records,...coordinationView},merged})():read.value,overlaid=overlayLegacy(directory,pendingCheckpoint);health=healthFromView(overlaid.view,read.value),health.recoverySource=overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}return health.legacyOverLimit=legacyOverLimit,applyFileStats(health,checkpointBytes,audit,archiveBytes),health}catch(err){return log(`[pr-monitor] getPrSubscriptionHealth failed: ${storageErrorCode(err)}`),emptyHealth2()}}function applyFileStats(health,checkpointBytes,audit,archiveBytes){health.checkpointBytes=checkpointBytes,health.pressurePct=checkpointBytes===0?0:Math.round(checkpointBytes/health.checkpointLimitBytes*1000)/10,health.auditLines=audit.lines,health.auditBytes=audit.bytes,health.legacyArchiveBytes=archiveBytes}function emptyHealth2(){return{schemaVersion:1,sequence:0,checkpointAgeMs:null,checkpointBytes:0,checkpointLimitBytes:PR_SUBSCRIPTION_LIMITS.maxCheckpointBytes,pressurePct:0,activeCount:0,removedCount:0,expiredCount:0,terminalSummary:{removed:0,expired:0,lastTerminalAt:null},auditLines:0,auditBytes:0,auditLimitBytes:PR_SUBSCRIPTION_LIMITS.auditMaxBytesHigh,compactions:0,corruptLegacyRecords:0,droppedAuditTransitions:0,resets:0,recoverySource:"empty",migration:null,legacyArchiveBytes:0,legacyOverLimit:!1}}function healthFromView(view,checkpoint2){let records=Object.values(view),health=emptyHealth2();return health.sequence=checkpoint2.sequence,health.checkpointAgeMs=checkpoint2.sequence>0?Date.now()-checkpoint2.updatedAt:null,health.activeCount=records.filter((r)=>r.status==="active").length,health.removedCount=records.filter((r)=>r.status==="removed").length,health.expiredCount=records.filter((r)=>r.status==="expired").length,health.terminalSummary={...checkpoint2.terminalSummary},health.compactions=checkpoint2.maintenance.compactions,health.corruptLegacyRecords=checkpoint2.maintenance.corruptLegacyRecords,health.droppedAuditTransitions=checkpoint2.maintenance.droppedAuditTransitions,health.resets=checkpoint2.maintenance.resets,health.migration=checkpoint2.migration?{done:checkpoint2.migration.done,scannedBytes:checkpoint2.migration.scannedBytes,sourceBytes:checkpoint2.migration.sourceBytes}:null,health}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",PR_SUBSCRIPTIONS_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.json",PR_SUBSCRIPTIONS_AUDIT_FILE="pr-monitor/subscriptions.audit.jsonl",LEGACY_ARCHIVE_FILE="pr-monitor/subscriptions.legacy.jsonl",FOREIGN_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.foreign.json",CORRUPT_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.corrupt.json",FOREIGN_LEGACY_FILE="pr-monitor/subscriptions.legacy.foreign.jsonl",PR_SUBSCRIPTION_COORDINATION_NAMESPACE="background.pr-subscription",STORE_LOCK_AGENT="pr-monitor",STORE_LOCK_TASK="pr-subscriptions",PR_SUBSCRIPTION_LIMITS,onSubscriptionCreated=null,prMonitorWorkerHandlers,MAX_PR_MONITOR_WORKER_HANDLERS=64,RecordSchema,TerminalSummarySchema,MigrationSchema,MaintenanceSchema,CheckpointSchema,PrSubscriptionCapacityError,legacyOverLimitWarned,migrationCapacityWarned,bootstrapAttempted,_internals85;var init_pr_subscriptions=__esm(()=>{init_zod();init_db();init_lock();init_learning_health();init_utils2();init_forge_provider();init_telemetry();init_utils();init_atomic_write();init_canonical_root();PR_SUBSCRIPTION_LIMITS={readChunkBytes:65536,maxRecordBytes:65536,migrationChunkBytes:1048576,migrationMaxBytesPerOperation:8388608,legacySourceMaxBytes:67108864,defaultMaxActiveSubscriptions:20,maxCheckpointRecords:512,maxCheckpointBytes:262144,checkpointHardReadBytes:1048576,terminalRecordsHigh:60,terminalRecordsLow:30,terminalMaxAgeMs:2592000000,auditMaxLinesHigh:500,auditMaxLinesLow:250,auditMaxBytesHigh:131072,auditMaxBytesLow:65536,legacyArchiveTtlMs:604800000,bootstrapLockTimeoutMs:5000};prMonitorWorkerHandlers=new Map;RecordSchema=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/\s]+(?:\/[^/\s]+)+$/,"Must be owner/repo format (GitLab nested namespaces allowed)"),prUrl:exports_external.string().min(1),forge:exports_external.object({provider:exports_external.literal("gitlab"),host:exports_external.string().min(1)}).optional(),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict().superRefine((record3,ctx)=>{if(isForgePrUrl(record3.prUrl))return;if(record3.forge&&isForgePrUrl(record3.prUrl,{provider:record3.forge.provider,host:record3.forge.host}))return;ctx.addIssue({code:exports_external.ZodIssueCode.custom,path:["prUrl"],message:"Must be a valid PR URL (GitHub /pull/N or GitLab /-/merge_requests/N)"})}),TerminalSummarySchema=exports_external.object({removed:exports_external.number().int().min(0),expired:exports_external.number().int().min(0),lastTerminalAt:exports_external.number().int().nullable()}).strict(),MigrationSchema=exports_external.object({scannedBytes:exports_external.number().int().nonnegative(),sourceBytes:exports_external.number().int().nonnegative(),sourceMtimeMs:exports_external.number().nonnegative(),corruptLines:exports_external.number().int().nonnegative(),discardingOversizeLine:exports_external.boolean().optional().default(!1),baselineRecords:exports_external.record(exports_external.string(),RecordSchema).optional().default({}),baselineTerminalSummary:TerminalSummarySchema.optional().default({removed:0,expired:0,lastTerminalAt:null}),done:exports_external.boolean(),archived:exports_external.boolean(),startedAt:exports_external.number().int().nonnegative()}).strict(),MaintenanceSchema=exports_external.object({compactions:exports_external.number().int().nonnegative(),droppedAuditTransitions:exports_external.number().int().nonnegative(),corruptLegacyRecords:exports_external.number().int().nonnegative(),lastCompactedAt:exports_external.number().int().nullable(),resets:exports_external.number().int().nonnegative()}).strict(),CheckpointSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative(),records:exports_external.record(exports_external.string(),RecordSchema),terminalSummary:TerminalSummarySchema,migration:MigrationSchema.nullable(),maintenance:MaintenanceSchema}).strict();PrSubscriptionCapacityError=class PrSubscriptionCapacityError extends Error{constructor(message){super(message);this.name="PrSubscriptionCapacityError"}};legacyOverLimitWarned=new Map;migrationCapacityWarned=new Map;bootstrapAttempted=new Map;_internals85={afterCheckpointFstat:(_filePath)=>{},archiveStatSync:fs61.statSync,auditCompactionWrite:atomicWriteSwarmFileSync,beforeBootstrapLock:(_directory2)=>{},beforeArchiveLegacy:(_directory2)=>{},beforeArchiveRename:(_directory2)=>{},foldLegacyRegion,legacyCloseSync:fs61.closeSync,legacyFstatSync:fs61.fstatSync,mergeFoldedRecords,readSync:fs61.readSync,renameWithRetry:renameWithRetry5,sameProjectRoot,statSync:fs61.statSync,writeCheckpointFile}});var exports_state={};__export(exports_state,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,settleReviewerScopeMergeback:()=>settleReviewerScopeMergeback,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setFinalPromptPressure:()=>setFinalPromptPressure,setFinalAccountingWarningBand:()=>setFinalAccountingWarningBand,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resolveInitialTurboMode:()=>resolveInitialTurboMode,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,reserveStageBRouteEvidence:()=>reserveStageBRouteEvidence,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBRouteEvidence:()=>recordStageBRouteEvidence,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordReviewerScopeGenerationCaptureFailure:()=>recordReviewerScopeGenerationCaptureFailure,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReviewerScopeGenerationByStatus:()=>peekReviewerScopeGenerationByStatus,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markStageBRouteRequired:()=>markStageBRouteRequired,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,markReviewerScopeGenerationNoChange:()=>markReviewerScopeGenerationNoChange,markReviewerScopeGenerationMergebackPending:()=>markReviewerScopeGenerationMergebackPending,isStageBRouteRequired:()=>isStageBRouteRequired,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasModifiedFilesForTask:()=>hasModifiedFilesForTask,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getStageBRouteEvidence:()=>getStageBRouteEvidence,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getRehydrationCache:()=>getRehydrationCache,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getFinalPromptPressure:()=>getFinalPromptPressure,getFinalAccountingWarningBand:()=>getFinalAccountingWarningBand,getDisplayFinalPromptPressure:()=>getDisplayFinalPromptPressure,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearStageBRouteRequired:()=>clearStageBRouteRequired,clearStageBRouteEvidence:()=>clearStageBRouteEvidence,clearGateDenialCount:()=>clearGateDenialCount,clearFinalAccountingWarningBands:()=>clearFinalAccountingWarningBands,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals86,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID13}from"node:crypto";import*as fs62 from"node:fs/promises";import*as path100 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),captureFailures:generation.captureFailures.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetBySession.clear(),swarmState.finalPromptPressureBySession.clear(),clearAllTurnLedgers(),swarmState.finalAccountingWarningBandsBySession.clear(),swarmState.liveContextWindows.clear(),swarmState.agentSessions.clear(),clearSnapshotSessionOwnerships(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],clearHydrationOwnershipState(),swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearAllActionCircuits(),clearAllTaskModelRoutingState(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID13(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations){if(entry.status==="claimed"||entry.status==="mergeback_pending"||entry.status==="mergeback_mismatch")continue;if(!Number.isFinite(entry.createdAt)||now<entry.createdAt||now-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key2)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512)||!input.captureDirectory.trim()||!input.workspaceIdentity.trim())return null;let now=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key3,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key3);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,captureDirectory:input.captureDirectory,workspaceIdentity:input.workspaceIdentity,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],captureFailures:[],status:"collecting",createdAt:now};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key2,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key2),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;generation.captureFailures=generation.captureFailures.filter((entry)=>entry.file!==input.fingerprint.file);let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function recordReviewerScopeGenerationCaptureFailure(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096))return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0],now=input.at??Date.now();generation.modifiedFileFingerprints=generation.modifiedFileFingerprints.filter((entry)=>entry.file!==input.file);let existingIndex=generation.captureFailures.findIndex((entry)=>entry.file===input.file);if(existingIndex>=0){let existing=generation.captureFailures[existingIndex];return generation.captureFailures[existingIndex]={...existing,code:input.code,retryable:input.retryable,attempts:existing.attempts+1,at:now},!0}if(generation.captureFailures.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)generation.captureFailures.shift();return generation.captureFailures.push({file:input.file,code:input.code,retryable:input.retryable,attempts:1,at:now}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;let generation=matches[0];if(generation.status==="ready")return!0;if(input.primaryWorkspaceIdentity&&generation.workspaceIdentity!==input.primaryWorkspaceIdentity)return!1;if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file3)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file3))))return!1;return generation.status="ready",generation.readyAt=now,!0}function markReviewerScopeGenerationNoChange(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.at??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.length!==0)return!1;return generation.status="no_change",generation.readyAt=now,!0}function markReviewerScopeGenerationMergebackPending(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="mergeback_pending")return!0;return matches[0].status="mergeback_pending",!0}function settleReviewerScopeMergeback(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status==="mergeback_pending");if(matches.length!==1)return!1;let generation=matches[0],now=input.outcome.at??Date.now();if(input.outcome.verified){if(generation.status="ready",generation.readyAt===void 0)generation.readyAt=now;return generation.mergeback={verifiedAt:now,primaryWorkspaceIdentity:input.outcome.primaryWorkspaceIdentity},generation.captureDirectory=input.outcome.primaryDirectory,generation.workspaceIdentity=input.outcome.primaryWorkspaceIdentity,!0}return generation.status="mergeback_mismatch",generation.mergeback={failedAt:now,reason:input.outcome.reason},!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReviewerScopeGenerationByStatus(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status===input.status);return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key2,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,captureDirectory:generation.captureDirectory,workspaceIdentity:generation.workspaceIdentity,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2})),createdAt:generation.createdAt,readyAt:generation.readyAt??input.now??Date.now(),consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key2),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file3)=>declared.has(file3)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs){if(directory&&isSnapshotSessionOwnedLocally(id)&&!isSnapshotSessionAuthoritativelyStale(directory,id,staleDurationMs,now))continue;staleIds.push(id)}for(let id of staleIds){if(directory&&isSnapshotSessionOwnedLocally(id)){try{deleteSnapshotSessionRows(directory,id,"stale")}catch(error93){warn("[state] durable stale-session teardown failed:",error93 instanceof Error?error93.message:String(error93))}try{clearOverrideForSession(directory,id)}catch(error93){warn("[state] durable stale-session override teardown failed:",error93 instanceof Error?error93.message:String(error93))}}releaseSnapshotSessionOwnership(id),swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),swarmState.activeAgent.delete(id)}return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now,directory)}function resolveInitialTurboMode(directory){if(!directory)return!1;try{return _internals86.loadPluginConfigWithMeta(directory).config.turbo_mode===!0}catch{return!1}}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let owningProjectKey=directory?hydrationProjectKey(directory):void 0,hydrationAuthority=owningProjectKey?captureCurrentHydrationAuthority(owningProjectKey):void 0,hydrationStamp=owningProjectKey?nextSessionHydrationStamp(owningProjectKey):void 0,hydrationAuthorityEpoch2=hydrationAuthority?.authorityEpoch;sweepStaleSessions(staleDurationMs,now,directory);let initialTurboMode=resolveInitialTurboMode(directory),sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,taskWorkflowCache:new Map,stageBCompletion:new Map,stageBRouteEvidence:new Map,stageBRouteRequiredTasks:new Set,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID13(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,turboMode:initialTurboMode,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,owningProjectKey,hydrationStamp,hydrationAuthorityEpoch:hydrationAuthorityEpoch2,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,prmEpisodes:new Map,prmEpisodeGeneration:0,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals86.applyRehydrationCache(sessionState),directory){let liveSession=sessionState,shouldCommitRehydration=()=>hydrationAuthority!==void 0&&isHydrationAuthorityCurrent(hydrationAuthority)&&swarmState.agentSessions.get(sessionId)===liveSession,rehydrationPromise;rehydrationPromise=_internals86.rehydrateSessionFromDisk(directory,sessionState,shouldCommitRehydration).then(async()=>{if(!shouldCommitRehydration())return;try{let subscriptions=await _internals86.rehydratePrSubscriptions(sessionId,directory);if(!shouldCommitRehydration())return;sessionState.prSubscriptions=subscriptions}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId,directory){if(directory){try{deleteSnapshotSessionRows(directory,sessionId)}catch(error93){warn("[state] durable snapshot session teardown failed:",error93 instanceof Error?error93.message:String(error93))}try{clearOverrideForSession(directory,sessionId)}catch(error93){warn("[state] durable session override teardown failed:",error93 instanceof Error?error93.message:String(error93))}}releaseSnapshotSessionOwnership(sessionId);let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(!session.completionGateWarnedForTask)session.completionGateWarnedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(!(session.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID13();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(session.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(STALE_SESSION_TTL_MS,now,directory),session}if(_internals86.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName),lastId=session.lastInvocationIdByAgent[stripped]||0;if(lastId>0)clearInvocationActionCircuits(sessionId,lastId),clearPendingTaskModelRoutesForSession(sessionId,"invocation");let newId=lastId+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key2=`${stripped}:${newId}`;return session.windows[key2]=window2,pruneOldWindows(sessionId,86400000,50),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key2=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key2]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files,workspaceDirectory){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.map((file3)=>canonicalAttributionPath(file3,workspaceDirectory)).filter((file3)=>file3!==null))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file3,workspaceDirectory){if(typeof file3!=="string"||file3.trim().length===0)return!1;if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let canonical=canonicalAttributionPath(file3,workspaceDirectory);if(canonical===null)return!0;let entries=ensureModifiedFilesByTask(session),current=entries.get(taskId)??[];if(current.includes(canonical))return!0;if(entries.set(taskId,[...current,canonical]),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function hasModifiedFilesForTask(session,taskId){if(!session)return!1;if(!isValidTaskId2(taskId))return!1;if(!(session.modifiedFilesByTask instanceof Map))return!1;return session.modifiedFilesByTask.has(taskId)}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides2){let cache2=ensureTaskWorkflowCache(session),existing=cache2.get(taskId);cache2.set(taskId,{generation:overrides2.generation??existing?.generation??0,retryCount:overrides2.retryCount??existing?.retryCount??0,lastOutcome:overrides2.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides2.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides2.updatedAt??existing?.updatedAt??""})}function advanceTaskState(session,taskId,newState2,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState2}`);if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState2),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState2==="complete")session.stageBCompletion?.delete(taskId),clearStageBRouteEvidence(session,taskId),clearStageBRouteRequired(session,taskId),completeModifiedFilesForTask(session,taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState2,current)}function canAdvanceTaskState(session,taskId,newState2,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)return!1;if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState2,_directory2,options,councilConfig){if(newState2==="coder_delegated"||newState2==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState2} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState2,options,councilConfig)}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function reserveStageBRouteEvidence(session,taskId,evidence){if(!isValidTaskId2(taskId))return null;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;let entries=session.stageBRouteEvidence.get(taskId)??[],dispatchIdentity=(entry)=>{if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")},incomingDispatchIdentity=dispatchIdentity(evidence),existingIndex=entries.findIndex((entry)=>entry.role===evidence.role&&(incomingDispatchIdentity!==null&&dispatchIdentity(entry)===incomingDispatchIdentity||incomingDispatchIdentity===null&&dispatchIdentity(entry)===null&&entry.identity===evidence.identity));if(existingIndex>=0){let previousEntry=entries[existingIndex],reservedEntry2={...evidence};return entries[existingIndex]=reservedEntry2,session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry2);if(reservedIndex<0)return;entries[reservedIndex]=previousEntry}}if(entries.length>=32)return null;let reservedEntry={...evidence};return entries.push(reservedEntry),session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry);if(reservedIndex<0)return;if(entries.splice(reservedIndex,1),entries.length===0)session.stageBRouteEvidence?.delete(taskId)}}function recordStageBRouteEvidence(session,taskId,evidence){return reserveStageBRouteEvidence(session,taskId,evidence)!==null}function getStageBRouteEvidence(session,taskId){return(session.stageBRouteEvidence?.get(taskId)??[]).map((entry)=>({...entry}))}function clearStageBRouteEvidence(session,taskId){session.stageBRouteEvidence?.delete(taskId)}function markStageBRouteRequired(session,taskId){if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;session.stageBRouteRequiredTasks.add(taskId)}function isStageBRouteRequired(session,taskId){return session.stageBRouteRequiredTasks?.has(taskId)===!0}function clearStageBRouteRequired(session,taskId){session.stageBRouteRequiredTasks?.delete(taskId)}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence){let snapshot=getTaskWorkflowSnapshot(evidence);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path100.join(directory,".swarm","plan.json"),content=await fs62.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path100.join(directory,".swarm","evidence"),entries=await fs62.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path100.join(evidenceDir,entry.name),content=await fs62.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory,options){let projectKey=hydrationProjectKey(directory),buildAuthority=captureCurrentHydrationAuthority(projectKey),planTaskStates=new Map,plan=options&&Object.hasOwn(options,"planOverride")?options.planOverride:await readPlanFromDisk(directory),cachePlan=plan??null;if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory),councilConfig;try{councilConfig=loadPluginConfig(directory).council}catch{councilConfig=void 0}if(options?.shouldCommit&&!options.shouldCommit()||!isHydrationAuthorityCurrent(buildAuthority))return{committed:!1,reason:"superseded"};return setRehydrationCache(projectKey,{planTaskStates,evidenceMap,taskIdentityContext:{plan:cachePlan,councilConfig}},buildAuthority)?{committed:!0}:{committed:!1,reason:"superseded"}}function applyRehydrationCache(session,projectKey){let resolvedKey=projectKey??session.owningProjectKey;if(!resolvedKey)return;let cache2=getRehydrationCache(resolvedKey);if(!cache2)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap,taskIdentityContext}=cache2;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedWorkflow=evidenceToWorkflowState(evidence);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){let council=evidence.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let rawIdentityDigest=council.identity_digest;if(typeof rawIdentityDigest!=="string"||!/^[a-f0-9]{64}$/.test(rawIdentityDigest)){session.taskCouncilApproved.delete(taskId);continue}let expectedIdentity=computeCouncilReviewIdentity({level:"task",scope:{kind:"task",taskId},plan:taskIdentityContext.plan,config:taskIdentityContext.councilConfig});if(rawIdentityDigest!==expectedIdentity.identityDigest){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);continue}let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session,shouldCommit){let cacheBuild=shouldCommit?await _internals86.buildRehydrationCache(directory,{shouldCommit}):await _internals86.buildRehydrationCache(directory);if(cacheBuild&&!cacheBuild.committed)return;if(shouldCommit&&!shouldCommit())return;_internals86.applyRehydrationCache(session,hydrationProjectKey(directory))}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map3=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map3.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map3.has(sessionID))map3.delete(sessionID);map3.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map3,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map3.has(sessionID))map3.delete(sessionID);map3.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map3,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached3=swarmState.liveContextWindows.get(sessionID);if(!cached3)return;if(identity&&!liveContextIdentityMatches(cached3,identity))return;return cached3.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached3=swarmState.liveContextWindows.get(sessionID);if(!cached3)return;return{modelID:cached3.modelID,providerID:cached3.providerID}}function evictOldestLiveContextWindow(map3,sessionID){if(map3.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map3=swarmState.lastBudgetBySession;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,{pct,tokens}),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function setFinalPromptPressure(sessionID,snapshot){let map3=swarmState.finalPromptPressureBySession;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,snapshot),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function getFinalPromptPressure(sessionID){if(!sessionID)return;return swarmState.finalPromptPressureBySession.get(sessionID)}function setFinalAccountingWarningBand(sessionID,band){let map3=swarmState.finalAccountingWarningBandsBySession,entry=map3.get(sessionID)??{warn:!1,critical:!1};if(map3.has(sessionID))map3.delete(sessionID);if(band==="critical")entry.critical=!0;else entry.warn=!0;if(map3.set(sessionID,entry),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function getFinalAccountingWarningBand(sessionID,band){if(!sessionID)return!1;let entry=swarmState.finalAccountingWarningBandsBySession.get(sessionID);if(!entry)return!1;return band==="critical"?entry.critical:entry.warn}function clearFinalAccountingWarningBands(){swarmState.finalAccountingWarningBandsBySession.clear()}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function getDisplayFinalPromptPressure(){let best=null;for(let entry of swarmState.finalPromptPressureBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function setCriticalShownIds(sessionID,value){let map3=swarmState.currentCriticalShownIds;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,value),map3.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map3=swarmState.gateDenialCounts,existing=map3.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,{count,directiveKey}),map3.size>MAX_TRACKED_GATE_DENIALS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.delete(sessionID)}function addKnowledgeAckDedup(key2){let set3=swarmState.knowledgeAckDedup;if(set3.has(key2))return;if(set3.add(key2),set3.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set3.values().next().value;if(oldest!==void 0)set3.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map3=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record3 of records){if(record3.sessionID!==sessionID)continue;let key2=`${record3.repoFullName}::${record3.prNumber}`;map3.set(key2,{prNumber:record3.prNumber,repoFullName:record3.repoFullName,prUrl:record3.prUrl,lastKnownStatus:record3.mergeableState??"unknown",lastPollTime:record3.lastCheckedAt,errorCount:record3.errorCount,isWatching:record3.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map3}var _councilDisagreementWarned,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals86;var init_state2=__esm(()=>{init_constants();init_loader();init_plan_schema();init_schema();init_council_review_identity();init_qa_gate_profile();init_qa_gate_session_override();init_action_circuit();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_task_model_routing();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_injection_budget();init_hydration_ownership();init_session_start_store();init_snapshot_store();init_worktree_link_suggestion();init_telemetry();init_logger();init_path();_councilDisagreementWarned=new Set,LINEAR_STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"];_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,finalPromptPressureBySession:new Map,finalAccountingWarningBandsBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals86={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,loadPluginConfigWithMeta,resolveInitialTurboMode,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,rehydratePrSubscriptions,isCouncilGateActive,defaultRunContext}});async function boundedSessionCall(call,timeoutMs,timeoutLabel,failureLabel,sessionId){let timer;try{await Promise.race([call(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(`${timeoutLabel} after ${timeoutMs}ms`)),Math.max(1,timeoutMs))})])}catch(error93){_internals87.log(`${failureLabel} for ephemeral session`,{sessionId,error:error93 instanceof Error?error93.message:String(error93)})}finally{if(timer)clearTimeout(timer)}}async function boundedAbortEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS){if(typeof session.abort!=="function")return;await _internals87.boundedSessionCall(()=>session.abort({path:{id:sessionId}}),timeoutMs,"ephemeral session abort timed out","ephemeral session abort failed",sessionId)}async function boundedDeleteEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS){await _internals87.boundedSessionCall(()=>session.delete({path:{id:sessionId}}),timeoutMs,"ephemeral session delete timed out","ephemeral session delete failed",sessionId)}async function teardownEphemeralSession(session,sessionId,options={}){let abortTimeoutMs=options.abortTimeoutMs??DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS,deleteTimeoutMs=options.deleteTimeoutMs??DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS;if(!(options.skipAbort??!1))await _internals87.boundedAbort(session,sessionId,abortTimeoutMs);await _internals87.boundedDelete(session,sessionId,deleteTimeoutMs)}async function sessionExists(session,sessionId,verifyTimeoutMs){if(typeof session.get!=="function")return!0;try{let body=(await withTimeout(session.get({path:{id:sessionId}}),verifyTimeoutMs,Error(`ephemeral session verify timed out after ${verifyTimeoutMs}ms`)))?.data;if(body===void 0||body===null)return!1;return!0}catch{return!1}}async function teardownEphemeralSessionVerified(session,sessionId,options={}){let verifyTimeoutMs=options.verifyTimeoutMs??DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS,attempts=Math.min(6,Math.max(2,options.maxDeleteAttempts??DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS));if(typeof session.get!=="function")return await teardownEphemeralSession(session,sessionId,options),{ok:!1,sessionId,attempts:1,kind:"ephemeral-session-teardown-unverified",reason:"get-unavailable"};let deleteAttempts=0;for(;;){if(await teardownEphemeralSession(session,sessionId,{...options,skipAbort:deleteAttempts>0?!0:options.skipAbort}),deleteAttempts+=1,!await _internals87.sessionExists(session,sessionId,verifyTimeoutMs))return{ok:!0,sessionId,attempts:deleteAttempts};if(deleteAttempts>=attempts)return{ok:!1,sessionId,attempts:deleteAttempts,kind:"ephemeral-session-teardown-unverified",reason:"session-survived-bounded-retries"}}}var DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS=5000,DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS=3,_internals87;var init_ephemeral_session_teardown=__esm(()=>{init_logger();init_timeout();_internals87={boundedSessionCall,boundedAbort:boundedAbortEphemeralSession,boundedDelete:boundedDeleteEphemeralSession,sessionExists,log}});var init_worktree=__esm(()=>{init_core3();init_merge2()});function verifyReviewerScopeGenerationMergeBack(input){try{let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,now:input.now});if(!generation||generation.modifiedFiles.length===0)return;if(generation.status!=="collecting"&&generation.status!=="mergeback_pending")return;if(generation.status==="collecting"){if(!markReviewerScopeGenerationMergebackPending({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,at:input.now}))return}let session=ensureAgentSession(input.parentSessionID),deadlineAt=(input.now??Date.now())+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let file3 of generation.modifiedFiles){let stored=generation.modifiedFileFingerprints.find((entry)=>entry.file===file3);if(!stored){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`incomplete fingerprints: ${file3} has no stored capture`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification found no stored fingerprint for ${file3}. ACTION[architect]: re-dispatch the coder for this task`);return}let captured=captureReviewerScopeFileFingerprint(input.primaryDirectory,file3,{deadlineAt});if(captured.kind==="capture_failed"){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`capture ${captured.code} on ${captured.file}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout capture failed for ${captured.file} (${captured.code}). ACTION[architect]: verify the primary checkout, then re-dispatch the reviewer`);return}let capturedFingerprint=reviewerScopeCaptureToFingerprint(captured);if(!capturedFingerprint||!reviewerScopeFileFingerprintsEqual(stored,capturedFingerprint)){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`primary bytes differ from lane manifest on ${file3}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout bytes differ from the lane manifest on ${file3}; lane evidence retained. ACTION[architect]: resolve the merge conflict or re-dispatch the coder`);return}}let primaryIdentity=canonicalWorkspaceIdentity(input.primaryDirectory);settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!0,primaryWorkspaceIdentity:primaryIdentity??input.primaryDirectory,primaryDirectory:input.primaryDirectory,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_VERIFIED: task ${input.taskId}: primary checkout matches the lane manifest exactly; reviewer dispatch is enabled`)}catch(error93){try{let session=ensureAgentSession(input.parentSessionID);pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification errored (${String(error93).slice(0,200)}). ACTION[architect]: re-dispatch the reviewer to retry verification`),settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:"verification error",at:input.now}})}catch{}}}var init_reviewer_scope_mergeback=__esm(()=>{init_scope_binding();init_state2();init_reviewer_scope_file_fingerprint()});import{createHash as createHash45,randomBytes as randomBytes7}from"node:crypto";import*as fs63 from"node:fs";import*as path101 from"node:path";function nowMs2(input){return input??Date.now()}function sha2565(input){return createHash45("sha256").update(input).digest("hex")}function storePath4(directory){return path101.join(directory,STORE_RELATIVE_PATH)}function journalPath2(directory){return path101.join(directory,JOURNAL_RELATIVE_PATH)}function credentialPath(directory,authorityDigest){return path101.join(directory,CREDENTIAL_DIRECTORY,`${authorityDigest}.json`)}function readAuthorityLockRecord(lockPath){try{let parsed=JSON.parse(fs63.readFileSync(lockPath,"utf8"));if(typeof parsed?.nonce==="string"&&typeof parsed?.acquiredAt==="number"&&Number.isFinite(parsed.acquiredAt)&&typeof parsed?.pid==="number"&&Number.isInteger(parsed.pid))return{nonce:parsed.nonce,acquiredAt:parsed.acquiredAt,pid:parsed.pid}}catch{}return}function writeAuthorityLockRecord(lockPath,record3){try{return fs63.writeFileSync(lockPath,JSON.stringify(record3,null,2),{flag:"wx"}),!0}catch{return!1}}function isProcessAlive2(pid){if(!Number.isSafeInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch{return!1}}function acquireAuthorityLock(directory){let lockPath=path101.join(directory,AUTHORITY_LOCK_RELATIVE_PATH);fs63.mkdirSync(path101.dirname(lockPath),{recursive:!0});let nonce=randomBytes7(16).toString("hex"),acquiredAt=Date.now(),attempt=()=>writeAuthorityLockRecord(lockPath,{nonce,acquiredAt,pid:process.pid});if(!attempt())try{let observed=readAuthorityLockRecord(lockPath);if(!observed)return;if(Date.now()-fs63.statSync(lockPath).mtimeMs>AUTHORITY_LOCK_STALE_MS){if(isProcessAlive2(observed.pid))return;let reread=readAuthorityLockRecord(lockPath);if(reread&&reread.nonce===observed.nonce&&reread.acquiredAt===observed.acquiredAt&&reread.pid===observed.pid){if(fs63.unlinkSync(lockPath),!attempt())return}}}catch{return}let acquired=readAuthorityLockRecord(lockPath);if(!acquired||acquired.nonce!==nonce)return;let released=!1;return()=>{if(released)return;released=!0;try{if(readAuthorityLockRecord(lockPath)?.nonce===nonce)fs63.unlinkSync(lockPath)}catch{}}}function taskKey(parentSessionId,taskId){return`${parentSessionId}::${taskId}`}function stableStringify(value){if(Array.isArray(value))return`[${value.map((item)=>stableStringify(item)).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key2,item])=>`${JSON.stringify(key2)}:${stableStringify(item)}`).join(",")}}`;return JSON.stringify(value)}function digestAuthorityIdentity(input){return sha2565(stableStringify({originalCallID:input.originalCallID,parentSessionId:input.parentSessionId,taskId:input.taskId,reservationId:input.reservationId,generation:input.generation,canonicalBranch:input.canonicalBranch,canonicalPath:input.canonicalPath,laneBranch:input.laneBranch,lanePath:input.lanePath,expectedPrimaryHead:input.expectedPrimaryHead,sourceBaseOid:input.sourceBaseOid,sourceHeadOid:input.sourceHeadOid,targetHeadOid:input.targetHeadOid,strategy:input.strategy,declaredConflictFiles:input.declaredConflictFiles??[]}))}function nonEmpty(value){return typeof value==="string"&&value.length>0&&value.length<=4096}function isHex40(value){return typeof value==="string"&&HEX_40_RE.test(value)}function isOidArray(value){return Array.isArray(value)&&value.length<=4096&&value.every(isHex40)}function isSettlementEvidence(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return isOidArray(candidate.sourceCommitOrder)&&isOidArray(candidate.rewrittenCommitOrder)&&candidate.sourceCommitOrder.length===candidate.rewrittenCommitOrder.length}function isStrategy(value){return value==="merge"||value==="rebase"||value==="cherry-pick"}function isImmutableIdentity(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.originalCallID)&&nonEmpty(candidate.parentSessionId)&&nonEmpty(candidate.taskId)&&nonEmpty(candidate.reservationId)&&typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0&&nonEmpty(candidate.canonicalBranch)&&nonEmpty(candidate.canonicalPath)&&nonEmpty(candidate.laneBranch)&&nonEmpty(candidate.lanePath)&&isHex40(candidate.expectedPrimaryHead)&&isHex40(candidate.sourceBaseOid)&&isHex40(candidate.sourceHeadOid)&&isHex40(candidate.targetHeadOid)&&isStrategy(candidate.strategy)&&(candidate.declaredConflictFiles===void 0||Array.isArray(candidate.declaredConflictFiles)&&candidate.declaredConflictFiles.every((item)=>nonEmpty(item)))&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function isClaimState(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.claimedAt==="number"&&Number.isFinite(candidate.claimedAt)&&candidate.claimedAt>=0}function isAuthority(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,claimCursor=candidate.claimCursor&&typeof candidate.claimCursor==="object"?candidate.claimCursor:void 0,validStatus=candidate.status==="preserved"||candidate.status==="claimed"||candidate.status==="released"||candidate.status==="finalized";return candidate.schemaVersion===2&&nonEmpty(candidate.authorityDigest)&&isImmutableIdentity(candidate.immutable)&&validStatus&&(candidate.claim===void 0||isClaimState(candidate.claim))&&(claimCursor===void 0||typeof claimCursor.lastClaimRevision==="number"&&Number.isInteger(claimCursor.lastClaimRevision)&&claimCursor.lastClaimRevision>0&&typeof claimCursor.lastAttempt==="number"&&Number.isInteger(claimCursor.lastAttempt)&&claimCursor.lastAttempt>0)&&(candidate.status!=="claimed"||candidate.claim!==void 0)&&(candidate.finalizedAt===void 0||typeof candidate.finalizedAt==="number"&&Number.isFinite(candidate.finalizedAt)&&candidate.finalizedAt>=0)&&(candidate.settlement===void 0||isSettlementEvidence(candidate.settlement))}function isJournalEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,validState=candidate.state==="PREPARED"||candidate.state==="COMMITTED"||candidate.state==="CLAIM_RENEWED"||candidate.state==="ABORTED"||candidate.state==="RELEASED"||candidate.state==="FINALIZED";return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&validState&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&(candidate.childSessionId===void 0||nonEmpty(candidate.childSessionId))&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.preparedAt==="number"&&Number.isFinite(candidate.preparedAt)&&candidate.preparedAt>=0&&(candidate.credentialInstalledAt===void 0||typeof candidate.credentialInstalledAt==="number"&&Number.isFinite(candidate.credentialInstalledAt)&&candidate.credentialInstalledAt>=0)&&(candidate.committedAt===void 0||typeof candidate.committedAt==="number"&&Number.isFinite(candidate.committedAt)&&candidate.committedAt>=0)&&(candidate.abortedAt===void 0||typeof candidate.abortedAt==="number"&&Number.isFinite(candidate.abortedAt)&&candidate.abortedAt>=0)&&(candidate.reason===void 0||nonEmpty(candidate.reason))}function isCredential(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&nonEmpty(candidate.rawToken)&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function rebuildIndex(authorities){let bySessionTask={};for(let authority of[...authorities].sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)){let key2=taskKey(authority.immutable.parentSessionId,authority.immutable.taskId),digests=bySessionTask[key2]??[];digests.push(authority.authorityDigest),bySessionTask[key2]=digests}return{bySessionTask}}function emptyJournal(){return{schemaVersion:1,entries:[]}}function readBoundedJsonFile2(filePath,maxBytes){try{if(fs63.statSync(filePath).size>maxBytes)return{ok:!1,reason:`${path101.basename(filePath)} exceeds the ${maxBytes}-byte safety bound`};let raw=fs63.readFileSync(filePath,"utf8");if(Buffer.byteLength(raw,"utf8")>maxBytes)return{ok:!1,reason:`${path101.basename(filePath)} changed beyond the ${maxBytes}-byte safety bound`};return{ok:!0,value:JSON.parse(raw)}}catch(error93){if(error93.code==="ENOENT")return{ok:!0,value:void 0};return{ok:!1,reason:`${path101.basename(filePath)} is unreadable or malformed: ${error93 instanceof Error?error93.message:String(error93)}`}}}function loadStoreStrict(directory){let loaded=readBoundedJsonFile2(storePath4(directory),MAX_STORE_BYTES);if(!loaded.ok)return{status:"uncertain",reason:loaded.reason};if(loaded.value===void 0)return{status:"ok",authorities:[]};let parsed=loaded.value;if(parsed.schemaVersion===1)return{status:"unsupported-legacy",reason:"worktree recovery v1 records are unsupported for claim mutation"};if(parsed.schemaVersion!==2)return{status:"uncertain",reason:`unknown worktree recovery schema version: ${String(parsed.schemaVersion)}`};if(!Array.isArray(parsed.authorities))return{status:"uncertain",reason:"worktree recovery store does not contain an authorities array"};if(parsed.authorities.length>MAX_STORE_AUTHORITIES)return{status:"uncertain",reason:`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`};for(let authority of parsed.authorities)if(!isAuthority(authority))return{status:"uncertain",reason:"worktree recovery store contains an invalid authority record"};return{status:"ok",authorities:[...parsed.authorities]}}function loadStoreWritable(directory){let scanned=loadStoreStrict(directory);if(scanned.status==="unsupported-legacy")return{ok:!1,code:"unsupported_legacy",reason:scanned.reason};if(scanned.status==="uncertain")return{ok:!1,code:"uncertain_store",reason:scanned.reason};return{schemaVersion:2,authorities:scanned.authorities,index:rebuildIndex(scanned.authorities)}}function loadJournal(directory){let loaded=readBoundedJsonFile2(journalPath2(directory),MAX_JOURNAL_BYTES2);if(!loaded.ok||loaded.value===void 0)return emptyJournal();let parsed=loaded.value;if(parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return emptyJournal();let entries=[];for(let entry of parsed.entries)if(isJournalEntry(entry))entries.push(entry);return{schemaVersion:1,entries:entries.slice(-MAX_JOURNAL_ENTRIES)}}function updateStore(store,authorities){return store.authorities=authorities,store.index=rebuildIndex(authorities),store}function currentClaimMatches(authority,request){if(!authority.claim)return!1;return authority.claim.claimantCallID===request.claimantCallID&&authority.claim.claimRevision===request.claimRevision&&authority.claim.claimTokenDigest===sha2565(request.rawToken)}function latestJournalEntriesByAuthority(journal){let latest=new Map;for(let entry of journal.entries)latest.set(entry.authorityDigest,entry);return[...latest.values()]}function recordJournalEntry(directory,entry){let journal=loadJournal(directory);if(journal.entries.push(entry),journal.entries.length>MAX_JOURNAL_ENTRIES)journal.entries=journal.entries.slice(-MAX_JOURNAL_ENTRIES);return _internals88.writeClaimJournal(journalPath2(directory),journal),journal}function writeCredential(directory,credential){let targetPath=credentialPath(directory,credential.authorityDigest);_internals88.writeCredentialFile(targetPath,credential);try{fs63.chmodSync(targetPath,384)}catch{}return targetPath}function readCredential(directory,authorityDigest){let loaded=readBoundedJsonFile2(credentialPath(directory,authorityDigest),MAX_CREDENTIAL_BYTES);if(!loaded.ok||loaded.value===void 0)return;return isCredential(loaded.value)?loaded.value:void 0}function removeCredentialIfMatch(directory,entry){let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID)try{fs63.unlinkSync(credentialPath(directory,entry.authorityDigest))}catch{}}function baseMutationFailure(code,reason){return{ok:!1,code,reason}}function publishWorktreeRecoveryAuthorityUnlocked(directory,input){let store=loadStoreWritable(directory);if("ok"in store)return store;let immutable={...input,createdAt:nowMs2()};if(!isImmutableIdentity(immutable))return baseMutationFailure("uncertain_store","invalid immutable recovery authority input");let authorityDigest=digestAuthorityIdentity(input),existing=store.authorities.find((authority2)=>authority2.authorityDigest===authorityDigest);if(existing)return{ok:!0,authority:existing};let authority={schemaVersion:2,authorityDigest,immutable,status:"preserved"},nextAuthorities=[...store.authorities,authority];if(nextAuthorities.length>MAX_STORE_AUTHORITIES)return baseMutationFailure("uncertain_store",`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`);return _internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"publish"),{ok:!0,authority}}function publishWorktreeRecoveryAuthority(directory,input){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return publishWorktreeRecoveryAuthorityUnlocked(directory,input)}finally{release()}}function scanWorktreeRecoveryAuthoritiesForRecovery(directory){return loadStoreStrict(directory)}function lookupWorktreeRecoveryAuthoritiesByTask(directory,query){let scanned=loadStoreStrict(directory);if(scanned.status!=="ok")return scanned;return{status:"ok",authorities:scanned.authorities.filter((authority)=>authority.immutable.parentSessionId===query.parentSessionId&&authority.immutable.taskId===query.taskId).sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)}}async function claimWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let authorityIndex=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(authorityIndex===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[authorityIndex];if(authority.status==="finalized")return baseMutationFailure("finalized","finalized worktree recovery authority cannot be claimed again");let currentTime=nowMs2(request.now),previousClaim=authority.claim;if(previousClaim&&previousClaim.leaseExpiresAt>currentTime)return baseMutationFailure("busy","worktree recovery authority is already claimed");if(previousClaim&&previousClaim.leaseExpiresAt<=currentTime){if(!request.revalidateExpiredClaim)return baseMutationFailure("revalidation_required","expired worktree recovery claims require full revalidation before transfer");let verdict=await request.revalidateExpiredClaim({authority,previousClaim});if(!verdict.ok)return baseMutationFailure("revalidation_failed",verdict.reason)}let nextAttempt=(previousClaim?.attempt??authority.claimCursor?.lastAttempt??0)+1,maxAttempts=request.maxAttempts??DEFAULT_MAX_ATTEMPTS;if(nextAttempt>maxAttempts)return baseMutationFailure("retry_cap_exceeded",`worktree recovery claim attempt ${nextAttempt} exceeds the ${maxAttempts}-attempt safety cap`);let nextRevision=(previousClaim?.claimRevision??authority.claimCursor?.lastClaimRevision??0)+1,rawToken=_internals88.generateRawToken(),claimTokenDigest=sha2565(rawToken);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let childSessionId=await request.createChildSession(),refreshedStore=loadStoreWritable(directory);if("ok"in refreshedStore)throw Error(`worktree recovery authority could not be revalidated: ${refreshedStore.reason}`);let refreshedAuthority=refreshedStore.authorities.find((candidate)=>candidate.authorityDigest===request.authorityDigest);if(!refreshedAuthority||stableStringify({status:refreshedAuthority.status,claim:refreshedAuthority.claim,claimCursor:refreshedAuthority.claimCursor,immutable:refreshedAuthority.immutable})!==stableStringify({status:authority.status,claim:authority.claim,claimCursor:authority.claimCursor,immutable:authority.immutable}))throw recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"ABORTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,abortedAt:nowMs2(),reason:"authority changed while child session was being created"}),Error("worktree recovery authority changed while child session was being created");recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let credential={schemaVersion:1,authorityDigest:authority.authorityDigest,claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,rawToken,leaseExpiresAt:currentTime+request.leaseMs,createdAt:currentTime},writtenCredentialPath=writeCredential(directory,credential);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime});let claimedAuthority={...authority,status:"claimed",claim:{claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,claimedAt:currentTime},claimCursor:{lastClaimRevision:nextRevision,lastAttempt:nextAttempt}},nextAuthorities=[...store.authorities];return nextAuthorities[authorityIndex]=claimedAuthority,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-commit"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"COMMITTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime,committedAt:currentTime}),{ok:!0,authority:claimedAuthority,rawToken,credentialPath:writtenCredentialPath}}async function claimWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return await claimWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function renewWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let renewed={...authority,claim:{...authority.claim,leaseExpiresAt:nowMs2(request.now)+request.leaseMs}},nextAuthorities=[...store.authorities];return nextAuthorities[index]=renewed,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-renew"),writeCredential(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,rawToken:request.rawToken,leaseExpiresAt:renewed.claim.leaseExpiresAt,createdAt:renewed.claim.claimedAt}),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,state:"CLAIM_RENEWED",claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,attempt:renewed.claim.attempt,leaseExpiresAt:renewed.claim.leaseExpiresAt,claimTokenDigest:renewed.claim.claimTokenDigest,preparedAt:renewed.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim lease renewed"}),{ok:!0,authority:renewed}}function renewWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return renewWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function releaseWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let released={...authority,status:"preserved",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor},nextAuthorities=[...store.authorities];return nextAuthorities[index]=released,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-release"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"RELEASED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim released after preserved settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:released}}function releaseWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return releaseWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function finalizeWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let finalized={...authority,status:"finalized",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor,finalizedAt:nowMs2(request.now),settlement:request.settlement},nextAuthorities=[...store.authorities];return nextAuthorities[index]=finalized,_internals88.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-finalize"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"FINALIZED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim finalized after landed settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:finalized}}function finalizeWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return finalizeWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function replayWorktreeRecoveryClaimJournalUnlocked(directory,options){let outcomes=[],storeScan=loadStoreStrict(directory),authorities=new Map((storeScan.status==="ok"?storeScan.authorities:[]).map((authority)=>[authority.authorityDigest,authority]));for(let entry of latestJournalEntriesByAuthority(loadJournal(directory))){if(entry.state==="ABORTED"||entry.state==="CLAIM_RENEWED"||entry.state==="RELEASED"||entry.state==="FINALIZED"){outcomes.push({authorityDigest:entry.authorityDigest,outcome:"noop"});continue}if(entry.state==="COMMITTED"){let current2=authorities.get(entry.authorityDigest);if(current2&&!current2.claim&¤t2.claimCursor?.lastClaimRevision===entry.claimRevision&&(current2.status==="preserved"||current2.status==="finalized")){recordJournalEntry(directory,{...entry,state:current2.status==="finalized"?"FINALIZED":"RELEASED",reason:"repaired terminal claim journal after interrupted settlement"}),removeCredentialIfMatch(directory,entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"repaired_terminal_claim"});continue}if(current2?.claim&¤t2.claim.claimRevision===entry.claimRevision&¤t2.claim.claimTokenDigest===entry.claimTokenDigest){let credential2=readCredential(directory,entry.authorityDigest),released=credential2?releaseWorktreeRecoveryClaimUnlocked(directory,{authorityDigest:entry.authorityDigest,claimantCallID:entry.claimantCallID,claimRevision:entry.claimRevision,rawToken:credential2.rawToken}):void 0;outcomes.push({authorityDigest:entry.authorityDigest,outcome:released?.ok?"released_orphaned_committed_claim":"uncertain_committed_without_authority"})}else outcomes.push({authorityDigest:entry.authorityDigest,outcome:"uncertain_committed_without_authority"});continue}let current=authorities.get(entry.authorityDigest);if(current?.claim&¤t.claim.claimRevision===entry.claimRevision&¤t.claim.claimTokenDigest===entry.claimTokenDigest){recordJournalEntry(directory,{...entry,state:"COMMITTED",committedAt:nowMs2()}),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"committed_claim_stable"});continue}let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID){removeCredentialIfMatch(directory,entry),recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"removed uncommitted credential during replay"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"removed_uncommitted_credential"});continue}recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"prepared claim never reached credential install or commit"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"aborted_prepared_claim"})}return outcomes}function replayWorktreeRecoveryClaimJournal(directory,options){let release=acquireAuthorityLock(directory);if(!release)throw Error("worktree recovery authority store is locked");try{return replayWorktreeRecoveryClaimJournalUnlocked(directory,options)}finally{release()}}var STORE_RELATIVE_PATH,JOURNAL_RELATIVE_PATH,CREDENTIAL_DIRECTORY,AUTHORITY_LOCK_RELATIVE_PATH,AUTHORITY_LOCK_STALE_MS=600000,MAX_STORE_BYTES=2097152,MAX_STORE_AUTHORITIES=512,MAX_JOURNAL_BYTES2=2097152,MAX_JOURNAL_ENTRIES=512,MAX_CREDENTIAL_BYTES=16384,DEFAULT_MAX_ATTEMPTS=8,HEX_40_RE,_internals88;var init_worktree_recovery_authority=__esm(()=>{init_atomic_write();STORE_RELATIVE_PATH=path101.join(".swarm","worktree-merge-recovery-v2.json"),JOURNAL_RELATIVE_PATH=path101.join(".swarm","worktree-merge-recovery-v2-journal.json"),CREDENTIAL_DIRECTORY=path101.join(".swarm","worktree-recovery-claims"),AUTHORITY_LOCK_RELATIVE_PATH=path101.join(".swarm","locks","worktree-recovery-authority.lock"),HEX_40_RE=/^[0-9a-f]{40}$/i;_internals88={generateRawToken:()=>randomBytes7(32).toString("hex"),writeRecoveryStore:(targetPath,store,_phase)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(store,null,2))},writeClaimJournal:(targetPath,journal)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(journal,null,2))},writeCredentialFile:(targetPath,credential)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(credential,null,2),{mode:384})},getRecoveryStorePath:storePath4,getClaimJournalPath:journalPath2,getCredentialPath:credentialPath,acquireAuthorityLock,readClaimJournal(directory){return loadJournal(directory)},resetForTest(){}}});import*as fs64 from"node:fs";import*as path102 from"node:path";function decodeTagPart(value){if(!value||!/^[A-Za-z0-9_-]+$/.test(value))return null;let decoded=Buffer.from(value,"base64url").toString("utf8");return decoded&&Buffer.from(decoded,"utf8").toString("base64url")===value?decoded:null}async function scanBackgroundWorktreeOwnershipTagsForRecovery(directory){try{fs64.statSync(path102.join(directory,".git"))}catch(error93){if(error93.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`Git metadata could not be inspected: ${error93 instanceof Error?error93.message:String(error93)}`}}let proc;try{proc=bunSpawn([resolveGitExecutable(),"-C",directory,"for-each-ref",`--count=${MAX_OWNERSHIP_TAGS+1}`,"--format=%(refname:strip=2)%00%(objectname)","refs/tags/swarm-preserved-owner/"],{stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:OWNERSHIP_TAG_SCAN_TIMEOUT_MS});let exitCode=await proc.exited;if(exitCode!==0)return{status:"uncertain",reason:`ownership tag scan exited ${exitCode}`};let lines=(await proc.stdout.text()).split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);if(lines.length>MAX_OWNERSHIP_TAGS)return{status:"uncertain",reason:`ownership tag scan exceeded the ${MAX_OWNERSHIP_TAGS}-tag safety bound`};let owners=[];for(let line of lines){let[tag,ref,...extra]=line.split("\x00"),segments=tag?.split("/")??[],sessionId=decodeTagPart(segments[1]??""),laneId=decodeTagPart(segments[2]??""),callDigest=segments[3];if(extra.length>0||segments.length!==4||segments[0]!=="swarm-preserved-owner"||!sessionId||!laneId||!callDigest||!/^[0-9a-f]{12}$/.test(callDigest)||!ref||!/^[0-9a-f]{40,64}$/i.test(ref))return{status:"uncertain",reason:`malformed background ownership tag entry "${tag??""}"`};owners.push({sessionId,laneId,callDigest,ref})}return{status:"ok",owners}}catch(error93){return{status:"uncertain",reason:`ownership tag scan failed: ${error93 instanceof Error?error93.message:String(error93)}`}}finally{try{proc?.kill()}catch{}}}var OWNERSHIP_TAG_SCAN_TIMEOUT_MS=2000,MAX_OWNERSHIP_TAGS=512;var init_worktree_ownership_tag=__esm(()=>{init_bun_compat();init_git_executable()});var exports_worktree_collision_ownership={};__export(exports_worktree_collision_ownership,{inspectStandardWorktreeCollisionOwnership:()=>inspectStandardWorktreeCollisionOwnership,_internals:()=>_internals89});import*as fs65 from"node:fs";function descriptorCoordinateMatch(descriptor,identity){let branchMatches=descriptor.branchName===identity.branchName,pathMatches2=canonicalRootKeyFresh(descriptor.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)return"none";if(!branchMatches||!pathMatches2||descriptor.parentSessionId!==identity.parentSessionId||descriptor.taskId!==identity.taskId)return"uncertain";return"exact"}function isProvenSettled(record3){let settlement=record3.coderSettlement;return settlement?.state==="settled"&&settlement.outcome?.kind==="standard-worktree"&&(settlement.outcome.result==="merged"||settlement.outcome.result==="unchanged")}function classifyRecord(record3,identity,ownerKind){if(!record3.worktree)return null;let coordinates=descriptorCoordinateMatch(record3.worktree,identity);if(coordinates==="none")return null;if(coordinates==="uncertain")return{status:"uncertain",reason:`${ownerKind} background owner has conflicting identity for branch "${identity.branchName}"`};if(isProvenSettled(record3))return null;let lifecycle=record3.coderSettlement?.state==="preserved"?"preserved":"active";return{status:"protected",ownerKind,lifecycle,reason:`${ownerKind} background owner ${record3.correlationId} is ${record3.status}`+(record3.coderSettlement?` with coder settlement ${record3.coderSettlement.state}`:" without a settled workspace outcome")}}async function inspectStandardWorktreeCollisionOwnership(identity){let provisioning=scanWorktreeProvisioningOwnersForRecovery(identity.directory);if(provisioning.status==="uncertain")return provisioning;let now=Date.now();for(let owner of provisioning.owners){if(!(owner.parentSessionId===identity.parentSessionId||owner.worktreeSessionId===identity.parentSessionId))continue;if(owner.schemaVersion===1||owner.taskId===identity.taskId){let leaseIsLive=now-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS;if(!leaseIsLive)try{_internals89.statSync(identity.worktreePath)}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} lane liveness is unreadable: ${error93 instanceof Error?error93.message:String(error93)}`};if(!_internals89.removeWorktreeProvisioningOwner(identity.directory,owner.callID,owner.schemaVersion===3?{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}:void 0))return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} could not be removed`};continue}return{status:"protected",ownerKind:"provisioning",lifecycle:"active",reason:!leaseIsLive?`provisioning owner ${owner.callID} lease expired, but its exact lane path still exists`:owner.schemaVersion===1?`legacy provisioning owner ${owner.callID} cannot disprove ownership of this same-session lane`:`provisioning owner ${owner.callID} is active for task ${identity.taskId}`}}}let fallback=await scanDelegationFallbacksForRecovery(identity.directory);if(fallback.status==="uncertain")return fallback;for(let artifact of fallback.owners){let classified=classifyRecord(artifact.record,identity,"fallback");if(classified)return classified}let primary=scanDelegationsForRecovery(identity.directory);if(primary.status==="uncertain")return primary;for(let record3 of primary.owners){let classified=classifyRecord(record3,identity,"primary");if(classified)return classified}let tags=await scanBackgroundWorktreeOwnershipTagsForRecovery(identity.directory);if(tags.status==="uncertain")return tags;for(let owner of tags.owners)if(owner.sessionId===identity.parentSessionId&&owner.laneId===identity.taskId)return{status:"protected",ownerKind:"ownership-tag",lifecycle:"preserved",reason:`durable ownership tag ${owner.callDigest} preserves this same-session lane`};let mergeStatus=scanWorktreeMergeFailuresForRecovery(identity.directory);if(mergeStatus.status==="uncertain")return mergeStatus;for(let[,failure]of mergeStatus.failures){let branchMatches=failure.branch===identity.branchName,pathMatches2=typeof failure.worktreePath==="string"&&canonicalRootKeyFresh(failure.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)continue;if(!branchMatches||!pathMatches2)return{status:"uncertain",reason:`merge-status owner has conflicting identity for branch "${identity.branchName}"`};return{status:"protected",ownerKind:"merge-status",lifecycle:"preserved",reason:`merge-status records ${failure.outcome} at stage ${failure.stage}`}}return{status:"unowned"}}var _internals89;var init_worktree_collision_ownership=__esm(()=>{init_pending_delegations();init_canonical_root();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();_internals89={statSync:fs65.statSync,removeWorktreeProvisioningOwner}});var exports_worktree_isolation={};__export(exports_worktree_isolation,{standardWorktreeSerializationSessions:()=>standardWorktreeSerializationSessions,standardWorktreeByCallID:()=>standardWorktreeByCallID,sanitizeWorktreeTaskId:()=>sanitizeWorktreeTaskId,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resetStandardWorktreeIsolationState:()=>resetStandardWorktreeIsolationState,readLaneEnvFileFromDisk:()=>readLaneEnvFileFromDisk,preserveDirtyWorktreeForCallId:()=>preserveDirtyWorktreeForCallId,preserveDirtyWorktreeAtPath:()=>preserveDirtyWorktreeAtPath,preserveBackgroundWorktreeOwnershipForCallId:()=>preserveBackgroundWorktreeOwnershipForCallId,precreateStandardWorktreeSession:()=>precreateStandardWorktreeSession,preProvisionCollisionCheck:()=>preProvisionCollisionCheck,parseLeanLaneIndex:()=>parseLeanLaneIndex,isLaneOwnedByCurrentSession:()=>isLaneOwnedByCurrentSession,getStandardWorktreeDegradationReason:()=>getStandardWorktreeDegradationReason,finishStandardWorktreeDispatch:()=>finishStandardWorktreeDispatch,computeLaneRuntimeProfile:()=>computeLaneRuntimeProfile,cleanupStandardWorktreeForCallId:()=>cleanupStandardWorktreeForCallId,checkStandardWorktreeSerializationRelease:()=>checkStandardWorktreeSerializationRelease,awaitingMergeByCallID:()=>awaitingMergeByCallID,abortStandardWorktreeDispatch:()=>abortStandardWorktreeDispatch,_internals:()=>_internals83,MAX_TRACKED_STANDARD_WORKTREE_CALLS:()=>MAX_TRACKED_STANDARD_WORKTREE_CALLS});import{createHash as createHash46}from"node:crypto";import*as fs66 from"node:fs/promises";import*as path103 from"node:path";function parseLeanLaneIndex(laneId){let match=/^lane-(\d+)$/.exec(laneId);if(match){let n=parseInt(match[1],10);return Number.isNaN(n)?0:n-1}return 0}function computeLaneRuntimeProfile(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects)){let laneSuffix=path103.join(basePath,`lane-${laneIndex}`);envOverrides[envName]=laneSuffix}return{laneIndex,worktreePath,envOverrides}}function allocateStandardLaneIndex(parentSessionID){let current=standardWorktreeLaneIndexBySession.get(parentSessionID)??0;return standardWorktreeLaneIndexBySession.set(parentSessionID,current+1),current}async function createSessionWithinBudget(promise3,label,onLateResolve,timeoutMs=_internals83.worktreeSessionCreateTimeoutMs){let settled=new Promise((resolveState)=>{promise3.then((result)=>resolveState({status:"fulfilled",result}),()=>resolveState({status:"rejected"}))});try{return await withTimeout(promise3,timeoutMs,Error(`${label} deadline expired after ${timeoutMs}ms (worktree.session_create_timeout_ms)`))}catch(error93){let teardown=settled.then(async(state2)=>{if(state2.status==="fulfilled")await onLateResolve?.(state2.result)},()=>{}).catch((teardownError)=>{log(`[worktree-isolation] ${label} late-settle teardown failed: ${teardownError instanceof Error?teardownError.message:String(teardownError)}`)});throw await withTimeout(teardown,_internals83.worktreeSessionCreateSettleGraceMs,Error(`${label} settle grace expired`)).catch(()=>{}),error93}}function resolveSessionCreateTimeoutMs(args2){return args2.config?.worktree?.session_create_timeout_ms??_internals83.worktreeSessionCreateTimeoutMs}async function handleStrandedLane(lane){recordDeadLaneReclaim(lane.directory,{lanePath:lane.lanePath,branchName:lane.branchName,parentSessionId:lane.parentSessionID,taskId:lane.taskId,reason:lane.reason});let session=ensureAgentSession(lane.parentSessionID);pushAdvisory(session,`WORKTREE_LANE_STRANDED: lane ${lane.lanePath} could not be removed (${lane.reason}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`)}function rememberStandardWorktreeDispatch(dispatch){standardWorktreeByCallID.set(dispatch.callID,dispatch)}function resolveRecoveryTaskId(input){return input.planTaskId??input.taskId}function toRecoveryStrategy(strategy){return strategy}function hasStandardWorktreeDispatchCapacity(){return standardWorktreeByCallID.size<MAX_TRACKED_STANDARD_WORKTREE_CALLS}function hasInFlightStandardWorktreeDispatch(parentSessionID){for(let dispatch of standardWorktreeByCallID.values())if(dispatch.parentSessionID===parentSessionID)return!0;for(let record3 of awaitingMergeByCallID.values())if(record3.parentSessionID===parentSessionID)return!0;return!1}function handleStandardWorktreeFailure(parentSessionID,policy,message){if(policy==="required")throw new StandardWorktreeLifecycleError(message);if(hasInFlightStandardWorktreeDispatch(parentSessionID))throw new StandardWorktreeLifecycleError(`STANDARD_WORKTREE_ISOLATION_UNSAFE: ${message} Sibling coder task(s) are isolated in worktrees for this session, so dispatching this coder un-isolated in the main tree would risk a merge-back collision. Wait for in-flight coder task(s) to be reviewed and merged, then retry.`);serializeStandardWorktreeDispatches(parentSessionID,message)}function hardStopStandardWorktreeLifecycle(parentSessionID,message){let session=ensureAgentSession(parentSessionID);throw pushAdvisory(session,message),new StandardWorktreeLifecycleError(message)}function serializeStandardWorktreeDispatches(sessionID,message){if(!rememberStandardWorktreeSerializationSession(sessionID)){let session2=ensureAgentSession(sessionID);pushAdvisory(session2,`${message} Serialization tracking is at capacity (256 sessions active); continuing in normal parallel mode.`);return}standardWorktreeDegradationReasonBySession.set(sessionID,{reason:message,at:Date.now()});let session=ensureAgentSession(sessionID);session.maxConcurrencyOverride=1,pushAdvisory(session,`${message} Serializing standard coder dispatches for this session.`)}function getStandardWorktreeDegradationReason(sessionID){return standardWorktreeDegradationReasonBySession.get(sessionID)}function resetStandardWorktreeIsolationState(){standardWorktreeByCallID.clear(),standardWorktreeSerializationSessions.clear(),serializationStateBySessionID.clear(),standardWorktreeDegradationReasonBySession.clear(),awaitingMergeByCallID.clear(),standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession.clear()}function releaseStandardWorktreeSerialization(sessionID){if(!standardWorktreeSerializationSessions.has(sessionID))return!1;standardWorktreeSerializationSessions.delete(sessionID),serializationStateBySessionID.delete(sessionID),standardWorktreeDegradationReasonBySession.delete(sessionID);let session=ensureAgentSession(sessionID);return session.maxConcurrencyOverride=void 0,pushAdvisory(session,`WORKTREE_SERIALIZATION_RELEASED: ${sessionID} regains parallel dispatch eligibility (release-after-dispatches or TTL).`),!0}function checkStandardWorktreeSerializationRelease(sessionID,config3){let state2=serializationStateBySessionID.get(sessionID);if(!state2)return;let count=config3.serialization_release_after_dispatches??5,ttl=config3.serialization_release_after_ms??60000;if(state2.successfulDispatchesSince>=count){releaseStandardWorktreeSerialization(sessionID);return}if(Date.now()-state2.serializedAt>=ttl)releaseStandardWorktreeSerialization(sessionID)}function rememberStandardWorktreeSerializationSession(sessionID){if(standardWorktreeSerializationSessions.size>=MAX_TRACKED_STANDARD_WORKTREE_CALLS){let evicted=!1;for(let key2 of serializationStateBySessionID.keys())if(!hasInFlightStandardWorktreeDispatch(key2)){standardWorktreeSerializationSessions.delete(key2),serializationStateBySessionID.delete(key2),standardWorktreeDegradationReasonBySession.delete(key2),evicted=!0;break}if(!evicted)return log(`[worktree-isolation] serialization set at cap with all sessions active; refusing eviction for ${sessionID}`),!1}if(standardWorktreeSerializationSessions.add(sessionID),!serializationStateBySessionID.has(sessionID))serializationStateBySessionID.set(sessionID,{sessionID,serializedAt:Date.now(),successfulDispatchesSince:0});return!0}function sanitizeWorktreeTaskId(raw){return raw.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)||"task"}async function preProvisionCollisionCheck(taskId,directory,_sessionId){let proc;try{proc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",directory,"worktree","list","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:WORKTREE_LIST_TIMEOUT_MS})}catch(error93){let detail=`git worktree list could not start in ${directory}: ${error93 instanceof Error?error93.message:String(error93)}`;return log(`[swarm] preProvisionCollisionCheck: ${detail}`),{collision:!1,uncertainty:detail}}let stdout="",stderr="";try{let exitCode=await proc.exited;if(stdout=await proc.stdout.text(),stderr=await proc.stderr.text(),exitCode!==0){if(stderr.toLowerCase().includes("not a git repository"))return{collision:!1};return log(`[swarm] preProvisionCollisionCheck: git worktree list failed (exit ${exitCode}): ${stderr}`),{collision:!1,uncertainty:stderr.trim()||`git worktree list exited ${exitCode}`}}}finally{try{proc.kill()}catch{}}let entries=[],current={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
|
|
1292
1292
|
`)){let line=rawLine.trim();if(line.startsWith("worktree ")){if(current.path)entries.push(current);current={path:line.slice(9),branch:void 0,prunable:!1}}else if(line.startsWith("branch "))current.branch=line.slice(7);else if(line==="prunable"||line.startsWith("prunable "))current.prunable=!0}if(current.path)entries.push(current);for(let entry of entries){if(!entry.branch)continue;if(entry.prunable)continue;let branchName=entry.branch.startsWith("refs/heads/")?entry.branch.slice(11):entry.branch,segments=branchName.split("/");if(segments.length>=4&&segments[0]==="swarm"&&segments[1]==="lane"){if(segments[3]===taskId){let ownerSessionId=segments[2];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}if(segments.length>=3&&segments[0]==="swarm-lane"){if(segments[2]===taskId){let ownerSessionId=segments[1];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}}return{collision:!1}}function isLaneOwnedByCurrentSession(branchName,expectedSessionId){return _internals35.extractSessionId(branchName)===expectedSessionId}async function inspectStandardWorktreeCollisionOwnership2(identity){return(await Promise.resolve().then(() => (init_worktree_collision_ownership(),exports_worktree_collision_ownership))).inspectStandardWorktreeCollisionOwnership(identity)}async function runRecoveryGit(directory,args2,timeoutMs=15000){let proc;try{proc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",directory,...args2],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,env:{...process.env,LC_ALL:"C"}});let exitCode=await proc.exited,stdout=await proc.stdout.text(),stderr=await proc.stderr.text();return{exitCode,stdout,stderr}}catch(error93){return{exitCode:1,stdout:"",stderr:error93 instanceof Error?error93.message:String(error93)}}finally{try{proc?.kill()}catch{}}}async function pathExists3(targetPath){try{return await fs66.stat(targetPath),!0}catch{return!1}}async function buildWorktreeRecoveryPublishIdentity(input){let mergeBase=await runRecoveryGit(input.directory,["merge-base",input.provenance.targetHeadBefore,input.provenance.sourceHead]),mergeBaseOid=mergeBase.stdout.trim();if(mergeBase.exitCode!==0||!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(mergeBaseOid))return;let targetHead=await runRecoveryGit(input.directory,["rev-parse","HEAD"]),targetHeadOid=targetHead.stdout.trim();if(targetHead.exitCode!==0||!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(targetHeadOid))return;return{originalCallID:input.dispatch.callID,parentSessionId:input.dispatch.parentSessionID,taskId:input.taskId,reservationId:input.dispatch.reservationId??`worktree:${input.dispatch.parentSessionID}:${input.taskId}`,generation:input.dispatch.generation??1,canonicalBranch:input.dispatch.canonicalBranch??input.dispatch.handle.branchName,canonicalPath:input.dispatch.canonicalPath??input.dispatch.handle.worktreePath,laneBranch:input.dispatch.handle.branchName,lanePath:input.dispatch.handle.worktreePath,expectedPrimaryHead:input.provenance.targetHeadBefore,sourceBaseOid:mergeBaseOid,sourceHeadOid:input.provenance.sourceHead,targetHeadOid,strategy:toRecoveryStrategy(input.provenance.strategy),...input.conflictFiles&&input.conflictFiles.length>0?{declaredConflictFiles:input.conflictFiles}:{}}}async function publishRecoveryAuthorityForSettlement(input){if(input.dispatch.recoveryClaim||!input.provenance)return{ok:!0};let identity=await _internals83.buildWorktreeRecoveryPublishIdentity({directory:input.directory,dispatch:input.dispatch,taskId:input.taskId,provenance:input.provenance,conflictFiles:input.conflictFiles});if(!identity)return{ok:!1,code:"identity_unavailable",reason:"worktree recovery publish identity could not be derived from the merge provenance"};let published=_internals83.publishWorktreeRecoveryAuthority(input.directory,identity);return published.ok?{ok:!0}:{ok:!1,code:published.code,reason:published.reason}}function isExactRecoveryClaimantStillActive(authority){let claim=authority.claim;if(!claim)return!1;if(standardWorktreeByCallID.has(claim.claimantCallID)||awaitingMergeByCallID.has(claim.claimantCallID))return!0;let childSession=swarmState.agentSessions.get(claim.childSessionId);if(!childSession?.workspaceDirectory?.trim())return!1;return sameProjectRoot(childSession.workspaceDirectory,authority.immutable.lanePath)}function describeRecoveryMutationFailure(input){return`recovery claim ${input.action} failed (${input.code}): ${input.reason}`}function maybeSelectRecoverableAuthority(lookup,collision){if(lookup.status!=="ok")return{status:"uncertain",reason:lookup.reason};let authority=lookup.authorities.find((candidate)=>candidate.status!=="finalized"&&candidate.immutable.laneBranch===collision.existingBranch&&candidate.immutable.lanePath===collision.worktreePath);return authority?{status:"match",authority}:{status:"none"}}async function precreateStandardWorktreeSession(args2){let worktreeConfig=resolveWorktreeIsolationConfig(args2.config);if(worktreeConfig.policy==="disabled")return;if(standardWorktreeSerializationSessions.has(args2.parentSessionID)){if(checkStandardWorktreeSerializationRelease(args2.parentSessionID,worktreeConfig),!standardWorktreeSerializationSessions.has(args2.parentSessionID))return}if(!hasStandardWorktreeDispatchCapacity()){if(worktreeConfig.policy==="required")throw Error("STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");serializeStandardWorktreeDispatches(args2.parentSessionID,"STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");return}let client=swarmState.opencodeClient;if(!client){handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,"STANDARD_WORKTREE_ISOLATION_UNAVAILABLE: OpenCode SDK client is unavailable; standard parallel coder work cannot be isolated.");return}let laneIndex=allocateStandardLaneIndex(args2.parentSessionID),provisioningOwnerIdentity={reservationId:args2.reservationId??`foreground:${args2.parentSessionID}:${resolveRecoveryTaskId(args2)}:${args2.callID}`,generation:Math.max(1,args2.generation??1),branchName:makeWorktreeBranchName(args2.parentSessionID,args2.taskId,{purpose:"lane"})},recoveryLaunch,lifecycleLock=await _internals83.tryAcquireWorktreeLifecycleLock(args2.directory,WORKTREE_LIFECYCLE_LOCK_FILE,"worktree-provisioning",args2.taskId);if(!lifecycleLock.acquired)hardStopStandardWorktreeLifecycle(args2.parentSessionID,"STANDARD_WORKTREE_LIFECYCLE_BUSY: init orphan recovery is active; retry this coder dispatch after recovery completes.");try{let collision=await _internals83.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(collision.uncertainty)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_SCAN_UNCERTAIN: ${collision.uncertainty}. Destructive cleanup and provisioning were blocked.`);if(collision.collision){if(!collision.existingBranch||!collision.worktreePath||!isLaneOwnedByCurrentSession(collision.existingBranch,args2.parentSessionID)){let ownerInfo=collision.ownerSessionId?` owned by session ${collision.ownerSessionId}`:" with uncertain ownership";hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION: task ${args2.taskId} already has a lane on branch ${collision.existingBranch??"unknown"}${ownerInfo}; cleanup and provisioning were blocked.`)}for(let dispatch of _internals83.standardWorktreeByCallID.values())if(dispatch.handle.branchName===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_ACTIVE: branch ${collision.existingBranch} is still tracked by an active standard-worktree dispatch.`);for(let record3 of _internals83.awaitingMergeByCallID.values())if(record3.branch===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_AWAITING_MERGE: branch ${collision.existingBranch} is still awaiting merge-back.`);let recoveryCandidate=maybeSelectRecoverableAuthority(_internals83.lookupWorktreeRecoveryAuthoritiesByTask(args2.directory,{parentSessionId:args2.parentSessionID,taskId:resolveRecoveryTaskId(args2)}),collision);if(recoveryCandidate.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_AUTHORITY_UNCERTAIN: ${recoveryCandidate.reason}. Recovery re-dispatch was blocked.`);if(recoveryCandidate.status==="match"){let recoveredChildSessionId="",claimed;try{claimed=await _internals83.claimWorktreeRecoveryAuthority(args2.directory,{authorityDigest:recoveryCandidate.authority.authorityDigest,claimantCallID:args2.callID,claimantSessionId:args2.parentSessionID,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS,createChildSession:async()=>{let createResult=await createSessionWithinBudget(client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree recovery lane)`},query:{directory:collision.worktreePath}}),"STANDARD_WORKTREE_RECOVERY_SESSION_CREATE",async(result)=>{let lateChildSessionId=result.data?.id;if(lateChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,lateChildSessionId);if(!verification.ok)pushAdvisory(ensureAgentSession(args2.parentSessionID),`WORKTREE_RECOVERY_CHILD_SESSION_LEAKED: recovery child session ${lateChildSessionId} survived verified teardown (${verification.reason}); it holds the lane swarm.db at ${collision.worktreePath}. Retry the dispatch or restart the host to release it.`)}},resolveSessionCreateTimeoutMs(args2));if(recoveredChildSessionId=createResult.data?.id??"",!recoveredChildSessionId){let createError=createResult.error;throw Error(typeof createError==="string"?createError:JSON.stringify(createError??"missing session id"))}return recoveredChildSessionId},revalidateExpiredClaim:async({authority})=>{if(isExactRecoveryClaimantStillActive(authority))return{ok:!1,reason:"expired recovery claim still belongs to a live claimant session or dispatch"};if(authority.immutable.laneBranch!==collision.existingBranch||authority.immutable.lanePath!==collision.worktreePath)return{ok:!1,reason:"preserved lane coordinates drifted before claim transfer"};try{await fs66.stat(authority.immutable.lanePath)}catch{return{ok:!1,reason:"preserved lane path is no longer live"}}let laneHead=await runRecoveryGit(args2.directory,["rev-parse",`${authority.immutable.laneBranch}^{commit}`]);if(laneHead.exitCode!==0||laneHead.stdout.trim()!==authority.immutable.sourceHeadOid)return{ok:!1,reason:"preserved lane head changed since authority publication"};return{ok:!0}}})}catch(error93){if(_internals83.replayWorktreeRecoveryClaimJournal(args2.directory),recoveredChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,recoveredChildSessionId);if(!verification.ok)pushAdvisory(ensureAgentSession(args2.parentSessionID),`WORKTREE_RECOVERY_CHILD_SESSION_LEAKED: recovery child session ${recoveredChildSessionId} survived verified teardown (${verification.reason}); it holds the lane swarm.db at ${collision.worktreePath}. Retry the dispatch or restart the host to release it.`)}hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_SESSION_CREATE_FAILED: ${error93 instanceof Error?error93.message:String(error93)}. The PREPARED claim was rolled back and recovery re-dispatch was blocked.`)}if(!claimed.ok)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_CLAIM_FAILED: ${claimed.reason}. The recovery child session ${recoveredChildSessionId} was created but the preserved lane was not reassigned.`);recoveryLaunch={childSessionId:recoveredChildSessionId,worktreePath:collision.worktreePath,branchName:collision.existingBranch,strategy:recoveryCandidate.authority.immutable.strategy,reservationId:recoveryCandidate.authority.immutable.reservationId,generation:recoveryCandidate.authority.immutable.generation,provisioningOwner:{reservationId:recoveryCandidate.authority.immutable.reservationId,generation:recoveryCandidate.authority.immutable.generation,branchName:collision.existingBranch},canonicalBranch:recoveryCandidate.authority.immutable.canonicalBranch,canonicalPath:recoveryCandidate.authority.immutable.canonicalPath,recoveryClaim:{authorityDigest:recoveryCandidate.authority.authorityDigest,claimRevision:claimed.authority.claim?.claimRevision??recoveryCandidate.authority.claimCursor?.lastClaimRevision??1,rawToken:claimed.rawToken,coordinates:{sourceBaseOid:recoveryCandidate.authority.immutable.sourceBaseOid,sourceHeadOid:recoveryCandidate.authority.immutable.sourceHeadOid,targetHeadOid:recoveryCandidate.authority.immutable.targetHeadOid,strategy:recoveryCandidate.authority.immutable.strategy}}}}if(!recoveryLaunch){let ownership=await _internals83.inspectStandardWorktreeCollisionOwnership({directory:args2.directory,parentSessionId:args2.parentSessionID,taskId:args2.taskId,branchName:collision.existingBranch,worktreePath:collision.worktreePath});if(ownership.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNERSHIP_UNCERTAIN: ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);if(ownership.status==="protected")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PROTECTED: ${ownership.ownerKind} owner is ${ownership.lifecycle}; ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);let collisionPathExists=!0;try{await fs66.stat(collision.worktreePath)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")collisionPathExists=!1;else hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PATH_STAT_FAILED: ${error93 instanceof Error?error93.message:String(error93)}. Destructive cleanup and provisioning were blocked.`)}if(collisionPathExists){let preserveResult=await _internals83.preserveDirtyWorktreeAtPath(collision.worktreePath,collision.existingBranch,"denied",args2.directory,worktreeConfig.worktree_dir);if(preserveResult.outcome==="preserve-failed")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: pre-provision collision for task ${args2.taskId} could not be preserved (${preserveResult.error}). Cleanup and provisioning were blocked.`);closeProjectDb(collision.worktreePath);let removeResult=await _internals83.removeWorktree(collision.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir});if("error"in removeResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_REMOVE_FAILED: ${removeResult.error}. Provisioning was blocked.`);let cleanupResult=await _internals83.postMergeCleanup(args2.directory,collision.existingBranch);if("error"in cleanupResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_BRANCH_CLEANUP_FAILED: ${cleanupResult.error}. Provisioning was blocked.`)}else{let pruneResult=await _internals83.pruneStaleWorktreeMetadata(args2.directory);if("error"in pruneResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PRUNE_FAILED: ${pruneResult.error}. Provisioning was blocked without deleting the lane branch.`)}let verification=await _internals83.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(verification.uncertainty||verification.collision)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_CLEANUP_UNVERIFIED: ${verification.uncertainty??"git still reports the colliding lane after cleanup"}. Provisioning was blocked.`)}}_internals83.recordWorktreeProvisioningOwner(args2.directory,{callID:args2.callID,parentSessionId:args2.parentSessionID,worktreeSessionId:args2.parentSessionID,taskId:args2.taskId,...provisioningOwnerIdentity})}catch(error93){if(error93 instanceof StandardWorktreeLifecycleError)throw error93;hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PERSIST_FAILED: ${error93 instanceof Error?error93.message:String(error93)}.`)}finally{try{await lifecycleLock.lock._release?.()}catch{}}let childSessionId="",handle,mergeStrategy,reservationId,generation,canonicalBranch,canonicalPath,recoveryClaim;if(recoveryLaunch)childSessionId=recoveryLaunch.childSessionId,handle={worktreePath:recoveryLaunch.worktreePath,branchName:recoveryLaunch.branchName,purpose:"lane",id:sanitizeWorktreeTaskId(args2.taskId),sessionId:args2.parentSessionID},mergeStrategy=recoveryLaunch.strategy,reservationId=recoveryLaunch.reservationId,generation=recoveryLaunch.generation,provisioningOwnerIdentity=recoveryLaunch.provisioningOwner,canonicalBranch=recoveryLaunch.canonicalBranch,canonicalPath=recoveryLaunch.canonicalPath,recoveryClaim=recoveryLaunch.recoveryClaim;else{reservationId=args2.reservationId??`foreground:${args2.parentSessionID}:${resolveRecoveryTaskId(args2)}:${args2.callID}`,generation=provisioningOwnerIdentity.generation,canonicalPath=args2.directory;let provisionResult;try{provisionResult=await _internals83.provisionWorktree(args2.directory,args2.taskId,args2.parentSessionID,{purpose:"lane",worktreeDir:worktreeConfig.worktree_dir,mergeStrategy:worktreeConfig.merge_strategy,depsStrategy:worktreeConfig.deps_strategy,scope:args2.scope})}catch(error93){throw _internals83.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity),error93}if("error"in provisionResult){_internals83.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let message=`STANDARD_WORKTREE_PROVISION_FAILED: ${provisionResult.error}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}handle=provisionResult,mergeStrategy=worktreeConfig.merge_strategy,recordLiveLaneOwner(args2.directory,{lanePath:handle.worktreePath,branchName:handle.branchName,sessionId:args2.parentSessionID,taskId:args2.taskId})}let originalPrompt=typeof args2.outputArgs.prompt==="string"?args2.outputArgs.prompt:"";args2.outputArgs.prompt=["<worktree_lane_context>",`authoritative_lane_root: ${JSON.stringify(handle.worktreePath)}`,"All FILE declarations and scope-bound edit/write paths must be workspace-relative to authoritative_lane_root.","Remain in authoritative_lane_root: do not change directory into, or edit/write through, the primary checkout or any other worktree.","Example: FILE: src/example.ts means <authoritative_lane_root>/src/example.ts, never <primary-checkout>/src/example.ts.","Do not declare project-root absolute paths; resolve and operate inside this lane root.","</worktree_lane_context>","",originalPrompt].join(`
|
|
1293
1293
|
`);let laneProfile=computeLaneRuntimeProfile(worktreeConfig.runtime_isolation,laneIndex,handle.worktreePath);if(laneProfile)try{let{writeLaneProfileToDiskReal:writeLaneProfileToDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await writeLaneProfileToDiskReal2(handle.worktreePath,laneProfile.laneIndex,laneProfile.envOverrides)}catch{}if((worktreeConfig.deps_strategy??"skip")==="skip"){let desc=(args2.description??args2.taskId??"").toLowerCase();if(/\btests?\b/.test(desc)||/\bbuild(ing|s)?\b/.test(desc)||/\blint(ing|er)?\b/.test(desc)||/\bchecks?\b/.test(desc)){let session=ensureAgentSession(args2.parentSessionID);pushAdvisory(session,`WORKTREE_DEPS_SKIP: task ${args2.taskId} was provisioned with deps_strategy: 'skip' (default). This task's gates appear to include test/build commands; the lane may lack node_modules. Set worktree.deps_strategy to 'copy' or 'link' (or use a non-worktree lane) if the task requires host dependencies.`)}}if(!recoveryLaunch){let createResult;try{createResult=await createSessionWithinBudget(client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree lane)`},query:{directory:handle.worktreePath}}),"STANDARD_WORKTREE_SESSION_CREATE",async(result)=>{let lateChildSessionId=result.data?.id;if(lateChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,lateChildSessionId);if(!verification.ok)await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:`late child session ${lateChildSessionId} survived verified teardown (${verification.reason})`})}},resolveSessionCreateTimeoutMs(args2))}catch(error93){closeProjectDb(handle.worktreePath);let removal=await _internals83.removeWorktree(handle.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${removalError}`),await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:removalError});_internals83.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${error93 instanceof Error?error93.message:String(error93)}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}if(!createResult?.data?.id){closeProjectDb(handle.worktreePath);let removal=await _internals83.removeWorktree(handle.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${removalError}`),await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:removalError});_internals83.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let createError=createResult.error,message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${typeof createError==="string"?createError:JSON.stringify(createError??"missing session id")}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}childSessionId=createResult.data.id}if(!childSessionId)throw Error("STANDARD_WORKTREE_SESSION_CREATE_FAILED: missing child session id.");args2.outputArgs.task_id=childSessionId,ensureAgentSession(childSessionId,"coder",handle.worktreePath),recordSessionWorkspaceRoot(childSessionId,handle.worktreePath),rememberStandardWorktreeDispatch({callID:args2.callID,parentSessionID:args2.parentSessionID,taskId:args2.taskId,planTaskId:args2.planTaskId,reservationId,generation,provisioningOwner:provisioningOwnerIdentity,canonicalBranch,canonicalPath,handle,mergeStrategy,recoveryClaim,laneIndex,worktree_dir:worktreeConfig.worktree_dir})}async function preserveBackgroundWorktreeOwnershipForCallId(callID){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch)return{outcome:"not-found"};let refProc;try{refProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",error:`git rev-parse could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let ref="";try{let exitCode=await refProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await refProc.stderr.text()||`git rev-parse exited ${exitCode}`};ref=(await refProc.stdout.text()).trim()}finally{try{refProc.kill()}catch{}}if(!ref)return{outcome:"preserve-failed",error:"git rev-parse returned empty"};let session=Buffer.from(dispatch.handle.sessionId,"utf8").toString("base64url"),lane=Buffer.from(dispatch.handle.id,"utf8").toString("base64url"),callDigest=createHash46("sha256").update(callID).digest("hex").slice(0,12),tag=`swarm-preserved-owner/${session}/${lane}/${callDigest}`,tagProc;try{tagProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"tag",tag,ref],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",error:`git tag could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let exitCode=await tagProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await tagProc.stderr.text()||`git tag exited ${exitCode}`}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",tag,ref}}async function preserveDirtyWorktreeForCallId(callID,reason,_directory2,_worktree_dir){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{outcome:"clean",preserved:!1};worktreePath=awaiting.worktreePath,parentSessionID=awaiting.parentSessionID}let statusProc;try{statusProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeForCallId: git status failed for ${callID}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git add failed for ${callID}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedCallID=callID.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for callID ${sanitizedCallID} at ${isoDate}`,commitProc;try{commitProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git commit failed for ${callID}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git rev-parse failed for ${callID}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-${sanitizedCallID}-${shortHash}`,tagProc;try{tagProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git tag failed for ${callID}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_PRESERVED: dispatch ${callID} dirty work preserved as commit ${commitHash} (tag: ${tagName}; reason: ${reason}); worktree will be cleaned.`),{outcome:"preserved",preserved:!0,ref:commitHash}}async function preserveDirtyWorktreeAtPath(worktreePath,branchName,reason,_directory2,_worktree_dir){let statusProc;try{statusProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeAtPath: git status failed for ${worktreePath}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git add failed for ${worktreePath}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedPath=worktreePath.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),sanitizedBranch=branchName.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for worktree ${sanitizedPath} at ${isoDate}`,commitProc;try{commitProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git commit failed for ${worktreePath}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git rev-parse failed for ${worktreePath}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-worktree-${sanitizedBranch}-${shortHash}`,tagProc;try{tagProc=_internals83.bunSpawn([_internals83.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git tag failed for ${worktreePath}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",preserved:!0,ref:commitHash}}async function cleanupStandardWorktreeForCallId(callID,reason,directory,worktree_dir,options){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,branchName,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,branchName=dispatch.handle.branchName,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!1};worktreePath=awaiting.worktreePath,branchName=awaiting.branch,parentSessionID=awaiting.parentSessionID}if(dispatch?.recoveryClaim&&(reason==="denied"||reason==="cancelled")){let renewResult=_internals83.renewWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:callID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS});if(!renewResult.ok){let message=`STANDARD_WORKTREE_RECOVERY_ABORT_RELEASE_FAILED: dispatch ${callID} preserved lane ${worktreePath} (${branchName}) after ${reason}, but ${describeRecoveryMutationFailure({action:"renew",code:renewResult.code,reason:renewResult.reason})}. No tracking teardown was performed.`,session3=ensureAgentSession(parentSessionID);throw pushAdvisory(session3,message),Error(message)}let releaseResult=_internals83.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:callID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken});if(!releaseResult.ok){let message=`STANDARD_WORKTREE_RECOVERY_ABORT_RELEASE_FAILED: dispatch ${callID} preserved lane ${worktreePath} (${branchName}) after ${reason}, but ${describeRecoveryMutationFailure({action:"release",code:releaseResult.code,reason:releaseResult.reason})}. No tracking teardown was performed.`,session3=ensureAgentSession(parentSessionID);throw pushAdvisory(session3,message),Error(message)}standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);return pushAdvisory(session2,`STANDARD_WORKTREE_RECOVERY_ABORT_PRESERVED: dispatch ${callID} released its recovery claim and preserved lane ${worktreePath} (${branchName}) after ${reason}.`),{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!0}}let preserveResult;if(reason==="denied"||reason==="cancelled"){try{preserveResult=await _internals83.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: preserveDirtyWorktreeForCallId threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}if(preserveResult.outcome==="clean")try{preserveResult=await _internals83.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: final preservation check threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}}if(preserveResult&&preserveResult.outcome==="preserve-failed"){standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);return pushAdvisory(session2,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: dispatch ${callID} has dirty uncommitted work but preservation failed (${preserveResult.error}). Cleanup aborted to protect uncommitted work. Investigate and resolve manually. Worktree=${worktreePath}; branch=${branchName}.`),{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!1}}let removedWorktree=!1;try{closeProjectDb(worktreePath);let result=await _internals83.removeWorktree(worktreePath,directory,{force:!0,worktreeDir:worktree_dir});if(!("error"in result))removedWorktree=!0;else if(result.error.includes("is not a working tree")&&await pathExists3(worktreePath)&&isPathUnderSwarmWorktreeBase(worktreePath,directory,worktree_dir?[worktree_dir]:[]))try{await fs66.rm(worktreePath,{recursive:!0,force:!0}),removedWorktree=!await pathExists3(worktreePath)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: residual directory cleanup failed for ${callID}: ${err}`)}}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: removeWorktree failed for ${callID}: ${err}`)}let cleanedBranch=!1;if(options?.retainBranch){let retainedSession=ensureAgentSession(parentSessionID);pushAdvisory(retainedSession,`STANDARD_WORKTREE_BRANCH_RETAINED: dispatch ${callID} removed worktree ${worktreePath} but retained branch ${branchName} (unstaged landing); the branch is the recovery backup until the landed changes are committed.`)}else try{cleanedBranch=!("error"in await _internals83.postMergeCleanup(directory,branchName))}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: postMergeCleanup failed for ${callID}: ${err}`)}standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_CLEANUP: dispatch ${callID} cleaned up (reason: ${reason}); worktree=${worktreePath}; branch=${branchName}.`),{removedWorktree,cleanedBranch,preservedRecoveryLane:!1}}async function abortStandardWorktreeDispatch(callID,reason,directory){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch){let session=ensureAgentSession("unknown");pushAdvisory(session,`STANDARD_WORKTREE_ABORT_NOOP: dispatch ${callID} has no tracked worktree to abort (reason: ${reason}).`);return}await cleanupStandardWorktreeForCallId(callID,reason,directory,dispatch.worktree_dir)}async function finishStandardWorktreeDispatch(directory,dispatch,config3,callID,settlement={}){let wtConfig=config3?resolveWorktreeIsolationConfig(config3):DEFAULT_WORKTREE_ISOLATION_CONFIG,resolvedCallID=callID??dispatch.callID,run=async()=>{let statusKey=dispatch.planTaskId??dispatch.taskId,failRecoverySettlement=(stage,message,provenance)=>{recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage,message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_RECOVERY_MUTATION_FAILED: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; ${message}.`),{outcome:"failed",stage,message,provenance}},renewRecoveryClaimLease=(phase,provenance)=>{if(!dispatch.recoveryClaim)return;let renewed=_internals83.renewWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS});if(renewed.ok)return;return failRecoverySettlement("recovery-claim-renew",`The live recovery lane could not extend its lease ${phase}; ${describeRecoveryMutationFailure({action:"renew",code:renewed.code,reason:renewed.reason})}`,provenance)},releaseRecoveryClaim=(provenance)=>{if(!dispatch.recoveryClaim)return;let released=_internals83.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken});if(released.ok)return;return failRecoverySettlement("recovery-claim-release",`The preserved recovery lane could not release its exact claim after settlement; ${describeRecoveryMutationFailure({action:"release",code:released.code,reason:released.reason})}`,provenance)},publishRecoveryAuthority=async(provenance,conflictFiles)=>{let published=await publishRecoveryAuthorityForSettlement({directory,dispatch,taskId:statusKey,provenance,conflictFiles});if(published.ok)return;return failRecoverySettlement("recovery-authority-publish",`The preserved original lane could not publish recoverable authority; ${describeRecoveryMutationFailure({action:"publish",code:published.code,reason:published.reason})}`,provenance)},preMergeRenewFailure=renewRecoveryClaimLease("before merge-back");if(preMergeRenewFailure)return preMergeRenewFailure;let mergeResult=await(async()=>{if(!dispatch.recoveryClaim)return _internals83.attemptMergeBackFromDirty(dispatch.handle.worktreePath,dispatch.handle.branchName,directory,getMergeStrategy({merge_strategy:dispatch.mergeStrategy}),{operationId:settlement.operationId,resume:settlement.resume,onBeforeMerge:settlement.onBeforeMerge,commitLanding:settlement.commitLanding});let coordinates=dispatch.recoveryClaim.coordinates;if(!coordinates)return{failed:!0,stage:"recovery-coordinates",message:"Claimed recovery lane is missing immutable Git coordinates"};let provenance={operationId:settlement.operationId??`recovery:${dispatch.recoveryClaim.authorityDigest}`,sourceHead:coordinates.sourceHeadOid,targetHeadBefore:coordinates.targetHeadOid,branchName:dispatch.handle.branchName,strategy:coordinates.strategy};if(settlement.onBeforeMerge)await settlement.onBeforeMerge(provenance);let recovered=await _internals83.recoverMergeBackFromImmutableCoordinates(directory,coordinates);if("merged"in recovered&&recovered.merged){if(recovered.sourceCommitOrder&&recovered.rewrittenCommitOrder)dispatch.recoveryClaim.settlement={sourceCommitOrder:recovered.sourceCommitOrder,rewrittenCommitOrder:recovered.rewrittenCommitOrder};return{merged:!0,strategy:recovered.strategy,autoCommitted:!1,cleaned:!0,reconciled:!1,provenance}}if("conflict"in recovered&&recovered.conflict)return{partial:!0,stage:"conflict",autoCommitted:!1,cleaned:!0,message:recovered.message,conflictFiles:recovered.files,provenance};return{failed:!0,stage:"recovery",message:"error"in recovered?recovered.error:"Immutable recovery returned an unexpected result",provenance}})();if("merged"in mergeResult&&mergeResult.merged){let mergedSettlement={outcome:"merged",strategy:mergeResult.strategy,autoCommitted:mergeResult.autoCommitted??!1,cleaned:mergeResult.cleaned??!1,reconciled:mergeResult.reconciled??!1,provenance:mergeResult.provenance};if(settlement.onMerged)try{await settlement.onMerged(mergedSettlement)}catch(error93){let failedSettlement={outcome:"failed",stage:"settlement-persist",message:`Git merge-back succeeded but settlement persistence failed: ${String(error93)}`,provenance:mergeResult.provenance},publishFailure=await publishRecoveryAuthority(mergeResult.provenance);if(publishFailure)failedSettlement.message=`${failedSettlement.message} ${publishFailure.message}`;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)failedSettlement.message=`${failedSettlement.message} ${releaseFailure.message}`;recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:failedSettlement.stage,message:failedSettlement.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_PERSIST_FAILED: task ${dispatch.taskId} landed in ${directory}, but settlement persistence failed; worktree and branch preserved at ${dispatch.handle.worktreePath} (${dispatch.handle.branchName}).`),failedSettlement}let preCleanupRenewFailure=renewRecoveryClaimLease("before cleanup/finalization",mergeResult.provenance);if(preCleanupRenewFailure)return preCleanupRenewFailure;let cleanupResult=await cleanupStandardWorktreeForCallId(resolvedCallID,"success",directory,dispatch.worktree_dir,{retainBranch:mergeResult.strategy==="squash-unstaged"});if(dispatch.recoveryClaim){let request={authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,settlement:dispatch.recoveryClaim.settlement};if(cleanupResult.removedWorktree&&cleanupResult.cleanedBranch){let finalized=_internals83.finalizeWorktreeRecoveryAuthority(directory,request);if(!finalized.ok)return failRecoverySettlement("recovery-claim-finalize",`The merged recovery lane was cleaned up but could not finalize its exact claim; ${describeRecoveryMutationFailure({action:"finalize",code:finalized.code,reason:finalized.reason})}`,mergeResult.provenance)}else{let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure}}clearWorktreeMergeStatus(statusKey);try{let{removeLaneProfileFromDiskReal:removeLaneProfileFromDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await removeLaneProfileFromDiskReal2(dispatch.handle.worktreePath,dispatch.laneIndex)}catch{}let state2=serializationStateBySessionID.get(dispatch.parentSessionID);if(state2)state2.successfulDispatchesSince++,checkStandardWorktreeSerializationRelease(dispatch.parentSessionID,wtConfig);try{verifyReviewerScopeGenerationMergeBack({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID,primaryDirectory:directory})}catch{}return mergedSettlement}if("partial"in mergeResult){let publishFailure=await publishRecoveryAuthority(mergeResult.provenance,mergeResult.conflictFiles);if(publishFailure)return publishFailure;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure;recordWorktreeMergeFailure(statusKey,{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);pushAdvisory(session,`STANDARD_WORKTREE_MERGE_PARTIAL: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; stage: ${mergeResult.stage}; ${mergeResult.message}`+(mergeResult.code?` (code: ${mergeResult.code})`:"")+(mergeResult.recoveryHint?` ${mergeResult.recoveryHint}`:""));try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,autoCommitted:mergeResult.autoCommitted,cleaned:mergeResult.cleaned,conflictFiles:mergeResult.conflictFiles,code:mergeResult.code,recoveryHint:mergeResult.recoveryHint,provenance:mergeResult.provenance}}if("failed"in mergeResult){let publishFailure=await publishRecoveryAuthority(mergeResult.provenance);if(publishFailure)return publishFailure;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure;recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID),location=mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE||mergeResult.stage===SOURCE_WORKTREE_UNCERTAIN_STAGE?`lane worktree ${dispatch.handle.worktreePath} no longer exists`:`preserved at ${dispatch.handle.worktreePath}`;pushAdvisory(session,`STANDARD_WORKTREE_MERGE_FAILED: task ${dispatch.taskId} ${location}; stage: ${mergeResult.stage}; ${mergeResult.message}.`);try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,provenance:mergeResult.provenance}}return{outcome:"failed",stage:"merge",message:"Merge-back returned an unexpected result"}},queuedRun=standardWorktreeMergeQueue.then(run,run);standardWorktreeMergeQueue=queuedRun;let result;try{result=await queuedRun}catch(error93){if(standardWorktreeByCallID.delete(resolvedCallID),awaitingMergeByCallID.delete(resolvedCallID),dispatch.recoveryClaim)try{_internals83.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken})}catch{}let message=`Unexpected worktree settlement failure: ${error93 instanceof Error?error93.message:String(error93)}`;recordWorktreeMergeFailure(dispatch.planTaskId??dispatch.taskId,{outcome:"failed",stage:"merge",message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_FAILED: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; ${message}.`),{outcome:"failed",stage:"merge",message}}if(resolvedCallID)awaitingMergeByCallID.delete(resolvedCallID);return result}async function readLaneEnvFileFromDisk(worktreePath,laneIndex){let envPath=path103.join(worktreePath,".swarm","lanes",`${laneIndex}.env`),content;try{content=await fs66.readFile(envPath,"utf-8")}catch(err){if(err.code==="ENOENT")return{};return log(`[worktree-isolation] failed to read lane env file ${envPath}: ${err.message}`),{}}let result={};for(let rawLine of content.split(`
|
|
1294
1294
|
`)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_RECOVERY_CLAIM_LEASE_MS=300000,WORKTREE_SESSION_CREATE_TIMEOUT_MS=30000,WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS=5000,StandardWorktreeLifecycleError,standardWorktreeDegradationReasonBySession,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals83;var init_worktree_isolation=__esm(()=>{init_constants();init_project_db();init_file_locks();init_lane_owners();init_executor();init_state2();init_bun_compat();init_canonical_root();init_ephemeral_session_teardown();init_git_executable();init_logger();init_timeout();init_worktree();init_merge2();init_reviewer_scope_mergeback();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;StandardWorktreeLifecycleError=class StandardWorktreeLifecycleError extends Error{kind="standard-worktree-lifecycle";constructor(message){super(message);this.name="StandardWorktreeLifecycleError"}};standardWorktreeDegradationReasonBySession=new Map;_internals83={provisionWorktree,removeWorktree,attemptMergeBackFromDirty,recoverMergeBackFromImmutableCoordinates,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,lookupWorktreeRecoveryAuthoritiesByTask,claimWorktreeRecoveryAuthority,renewWorktreeRecoveryClaim,releaseWorktreeRecoveryClaim,finalizeWorktreeRecoveryAuthority,publishWorktreeRecoveryAuthority,replayWorktreeRecoveryClaimJournal,buildWorktreeRecoveryPublishIdentity,preserveDirtyWorktreeAtPath,worktreeSessionCreateTimeoutMs:WORKTREE_SESSION_CREATE_TIMEOUT_MS,worktreeSessionCreateSettleGraceMs:WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS,createSessionWithinBudget,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});var exports_coder_settlement={};__export(exports_coder_settlement,{transferCoderSettlementToBackground:()=>transferCoderSettlementToBackground,settleCoderDispatch:()=>settleCoderDispatch,releaseCoderDispatchOwnership:()=>releaseCoderDispatchOwnership,recoverStaleCoderSettlements:()=>recoverStaleCoderSettlements,recoverCoderSettlement:()=>recoverCoderSettlement,recordCoderMergeProvenance:()=>recordCoderMergeProvenance,listCoderSettlementWalStates:()=>listCoderSettlementWalStates,hasUnattributedEmptyScopeMutation:()=>hasUnattributedEmptyScopeMutation,completeCoderSettlementCleanup:()=>completeCoderSettlementCleanup,beginCoderSettlement:()=>beginCoderSettlement,assertNoUnsettledCoderDispatch:()=>assertNoUnsettledCoderDispatch,abortCoderSettlementIfDoomed:()=>abortCoderSettlementIfDoomed,abortCoderSettlement:()=>abortCoderSettlement,_internals:()=>_internals90});import{spawnSync as spawnSync12}from"node:child_process";import{randomUUID as randomUUID14}from"node:crypto";import{existsSync as existsSync54}from"node:fs";import{readdir as readdir6}from"node:fs/promises";function dispatchKey(directory,taskId,transitionId){return`${canonicalRootKeyFresh(directory)}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal2(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal3(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){try{appendCoreEventSync(directory,{type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}catch(error93){criticalWarn(`[coder-settlement] lifecycle event write failed (${action} ${wal.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}}function baselineAttributionDoomed(baseline){if(baseline.gitHead===null)return!0;return Array.isArray(baseline.changedFiles)&&baseline.changedFiles.length>0}function hasUnattributedEmptyScopeMutation(declaredFiles,rawObservedFiles){return Array.isArray(declaredFiles)&&declaredFiles.length===0&&Array.isArray(rawObservedFiles)&&rawObservedFiles.length>0}function doomedReason(baseline){if(baseline.gitHead===null)return"launch workspace has no git baseline (not a git repository, or git unavailable at dispatch)";return`launch baseline was dirty with ${String(baseline.changedFiles?.length??0)} pre-existing uncommitted/untracked change(s)`}function isProcessAlive3(processId){if(processId===process.pid)return!0;try{return process.kill(processId,0),!0}catch(error93){return error93.code==="EPERM"}}async function scopedObservedFiles(directory,context){let baseline={...context.baseline,directory},observed=await changedFilesSinceSnapshotAsync(directory,baseline);if(!observed||!context.declaredFiles)return null;if(hasUnattributedEmptyScopeMutation(context.declaredFiles,observed))return observed;return observed.filter((filePath)=>isPathWithinDeclaredScope(filePath,context.declaredFiles??[],directory))}function settlementTransitionEvent(wal){return wal.accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:wal.testEngineerExempt===!0,settlementFailed:wal.settlementFailed===!0},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}:{type:"dispatch_no_mutation",agentType:"coder",context:{declaredFiles:wal.context.declaredFiles,settlementTransitionId:wal.transitionId},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}}function withLandedUnstaged(worktree,landedUnstaged){if(worktree===void 0||landedUnstaged===void 0)return worktree;return{...worktree,landedUnstaged}}async function commitPrepared(directory,wal,options){return withTaskEvidenceTransaction(directory,wal.taskId,wal.actor,async(transaction)=>{let lockedWal=await readWal2(walPath(directory,wal.taskId),wal.taskId);if(lockedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(lockedWal.transitionId!==wal.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let transitionEvent=settlementTransitionEvent(lockedWal),snapshot=getTaskWorkflowSnapshot(transaction.read());if(lockedWal.accepted===!0?snapshot.authoritative&&snapshot.state===(lockedWal.settlementFailed===!0?"rework_required":"coder_delegated")&&snapshot.generation===lockedWal.expectedGeneration+1&&snapshot.lastOutcome===(lockedWal.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation")&&snapshot.lastTransitionId===lockedWal.transitionId:snapshot.authoritative&&snapshot.generation===lockedWal.expectedGeneration&&(lockedWal.context.declaredFiles?.length===0?snapshot.noMutationSettlement?.transitionId===lockedWal.transitionId:snapshot.lastOutcome==="dispatch_no_mutation"&&snapshot.lastTransitionId===lockedWal.transitionId)){let evidence2=transaction.read();if(lockedWal.accepted===!0)await ensureTaskGateRequirementsReceiptForSettledTransition(directory,lockedWal.taskId,evidence2,transitionEvent);if(lockedWal.state!=="COMMITTED")lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal,{resumed:!0});return{evidence:evidence2,accepted:lockedWal.accepted===!0,alreadyApplied:!0}}if(lockedWal.state!=="PREPARED"&&!(lockedWal.state==="COMMITTED"&&lockedWal.accepted!==!0&&snapshot.state==="idle"))throw Error("CODER_SETTLEMENT_NOT_PREPARED");let evidence=await transaction.transition(transitionEvent);return lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal),{evidence,accepted:lockedWal.accepted===!0,alreadyApplied:!1}})}async function beginCoderSettlement(options){if(options.context.baseline.gitHead===null){if((await captureWorkspaceSnapshotAsync(options.directory)).gitHead!==null)throw Error(`CODER_SETTLEMENT_BASELINE_UNAVAILABLE: the launch baseline for task ${options.taskId} has no git HEAD — the observation directory (${options.context.baseline.directory}) is not a git repository or git is unavailable there. An unregistered worktree lane (a lane directory that git worktree list does not know) produces exactly this. The task was not dispatched and no settlement state was created; retry the dispatch, or set worktree.policy "disabled" to run coders in the primary tree.`)}let filePath=walPath(options.directory,options.taskId),ownsActiveDispatch=!1;if(await withSettlementLock(options.directory,options.taskId,options.actor,()=>withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{let snapshot=getTaskWorkflowSnapshot(transaction.read());if(snapshot.generation!==options.expectedGeneration)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${options.expectedGeneration}, found ${snapshot.generation}`);let existing=await readWal2(filePath,options.taskId);if(existing!==null){if((existing.state==="DISPATCHED"||existing.state==="PREPARED")&&existing.transitionId!==options.transitionId)throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${existing.transitionId} owns task ${options.taskId}, so transition ${options.transitionId} cannot dispatch it (${filePath}, state ${existing.state}). Wait for the owning transition to settle or run /swarm recover ${options.taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(existing.transitionId===options.transitionId){if(!(existing.actor===options.actor&&existing.expectedGeneration===options.expectedGeneration&&JSON.stringify(existing.context)===JSON.stringify(options.context)&&JSON.stringify(existing.worktree)===JSON.stringify(options.worktree)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(existing.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");ownsActiveDispatch=existing.state==="DISPATCHED"&&existing.runtimeId===runtimeId;return}}await transaction.transition({type:"dispatch_attempted",agentType:"coder",expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),await writeWal3(filePath,{version:1,state:"DISPATCHED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,processId:process.pid,runtimeId,expectedGeneration:options.expectedGeneration,context:options.context,...options.worktree?{worktree:options.worktree}:{},recordedAt:new Date().toISOString()}),ownsActiveDispatch=!0,await appendSettlementEvent(options.directory,"dispatched",{taskId:options.taskId,transitionId:options.transitionId,actor:options.actor})})),ownsActiveDispatch){let key2=dispatchKey(options.directory,options.taskId,options.transitionId);if(!liveDispatches.has(key2)&&liveDispatches.size>=MAX_LIVE_DISPATCHES)throw Error("CODER_SETTLEMENT_CAPACITY_EXCEEDED");liveDispatches.add(key2)}}async function settleCoderDispatch(options){return withSettlementLock(options.directory,options.taskId,"coder-settlement",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,options.observedFiles),accepted=options.accepted||unattributedEmptyScopeMutation,settlementFailed=options.settlementFailed===!0||unattributedEmptyScopeMutation;if(wal.state==="COMMITTED"){if(wal.accepted!==accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==settlementFailed)throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return commitPrepared(options.directory,wal,{landedUnstaged:options.landedUnstaged})}if(wal.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(wal.state==="PREPARED"&&(wal.accepted!==accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==settlementFailed))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");let prepared={...wal,state:"PREPARED",accepted,testEngineerExempt:options.testEngineerExempt,settlementFailed};if(wal.state!=="PREPARED")await writeWal3(filePath,prepared);liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId));try{return await commitPrepared(options.directory,prepared,{landedUnstaged:options.landedUnstaged})}finally{let finalWal=await readWal2(filePath,options.taskId);if(finalWal!==null&&finalWal.state==="COMMITTED")liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId))}})}async function abortCoderSettlement(options){let{outcome,worktree}=await withSettlementLock(options.directory,options.taskId,"coder-abort",async()=>abortDispatchedWalUnderLock(options.directory,options.taskId,options.transitionId,options.reason));if(worktree&&outcome!=="not-dispatched")try{await completeCoderSettlementCleanup(options.directory,options.taskId,options.transitionId)}catch(error93){criticalWarn(`[coder-settlement] aborted settlement worktree cleanup failed for task ${options.taskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}return outcome}async function transferCoderSettlementToBackground(options){return withSettlementLock(options.directory,options.taskId,"coder-background-transfer",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)return"missing";if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="PREPARED")throw Error("CODER_SETTLEMENT_IN_PROGRESS");if(wal.state!=="DISPATCHED")return liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),"already-terminal";let reason="ownership transferred to durable background completion";return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason,cleanupComplete:!0}),liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),await appendSettlementEvent(options.directory,"aborted",wal,{reason,ownership:"background-delegation"}),"transferred"})}async function abortDispatchedWalUnderLock(directory,taskId,transitionId,reason){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="ABORTED")return{outcome:"already-aborted",worktree:wal.worktree!==void 0};if(wal.state!=="DISPATCHED")return{outcome:"not-dispatched",worktree:!1};return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason}),liveDispatches.delete(dispatchKey(directory,taskId,transitionId)),await appendSettlementEvent(directory,"aborted",wal,{reason}),{outcome:"aborted",worktree:wal.worktree!==void 0}}async function abortCoderSettlementIfDoomed(options){let filePath=walPath(options.directory,options.taskId),wal;try{wal=await readWal2(filePath,options.taskId)}catch{return"not-doomed"}if(wal===null)return"not-doomed";if(wal.state==="ABORTED")return"already-aborted";if(wal.transitionId!==options.transitionId||wal.state!=="DISPATCHED")return"not-doomed";if(!baselineAttributionDoomed(wal.context.baseline))return"not-doomed";let outcome=await abortCoderSettlement({directory:options.directory,taskId:options.taskId,transitionId:options.transitionId,reason:doomedReason(wal.context.baseline)});return outcome==="aborted"||outcome==="already-aborted"?outcome:"not-doomed"}async function recordCoderMergeProvenance(options){await withSettlementLock(options.directory,options.taskId,"coder-merge-provenance",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="DISPATCHED"){if(!(JSON.stringify(wal.mergeProvenance)===JSON.stringify(options.provenance)&&JSON.stringify(wal.observedFiles)===JSON.stringify(options.observedFiles)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return}await writeWal3(filePath,{...wal,mergeProvenance:options.provenance,observedFiles:[...options.observedFiles]})})}function probeBranchExists(directory,branchName){let result=spawnSync12(resolveGitExecutable(),["-C",directory,"show-ref","--verify","--quiet",`refs/heads/${branchName}`],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:5000,windowsHide:!0});if(result.error)throw result.error;if(result.status===0)return!0;if(result.status===1)return!1;throw Error(`CODER_SETTLEMENT_CLEANUP_UNCERTAIN: git show-ref exited with status ${String(result.status)}`)}async function cleanupRecoveredWorktree(directory,descriptor,options){let retainBranch=options?.retainBranch??descriptor.landedUnstaged===!0,branchExists=()=>_internals90.branchExists(directory,descriptor.branchName),hasResidue=existsSync54(descriptor.worktreePath)||branchExists(),{awaitingMergeByCallID:awaitingMergeByCallID2,cleanupStandardWorktreeForCallId:cleanupStandardWorktreeForCallId2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation));if(standardWorktreeByCallID2.delete(descriptor.callID),hasResidue)awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});if(hasResidue)await cleanupStandardWorktreeForCallId2(descriptor.callID,"success",directory,descriptor.worktreeDir??void 0,retainBranch?{retainBranch:!0}:void 0);if(existsSync54(descriptor.worktreePath)||branchExists()&&!retainBranch)throw Error("CODER_SETTLEMENT_WORKTREE_CLEANUP_UNVERIFIED");let provisioningOwner=descriptor.provisioningOwner??(descriptor.reservationId!==void 0&&descriptor.generation!==void 0?{reservationId:descriptor.reservationId,generation:descriptor.generation,branchName:descriptor.branchName}:void 0);if(!_internals90.removeWorktreeProvisioningOwner(directory,descriptor.callID,provisioningOwner))throw Error("CODER_SETTLEMENT_OWNER_CLEANUP_FAILED")}async function completeCoderSettlementCleanup(directory,taskId,transitionId){await withSettlementLock(directory,taskId,"coder-cleanup",async()=>{let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==taskId||wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="COMMITTED"&&wal.state!=="ABORTED")throw Error("CODER_SETTLEMENT_NOT_COMMITTED");if(!wal.worktree||wal.cleanupComplete===!0)return;await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0})})}async function selfHealMissingLaneWorktree(directory,filePath,taskId,transitionId,descriptor,detail){if(existsSync54(descriptor.worktreePath))return!1;if(_internals90.branchExists(directory,descriptor.branchName))return!1;let reason=`CODER_SETTLEMENT_SELF_HEALED_MISSING_WORKTREE: ${detail}`;if((await abortDispatchedWalUnderLock(directory,taskId,transitionId,reason)).outcome==="not-dispatched")return!1;try{await cleanupRecoveredWorktree(directory,descriptor);let healedWal=await readWal2(filePath,taskId);if(healedWal!==null)await writeWal3(filePath,{...healedWal,cleanupComplete:!0})}catch(error93){criticalWarn(`[coder-settlement] self-healed task ${taskId} but residual cleanup failed: ${error93 instanceof Error?error93.message:String(error93)}`)}let message=`STALE_CODER_SETTLEMENT_SELF_HEALED: task ${taskId} was blocked by a coder settlement whose lane worktree "${descriptor.worktreePath}" and lane branch "${descriptor.branchName}" no longer exist. Nothing was recoverable, so the write-ahead log at "${filePath}" was marked terminal (ABORTED) and the task was unblocked. Re-dispatch the task if its work still needs doing.`;return criticalWarn(message),advisoryWarn(message),!0}async function recoverCoderSettlement(directory,taskId){return withSettlementLock(directory,taskId,"coder-recovery",async()=>{let filePath=walPath(directory,taskId),existingWal=await readWal2(filePath,taskId);if(existingWal===null)return null;let wal=existingWal;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED"){if(wal.worktree&&wal.cleanupComplete!==!0)await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0});return null}let key2=dispatchKey(directory,taskId,wal.transitionId);if(liveDispatches.has(key2)||wal.processId!==process.pid&&isProcessAlive3(wal.processId))throw Error(`CODER_DISPATCH_IN_PROGRESS: transition ${wal.transitionId} still owns task ${taskId} (${filePath}, state ${wal.state}, pid ${wal.processId}). Wait for that dispatch to settle or run /swarm recover ${taskId} (or /swarm reset-session) to unwedge it; do not remove the WAL by hand.`);if(wal.state==="DISPATCHED"){if(wal.worktree){let worktree=wal.worktree,observed2=wal.observedFiles??await scopedObservedFiles(worktree.worktreePath,wal.context);if(observed2===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for isolated task ${taskId} could not attribute worktree changes to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);let unattributedEmptyScopeMutation2=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,observed2),accepted=observed2.length>0||unattributedEmptyScopeMutation2,settlementFailed=wal.settlementFailed===!0||unattributedEmptyScopeMutation2;if(wal.mergeProvenance){let landed=await reconcileLandedMerge(directory,wal.mergeProvenance);if(landed.landed){let landedUnstaged=landed.method==="worktree-match";wal={...wal,state:"PREPARED",observedFiles:observed2,accepted,settlementFailed,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal);let committed2=await commitPrepared(directory,wal,{landedUnstaged});await cleanupRecoveredWorktree(directory,worktree,{retainBranch:landedUnstaged});let reconciledWal=await readWal2(filePath,taskId);if(reconciledWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...reconciledWal,cleanupComplete:!0}),committed2}if(landed.error)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} could not reconcile the landed merge (${filePath}, state ${wal.state}): ${landed.error}. Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}let{awaitingMergeByCallID:awaitingMergeByCallID2,finishStandardWorktreeDispatch:finishStandardWorktreeDispatch2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation)),descriptor=wal.worktree,reconstructedDispatch={callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID2.delete(descriptor.callID),awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let recovered=null,mergeResult=await finishStandardWorktreeDispatch2(directory,reconstructedDispatch,void 0,descriptor.callID,{operationId:wal.transitionId,...wal.mergeProvenance?{resume:wal.mergeProvenance}:{},onBeforeMerge:async(provenance)=>{wal={...wal,mergeProvenance:provenance,observedFiles:observed2},await writeWal3(filePath,wal)},onMerged:async(mergedResult)=>{wal={...wal,state:"PREPARED",accepted,settlementFailed,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal),recovered=await commitPrepared(directory,wal,{landedUnstaged:mergedResult.strategy==="squash-unstaged"})}});if(mergeResult.outcome!=="merged"||recovered===null){if(mergeResult.outcome==="failed"&&mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE&&await selfHealMissingLaneWorktree(directory,filePath,taskId,wal.transitionId,descriptor,mergeResult.message))return null;throw Error(`CODER_SETTLEMENT_MERGE_RECOVERY_REQUIRED: transition ${wal.transitionId} for task ${taskId} worktree merge-back did not reach merged (${filePath}, state ${wal.state}, outcome ${mergeResult.outcome}${mergeResult.outcome==="failed"&&mergeResult.message?`: ${mergeResult.message}`:""}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}await cleanupRecoveredWorktree(directory,descriptor,{retainBranch:mergeResult.strategy==="squash-unstaged"});let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...committedWal,cleanupComplete:!0}),recovered}let rawObserved=await changedFilesSinceSnapshotAsync(directory,wal.context.baseline),unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,rawObserved),observed;if(rawObserved===null){if(baselineAttributionDoomed(wal.context.baseline)){let aborted3=await abortDispatchedWalUnderLock(directory,taskId,wal.transitionId,doomedReason(wal.context.baseline));if(aborted3.outcome==="aborted"||aborted3.outcome==="already-aborted")return null}observed=null}else if(wal.context.declaredFiles===null)observed=[];else observed=unattributedEmptyScopeMutation?rawObserved:rawObserved.filter((filePath2)=>isPathWithinDeclaredScope(filePath2,wal.context.declaredFiles??[],directory));if(observed===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} workspace changes could not be attributed to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);wal={...wal,state:"PREPARED",accepted:observed.length>0,settlementFailed:wal.settlementFailed===!0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed)},await writeWal3(filePath,wal)}let committed=await commitPrepared(directory,wal);if(wal.worktree){await cleanupRecoveredWorktree(directory,wal.worktree);let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");await writeWal3(filePath,{...committedWal,cleanupComplete:!0})}return committed})}function releaseCoderDispatchOwnership(directory,taskId,transitionId){liveDispatches.delete(dispatchKey(directory,taskId,transitionId))}async function assertNoUnsettledCoderDispatch(directory,taskId){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)return;if(wal.state==="DISPATCHED"||wal.state==="PREPARED")throw Error(`CODER_SETTLEMENT_RECOVERY_REQUIRED: transition ${wal.transitionId} must settle before task ${taskId} can change plan status (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry.`)}async function listCoderSettlementWalStates(directory){let entries;try{let dirPath=validateSwarmPath(directory,"coder-settlements");entries=await readdir6(dirPath)}catch{return{states:[],truncated:!1}}let matching=entries.filter((entry)=>SETTLEMENT_WAL_FILE_PATTERN.test(entry)),states=[];for(let entry of matching.sort().slice(0,MAX_SETTLEMENT_WAL_SCAN)){let taskId=entry.slice(0,-5);try{let wal=await readWal2(walPath(directory,taskId),taskId);if(wal===null)continue;states.push({taskId,state:wal.state,transitionId:wal.transitionId,processId:wal.processId,recordedAt:wal.recordedAt,accepted:wal.accepted===!0?!0:void 0,declaredFiles:wal.context?.declaredFiles??null,expectedGeneration:wal.expectedGeneration,ownedInProcess:liveDispatches.has(dispatchKey(directory,taskId,wal.transitionId)),ownedByLiveForeignPid:wal.processId!==process.pid&&isProcessAlive3(wal.processId)})}catch{states.push({taskId,state:"unreadable",ownedInProcess:!1,ownedByLiveForeignPid:!1})}}return{states,truncated:matching.length>MAX_SETTLEMENT_WAL_SCAN}}async function recoverStaleCoderSettlements(directory,options){let{states:listed,truncated}=await listCoderSettlementWalStates(directory),filter=options?.taskIds?new Set(options.taskIds):void 0,results=[];for(let entry of listed){if(filter&&!filter.has(entry.taskId))continue;if(entry.state==="unreadable"){results.push({taskId:entry.taskId,outcome:"unreadable_wal"});continue}if(entry.state==="ABORTED"||entry.state==="COMMITTED"){try{await _internals90.recoverCoderSettlement(directory,entry.taskId),results.push({taskId:entry.taskId,outcome:"already_terminal",state:entry.state})}catch(error93){results.push({taskId:entry.taskId,outcome:"error",message:error93 instanceof Error?error93.message:String(error93)})}continue}if(entry.ownedInProcess&&options?.force!==!0){results.push({taskId:entry.taskId,outcome:"owned_in_process",transitionId:entry.transitionId??""});continue}if(entry.ownedByLiveForeignPid){results.push({taskId:entry.taskId,outcome:"owned_by_live_foreign_pid",processId:entry.processId??-1});continue}let forced=entry.ownedInProcess&&options?.force===!0;if(forced&&entry.transitionId)releaseCoderDispatchOwnership(directory,entry.taskId,entry.transitionId),await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId,actor:"swarm-recovery"},{forced:!0,stage:"ownership-release"});try{let recovered=await _internals90.recoverCoderSettlement(directory,entry.taskId);if(recovered===null){let current=null;try{current=await readWal2(walPath(directory,entry.taskId),entry.taskId)}catch{current=null}if(current&&(current.state==="COMMITTED"||current.state==="ABORTED")){results.push({taskId:entry.taskId,outcome:"already_terminal",state:current.state});continue}results.push({taskId:entry.taskId,outcome:"error",message:"settlement WAL disappeared during recovery"});continue}await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,accepted:recovered.accepted,previousTransitionId:entry.transitionId??"",previousState:entry.state,...typeof entry.expectedGeneration==="number"?{expectedGeneration:entry.expectedGeneration}:{}}),results.push({taskId:entry.taskId,outcome:"recovered",accepted:recovered.accepted,forced})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendSettlementEvent(directory,"recovery-failed",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,error:message}),results.push({taskId:entry.taskId,outcome:"error",message})}}return{results,truncated}}var LIVE_DISPATCHES_SYMBOL,globalRegistry3,liveDispatches,runtimeId,MAX_LIVE_DISPATCHES=512,MAX_SETTLEMENT_WAL_SCAN=200,SETTLEMENT_WAL_FILE_PATTERN,_internals90;var init_coder_settlement=__esm(()=>{init_workspace_snapshot();init_core_events();init_gate_evidence();init_gate_evidence_classification();init_worktree_provisioning_owner();init_utils2();init_file_locks();init_path_identity();init_warning_buffer();init_canonical_root();init_git_executable();init_logger();init_merge2();init_workflow_wal_file();LIVE_DISPATCHES_SYMBOL=Symbol.for("opencode-swarm.workflow.coder-settlement.live-dispatches"),globalRegistry3=globalThis;if(!globalRegistry3[LIVE_DISPATCHES_SYMBOL])globalRegistry3[LIVE_DISPATCHES_SYMBOL]=new Set;liveDispatches=globalRegistry3[LIVE_DISPATCHES_SYMBOL],runtimeId=randomUUID14();SETTLEMENT_WAL_FILE_PATTERN=/^[\w.\-:]+\.json$/;_internals90={liveDispatches,removeWorktreeProvisioningOwner,branchExists:probeBranchExists,recoverCoderSettlement}});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,replacePendingBackgroundAdvisory:()=>replacePendingBackgroundAdvisory,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,registerStaleSweepObserver:()=>registerStaleSweepObserver,registerLegacyCoderSettlementReconciler:()=>registerLegacyCoderSettlementReconciler,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegationsDetailed:()=>readDelegationsDetailed,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,publishPrReviewResultReceipt:()=>publishPrReviewResultReceipt,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,markLegacyCoderSettlementTransferPending:()=>markLegacyCoderSettlementTransferPending,maintainBackgroundDelegations:()=>maintainBackgroundDelegations,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,isTerminalDelegationStatus:()=>isTerminalDelegationStatus,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationIdDetailed:()=>findByCorrelationIdDetailed,findByCorrelationId:()=>findByCorrelationId,findByBatchIdDetailed:()=>findByBatchIdDetailed,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,clearLegacyCoderSettlementTransferPending:()=>clearLegacyCoderSettlementTransferPending,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildTypedDelegationTerminal:()=>buildTypedDelegationTerminal,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_internals:()=>_internals91,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER:()=>LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER,DELEGATION_READ_RETRY_DELAY_MS:()=>DELEGATION_READ_RETRY_DELAY_MS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATION_LEASE_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MS,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash47}from"node:crypto";import*as fs67 from"node:fs";import*as path104 from"node:path";import{isDeepStrictEqual}from"node:util";function clampReservationLeaseMs(leaseMs){if(leaseMs===void 0)return BACKGROUND_CODER_RESERVATION_LEASE_MS;if(!Number.isFinite(leaseMs))return BACKGROUND_CODER_RESERVATION_LEASE_MS;return Math.min(Math.max(Math.round(leaseMs),BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS),BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS)}function isValidReservationGeneration(generation){return generation===void 0||Number.isInteger(generation)&&generation>=1&&generation<=MAX_BACKGROUND_DELEGATION_GENERATION}function storePath5(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath2(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function importedShadowPath2(filePath){return`${filePath}.imported`}function projectionMarkerPath2(filePath){return`${filePath}.sqlite-projection`}function coordinationReservationLeaseKey(reservation){return{namespace:RESERVATION_LEASE_NAMESPACE,entityKey:reservation.reservationId,generation:reservation.generation??1,ownerToken:reservation.reservationId}}function releaseReservationLeaseIfPresent(directory,reservation){let leaseKey=coordinationReservationLeaseKey(reservation),existing=getCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey);if(!existing)return;if(existing.generation!==leaseKey.generation||existing.ownerToken!==leaseKey.ownerToken||!releaseCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey,leaseKey.generation,leaseKey.ownerToken))throw Error(`reservation lease authority mismatch for ${reservation.reservationId}`)}function coordinationRowsToDelegations(directory){if(!projectDbExists(directory))return null;try{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);return rows.map((row)=>{let parsed=RecordSchema2.safeParse(JSON.parse(row.payload));if(!parsed.success)throw Error(`delegation coordination row failed schema validation for ${row.entityKey}`);if(parsed.data.correlationId!==row.entityKey)throw Error(`delegation coordination row authority binding mismatch: payload correlationId does not equal entity key ${row.entityKey}`);if(Math.max(parsed.data.generation??1,1)!==row.generation)throw Error(`delegation coordination row authority binding mismatch: payload generation does not equal row generation for ${row.entityKey}`);if(parsed.data.status!==row.status)throw Error(`delegation coordination row authority binding mismatch: payload status does not equal row status for ${row.entityKey}`);return parsed.data}).sort((left,right)=>left.createdAt===right.createdAt?left.correlationId.localeCompare(right.correlationId):left.createdAt-right.createdAt)}catch(error93){return recordLedgerUncertainty(directory,error93 instanceof Error?error93.message:String(error93),"coordination-read"),null}}function archiveShadowFileBestEffort2(filePath){if(!fs67.existsSync(filePath))return;let importedPath=importedShadowPath2(filePath);try{if(fs67.existsSync(importedPath))return;fs67.renameSync(filePath,importedPath)}catch(error93){warn(`[background] shadow archive failed for ${path104.basename(filePath)}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function writeDelegationShadowProjection(directory,records){ensureSwarmDir4(directory);let payload=records.map((record3)=>JSON.stringify(record3)).join(`
|
|
@@ -7856,7 +7856,7 @@ Ignoring will not affect already-tracked files. To stop tracking them, run:
|
|
|
7856
7856
|
`:""),findingsDigest=createHash117("sha256").update(serializedFindings,"utf8").digest("hex"),criticSettlements;if(findingsInput.boundary==="post_critic")try{let authoritativeCriticVerdicts=existing.some((record3)=>record3.boundary==="post_reviewer"&&record3.next_action==="route_to_critic")?await readAuthoritativePrReviewCriticVerdicts(directory,sessionID):new Map;criticSettlements=assertCriticSettlements(findingsInput.records,existing,authoritativeCriticVerdicts)}catch(error93){return withPartialAdmissionRollback(operationFailure("validate",relativeFindingsPath.split(path377.sep).join("/"),"an authoritative critic settlement matching the authenticated critic verdict map",error93))}if(!isExactReplay){let serializedBytes=Buffer.byteLength(serializedFindings,"utf8");if(serializedBytes>PR_REVIEW_FINDINGS_MAX_BYTES)return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError("records",`a complete findings artifact at most ${PR_REVIEW_FINDINGS_MAX_BYTES} UTF-8 bytes`,`${serializedBytes} bytes`)));try{await _internals314.atomicWrite(findingsPath,serializedFindings)}catch(error93){return withPartialAdmissionRollback(operationFailure("write",relativeFindingsPath.split(path377.sep).join("/"),"an atomic findings checkpoint write",error93))}}let latest2=latestFindings(allRecords);if(findingsInput.boundary==="post_critic")try{let synthesis=synthesizePrReviewFindings({candidates:policyCandidates([...latest2.values()],sessionID,findingsInput.boundary)});await persistReviewOutcome({projectRoot:directory,routeReceipt:{kind:"pr_review_finding_policy",version:1,sessionId:sessionID,taskId:resolvedRunId,boundary:findingsInput.boundary,prHeadSha:state2.prHeadSha,findingsPath:relativeFindingsPath.split(path377.sep).join("/"),findingsDigest},synthesis:{...synthesis,criticSettlements}})}catch(error93){return withPartialAdmissionRollback(operationFailure("persist",`pr-review/${resolvedRunId}/finding-policy.json`,"an authoritative version-1 critic settlement and finding-policy evidence record",error93))}let handoffRequired=deriveFeedbackHandoffFindingIds([...latest2.values()]).length>0;if(!isCommittedReplay)try{await markPrReviewArtifactBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,relativeFindingsPath.split(path377.sep).join("/"),findingIds,handoffRequired)}catch(error93){return withPartialAdmissionRollback(operationFailure("update",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,`a durable ${findingsInput.boundary} boundary receipt`,error93))}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeFindingsPath.split(path377.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,replayed:isExactReplay,handoff_required:handoffRequired,...state2.prReviewPartialBaseCoverage?{partial_base_coverage:{unresolved_dimensions:normalizePrReviewPartialBaseCoverageRecord(state2.prReviewPartialBaseCoverage).unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),path:state2.prReviewCoverageDisclosurePath,digest:state2.prReviewCoverageDisclosureDigest}}:{}},null,2)}let latest=latestFindings(existing),actionableIds=deriveFeedbackHandoffFindingIds([...latest.values()]),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`field handoff.finding_ids: expected authoritative actionable set [${actionableIds.join(", ")||"(none)"}], got requested [${requestedIds.join(", ")||"(none)"}]`);let relativeHandoffPath=path377.join("pr-review",resolvedRunId,"feedback-handoff.json"),handoffPath;try{handoffPath=validateSwarmPath(directory,relativeHandoffPath)}catch(error93){return operationFailure("resolve",relativeHandoffPath.split(path377.sep).join("/"),"a contained path below the project .swarm directory",error93)}let handoffRecord={schema_version:1,run_id:resolvedRunId,pr_head_sha:state2.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},comparableHandoff=(record3)=>({schema_version:record3.schema_version,run_id:record3.run_id,pr_head_sha:record3.pr_head_sha,pr_url:record3.pr_url,finding_ids:record3.finding_ids,summary:record3.summary,provenance:record3.provenance}),handoffsMatch=(existing2)=>JSON.stringify(comparableHandoff(existing2))===JSON.stringify(comparableHandoff(handoffRecord)),readPersistedHandoff=async()=>{let raw=await readBoundedUtf8File2(handoffPath,PR_REVIEW_HANDOFF_MAX_BYTES,"handoff artifact"),decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`invalid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}let validated=PersistedHandoffSchema.safeParse(decoded);if(!validated.success)throw Error(`schema mismatch: ${formatPrReviewValidationIssues(validated.error.issues,decoded).join("; ")}`);return validated.data},existingHandoff=null;try{existingHandoff=await readPersistedHandoff()}catch(error93){if(error93.code!=="ENOENT")return failure3(`operation read path "${relativeHandoffPath.split(path377.sep).join("/")}": expected bounded JSON matching the persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(existingHandoff){if(!handoffsMatch(existingHandoff))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting handoff content")}else{let serializedHandoff=`${JSON.stringify(handoffRecord,null,2)}
|
|
7857
7857
|
`,serializedHandoffBytes=Buffer.byteLength(serializedHandoff,"utf8");if(serializedHandoffBytes>PR_REVIEW_HANDOFF_MAX_BYTES)return failure3(formatPrReviewRuntimeFieldError("handoff",`a persisted handoff artifact at most ${PR_REVIEW_HANDOFF_MAX_BYTES} UTF-8 bytes`,`${serializedHandoffBytes} bytes`));let created;try{created=await _internals314.atomicCreate(handoffPath,serializedHandoff)}catch(error93){return operationFailure("create",relativeHandoffPath.split(path377.sep).join("/"),"an atomic create-only handoff artifact",error93)}if(!created){let raced;try{raced=await readPersistedHandoff()}catch(error93){return failure3(`operation read path "${relativeHandoffPath.split(path377.sep).join("/")}": expected the concurrently persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(!handoffsMatch(raced))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting concurrent handoff content")}}let alreadyOffered;try{alreadyOffered=(await markPrReviewHandoffComplete(directory,sessionID,resolvedRunId,relativeHandoffPath.split(path377.sep).join("/"))).alreadyOffered}catch(error93){return operationFailure("update",`pr-review/${resolvedRunId}/feedback-consent.json and pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a matching durable consent offer and handoff receipt",error93)}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeHandoffPath.split(path377.sep).join("/"),finding_count:actionableIds.length,already_offered:alreadyOffered,confirmation_command:`/swarm pr-feedback ${parsed.data.handoff.pr_url} continue from .swarm/${relativeHandoffPath.split(path377.sep).join("/")}`},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(PrReviewFindingSchema).min(1).max(1000).optional(),partial_base_coverage:PrReviewPartialBaseCoverageSchema.optional(),handoff:PrReviewHandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_logger();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID49}from"node:crypto";import fs233 from"node:fs";import path378 from"node:path";var _internals315={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase,resolveMergeBaseAsync:resolveExactMergeBaseAsync,markPrReviewTriggerEvaluationComplete,findByBatchIdDetailed,readPrWorkflowGateState};function comparableTriggerReceipt(receipt){return JSON.stringify({...receipt,evaluated_at:void 0,base_verification:void 0})}async function readBoundedTriggerReceipt(destination){let stat25=await fs233.promises.stat(destination);if(!stat25.isFile()||stat25.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt is not a bounded regular file (max ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes)`);let raw=await fs233.promises.readFile(destination,"utf8"),bytes=Buffer.byteLength(raw,"utf8");if(bytes>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt exceeds ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes after read (got ${bytes})`);let decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`trigger evaluation receipt is not valid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsePrReviewTriggerReceipt(decoded),decoded.schema_version!==2)throw Error("trigger evaluation receipt must use schema_version 2");return decoded}async function createTriggerReceipt(destination,content){let parent=path378.dirname(destination),tempPath=path378.join(parent,`.trigger-eval.${randomUUID49()}.tmp`);await fs233.promises.mkdir(parent,{recursive:!0});try{await fs233.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs233.promises.link(tempPath,destination),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs233.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals315.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals315.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals315.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var REVISION_DIGEST_RESOLUTION_ATTEMPTS=2;async function resolveCurrentRevisionDigestWithRetry(directory,prHeadSha){for(let attempt=1;attempt<=REVISION_DIGEST_RESOLUTION_ATTEMPTS;attempt+=1){let digest5=await resolveCurrentRevisionDigest(directory,prHeadSha);if(digest5)return digest5}return null}async function resolveReviewMergeBase(directory,baseRef,prHeadSha){if(_internals315.resolveMergeBase!==resolveExactMergeBase)return _internals315.resolveMergeBase(directory,baseRef,prHeadSha);return _internals315.resolveMergeBaseAsync(directory,baseRef,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(formatPrReviewRuntimeFieldError("pr_head_sha",`"${gateState.prHeadSha}"`,parsed.data.pr_head_sha));try{await assertPrReviewBaseCoverageSettled2(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch — dispatch the first swarm-pr-review:micro batch with the complete trigger_evaluation parameter on dispatch_lanes_async; that dispatch freezes the ledger this tool then persists");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigestWithRetry(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4(`Active PR_REVIEW trigger evaluation could not bind the current exact revision digest for pr_head_sha "${parsed.data.pr_head_sha}" after ${REVISION_DIGEST_RESOLUTION_ATTEMPTS} attempts. A null digest collapses several causes: the bounded git call timed out, the git process failed to spawn, the working tree could not be read, or pr_head_sha was rejected as an unsafe revision token. This fails closed on purpose and has no bound-value fallback — no independently-bound durable PR_REVIEW revision digest exists to compare against, so accepting an unresolved digest would let a lane artifact self-certify its own revision. Nothing was persisted, so this call is retryable as-is. Recovery: confirm the checkout is readable and pr_head_sha exists here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let citedLaneOwnership=new Map,coverageDegradations=[],countFamilyDispatchAttempts=(state2,triggerId,prHeadSha)=>(state2?.prReviewMicroFamilyDispatches??[]).filter((dispatchRecord)=>dispatchRecord.prHeadSha===prHeadSha&&dispatchRecord.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:lane.workflowLane?[lane.workflowLane]:[]).includes(triggerId)));for(let row of validatedRows){if(row.result!=="MATCHED")continue;let batchRead=_internals315.findByBatchIdDetailed(directory,row.source_batch_id,{parentSessionId:sessionID});if(batchRead.status==="uncertain")return failure4(`MATCHED trigger ${row.trigger_id} cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Nothing was persisted, so this call is retryable as-is once the store is readable.`);let record3=batchRead.value.find((candidate2)=>candidate2.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null,provenanceFailure=!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha,laneAlreadySubmittedReceipt=!!record3?.result?.prReviewResultReceipt||!!record3?.terminalResult?.result.prReviewResultReceipt,deadFamilyRecordShape=provenanceFailure&&!laneAlreadySubmittedReceipt&&!!record3&&record3.mode==="swarm-pr-review:micro"&&recordOwnedLanes.includes(row.trigger_id)&&(record3.status==="stale"||record3.status==="error")&&record3.result?.workflowLaneFailureClass==="liveness"&&!record3.result?.outputRef?.trim()&&!outputArtifact&&record3.workspace?.prHeadSha===parsed.data.pr_head_sha&&record3.workspace?.gitHead===parsed.data.pr_head_sha,snapshotFamilyAttempts=countFamilyDispatchAttempts(gateState,row.trigger_id,parsed.data.pr_head_sha),citedBatchAmongRecordedAttempts=snapshotFamilyAttempts.some((dispatchRecord)=>dispatchRecord.batchId===row.source_batch_id),deadFamilyRetryBudgetExhausted=snapshotFamilyAttempts.length>=1+PR_REVIEW_MICRO_FAMILY_RETRY_BUDGET&&citedBatchAmongRecordedAttempts,livenessTerminalDead=deadFamilyRecordShape&&deadFamilyRetryBudgetExhausted;if(deadFamilyRecordShape&&!deadFamilyRetryBudgetExhausted)return failure4(snapshotFamilyAttempts.length<1+PR_REVIEW_MICRO_FAMILY_RETRY_BUDGET?`MATCHED trigger ${row.trigger_id} cites a liveness-dead micro lane, but the dead-family disclosure requires the bounded retry budget (initial dispatch plus ${PR_REVIEW_MICRO_FAMILY_RETRY_BUDGET} retries) to be exhausted first: only ${snapshotFamilyAttempts.length} dispatch attempt(s) for this family are recorded in gate state for pr_head_sha "${parsed.data.pr_head_sha}"${citedBatchAmongRecordedAttempts?"":`, and the cited batch "${row.source_batch_id}" is not among them`}. Nothing was persisted, so this call is retryable as-is. Recovery: re-dispatch the family (each micro dispatch_lanes acknowledgment records one attempt) or restart with abort_pr_workflow (kind "recovery").`:`MATCHED trigger ${row.trigger_id} cites a liveness-dead micro lane whose batch "${row.source_batch_id}" is not among the recorded dispatch attempts for this family under pr_head_sha "${parsed.data.pr_head_sha}", so retry-budget exhaustion cannot be attributed to the cited lane. Nothing was persisted, so this call is retryable as-is. Recovery: re-dispatch the family or restart with abort_pr_workflow (kind "recovery").`);if(provenanceFailure&&!livenessTerminalDead)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a verifiable micro-lane provenance chain`);if(livenessTerminalDead){let freshRead=_internals315.findByBatchIdDetailed(directory,row.source_batch_id,{parentSessionId:sessionID});if(freshRead.status==="uncertain")return failure4(`MATCHED trigger ${row.trigger_id} cannot be validated: the delegation store is unreadable after ${freshRead.attempts} attempts (${freshRead.reason}); the batch's records are UNKNOWN, not absent. Nothing was persisted, so this call is retryable as-is once the store is readable.`);let freshRecord2=freshRead.value.find((candidate2)=>candidate2.laneId===row.source_lane_id),freshOwnedLanes=freshRecord2?.ownedWorkflowLanes?.length?freshRecord2.ownedWorkflowLanes:freshRecord2?.workflowLane?[freshRecord2.workflowLane]:[],freshAlreadySubmittedReceipt=!!freshRecord2?.result?.prReviewResultReceipt||!!freshRecord2?.terminalResult?.result.prReviewResultReceipt;if(!(!!freshRecord2&&freshRecord2.mode==="swarm-pr-review:micro"&&freshOwnedLanes.includes(row.trigger_id)&&(freshRecord2.status==="stale"||freshRecord2.status==="error")&&freshRecord2.result?.workflowLaneFailureClass==="liveness"&&!freshRecord2.result?.outputRef?.trim()&&freshRecord2.workspace?.prHeadSha===parsed.data.pr_head_sha&&freshRecord2.workspace?.gitHead===parsed.data.pr_head_sha&&!freshAlreadySubmittedReceipt))return failure4(`MATCHED trigger ${row.trigger_id} does not reference a verifiable micro-lane provenance chain`);let freshGateState;try{freshGateState=await _internals315.readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let freshFamilyAttempts=countFamilyDispatchAttempts(freshGateState,row.trigger_id,parsed.data.pr_head_sha);if(!(freshFamilyAttempts.length>=1+PR_REVIEW_MICRO_FAMILY_RETRY_BUDGET&&freshFamilyAttempts.some((dispatchRecord)=>dispatchRecord.batchId===row.source_batch_id)))return failure4(`MATCHED trigger ${row.trigger_id} cites a liveness-dead micro lane, but the persisted dispatch-attempt ledger no longer proves the retry budget exhausted for this family at the decision moment (${freshFamilyAttempts.length} attempt(s) recorded, cited batch ${row.source_batch_id}). Nothing was persisted, so this call is retryable as-is. Recovery: re-dispatch the family or restart with abort_pr_workflow (kind "recovery").`);coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason:`liveness-terminal dead family: lane settled ${freshRecord2.status} with typed liveness class (presumed host abandonment), no retained artifact; family disclosed unattested; retry budget exhausted after ${freshFamilyAttempts.length} recorded dispatch attempt(s) for this family (cited batch ${row.source_batch_id} among them)`});continue}let degradationReasons=[];if(record3.status!=="completed")degradationReasons.push(`lane status ${record3.status}`);if(record3.result?.outputDegraded===!0)degradationReasons.push("output degraded");if(record3.result?.transcriptIncomplete===!0)degradationReasons.push("transcript incomplete");if(record3.result?.truncated===!0)degradationReasons.push("output truncated");if((record3.result?.chars??0)<=0)degradationReasons.push("empty output");if(!prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,row.trigger_id,recordOwnedLanes,record3.mode))degradationReasons.push(`no covered candidate or clean row for: ${row.trigger_id}`);for(let reason of degradationReasons)coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason})}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");if(!gateState.prReviewBaseRef||!gateState.prReviewBaseSha)return failure4('Active PR_REVIEW trigger evaluation requires a durably bound review base; the active PR_REVIEW gate has no bound base_ref/base_sha, so the received scope cannot be verified against anything. Re-bind the review scope by dispatching the review lanes for this PR, or restart with abort_pr_workflow (kind "recovery").');let resolvedMergeBase=await resolveReviewMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha),baseVerification="live";if(resolvedMergeBase){if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`)}else if(parsed.data.base_ref===gateState.prReviewBaseRef&&parsed.data.base_sha.toLowerCase()===gateState.prReviewBaseSha)baseVerification="bound_fallback",criticalWarn(`PR_REVIEW trigger evaluation could not re-derive the merge base for base_ref "${parsed.data.base_ref}" at pr_head_sha "${parsed.data.pr_head_sha}"; proceeding on the durably bound, bind-time-verified review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}). The receipt discloses base_verification: bound_fallback and the final review report must disclose it too.`);else return failure4(`Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref "${parsed.data.base_ref}" and pr_head_sha "${parsed.data.pr_head_sha}", and the received scope does not equal the durably bound review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}), so the bound-scope fallback does not apply. A null resolution collapses several causes: the bounded git call timed out, the git process failed to spawn, base_ref is not resolvable in this checkout, or base_ref/pr_head_sha was rejected as an unsafe revision token. Recovery: verify both revisions exist here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let artifact=buildPrReviewTriggerReceiptV2({run_id:resolvedRunId,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows,coverage_degradations:coverageDegradations,base_verification:baseVerification}),relativePath2=path378.join("pr-review",resolvedRunId,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let replayed=!1;try{let existing=null;try{existing=await readBoundedTriggerReceipt(destination)}catch(error93){if(error93.code!=="ENOENT")throw error93}if(existing){if(comparableTriggerReceipt(existing)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${resolvedRunId}" with conflicting content`);artifact=existing,replayed=!0}else if(!await createTriggerReceipt(destination,`${JSON.stringify(artifact,null,2)}
|
|
7858
7858
|
`)){let raced=await readBoundedTriggerReceipt(destination);if(comparableTriggerReceipt(raced)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt concurrently appeared for run "${resolvedRunId}" with conflicting content`);artifact=raced,replayed=!0}}catch(error93){return failure4(`Failed to read or persist trigger evaluation at "${relativePath2.split(path378.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}try{await _internals315.markPrReviewTriggerEvaluationComplete(directory,sessionID,resolvedRunId,relativePath2.split(path378.sep).join("/"))}catch(error93){return failure4(`Failed to persist trigger evaluation gate receipt for "${relativePath2.split(path378.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}return JSON.stringify({success:!0,replayed,run_id:resolvedRunId,path:relativePath2.split(path378.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2,base_verification:baseVerification,...baseVerification==="bound_fallback"?{base_verification_note:"live merge-base re-derivation was unavailable; the bound review scope was used and MUST be disclosed in the final review report"}:{},coverage_degradation_count:coverageDegradations.length,...coverageDegradations.length>0?{coverage_degradations:coverageDegradations,note:"degraded families recorded on the receipt; disclose them in the final review report"}:{}},null,2)}var write_pr_review_trigger_eval=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",args:{run_id:WritePrReviewTriggerEvalArgsSchema.shape.run_id,pr_head_sha:WritePrReviewTriggerEvalArgsSchema.shape.pr_head_sha,base_sha:WritePrReviewTriggerEvalArgsSchema.shape.base_sha,base_ref:WritePrReviewTriggerEvalArgsSchema.shape.base_ref,rows:WritePrReviewTriggerEvalArgsSchema.shape.rows},execute:executeWritePrReviewTriggerEval});init_write_retro();function defineHandlers(handlers){return handlers}var TOOL_MANIFEST=defineHandlers({diff:()=>diff,diff_summary:()=>diff_summary,syntax_check:()=>syntax_check,placeholder_scan:()=>placeholder_scan,imports:()=>imports,lint:()=>lint,secretscan:()=>secretscan,sast_scan:()=>sast_scan,build_check:()=>build_check,pre_check_batch:()=>pre_check_batch,quality_budget:()=>quality_budget,symbols:()=>symbols,complexity_hotspots:()=>complexity_hotspots,schema_drift:()=>schema_drift,todo_extract:()=>todo_extract,evidence_check:()=>evidence_check,check_gate_status:()=>check_gate_status,completion_verify:()=>completion_verify,complete_pr_workflow:()=>complete_pr_workflow,abort_pr_workflow:()=>abort_pr_workflow,cancel_lane_batch:()=>cancel_lane_batch,authorize_pr_review_reentry:()=>authorize_pr_review_reentry,submit_pr_review_result:()=>submit_pr_review_result,approve_plan_critic:()=>approve_plan_critic,approve_retry_sounding_board:()=>approve_retry_sounding_board,recover_rework_task:()=>recover_rework_task,recover_stage_a_task:()=>recover_stage_a_task,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,record_branch_freshness:()=>record_branch_freshness,record_trace_validation:()=>record_trace_validation,record_merge_approval:()=>record_merge_approval,invalidate_pr_feedback_publication:()=>invalidate_pr_feedback_publication,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,run_pr_feedback_stage_a:()=>run_pr_feedback_stage_a,submit_council_verdicts:()=>submit_council_verdicts,submit_phase_council_verdicts:()=>submit_phase_council_verdicts,declare_council_criteria:()=>declare_council_criteria,sbom_generate:()=>sbom_generate,checkpoint:()=>checkpoint,pkg_audit:()=>pkg_audit,parse_lane_candidates:()=>parse_lane_candidates,plan_conflict_check:()=>plan_conflict_check,prepare_pr_feedback_scope:()=>prepare_pr_feedback_scope,write_pr_review_artifact:()=>write_pr_review_artifact,write_pr_review_trigger_eval:()=>write_pr_review_trigger_eval,test_runner:()=>test_runner,test_impact:()=>test_impact,mutation_test:()=>mutation_test,generate_mutants:()=>generate_mutants,detect_domains:()=>detect_domains,git_blame:()=>git_blame,gitingest:()=>gitingest,retrieve_summary:()=>retrieve_summary,retrieve_lane_output:()=>retrieve_lane_output,extract_code_blocks:()=>extract_code_blocks,phase_complete:()=>phase_complete,run_phase_review:()=>run_phase_review,repair_gate_evidence:()=>repair_gate_evidence,repair_knowledge_receipt_ledger:()=>repair_knowledge_receipt_ledger,record_directive_override:()=>record_directive_override,save_plan:()=>save_plan,update_task_status:()=>update_task_status,lint_spec:()=>lint_spec,write_retro:()=>write_retro,write_drift_evidence:()=>write_drift_evidence,write_hallucination_evidence:()=>write_hallucination_evidence,write_mutation_evidence:()=>write_mutation_evidence,declare_scope:()=>declare_scope,scope_validate:()=>scope_validate,knowledge_query:()=>knowledge_query,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract,curator_analyze:()=>curator_analyze,consensus_mine:()=>consensus_mine,knowledge_add:()=>knowledge_add,knowledge_recall:()=>knowledge_recall,knowledge_remove:()=>knowledge_remove,co_change_analyzer:()=>co_change_analyzer,context_status:()=>context_status,search:()=>search,ast_grep:()=>ast_grep,actionlint_scan:()=>actionlint_scan,osv_scan:()=>osv_scan,gh_evidence:()=>gh_evidence,pr_workflow_status:()=>pr_workflow_status,batch_symbols:()=>batch_symbols,suggest_patch:()=>suggestPatch,req_coverage:()=>req_coverage,get_approved_plan:()=>get_approved_plan,repo_map:()=>repo_map,get_qa_gate_profile:()=>get_qa_gate_profile,set_qa_gates:()=>set_qa_gates,web_search:()=>web_search,web_fetch:()=>web_fetch,convene_general_council:()=>convene_general_council,write_final_council_evidence:()=>write_final_council_evidence,skill_generate:()=>skill_generate,skill_list:()=>skill_list,skill_apply:()=>skill_apply,skill_inspect:()=>skill_inspect,run_stale_reconciliation:()=>run_stale_reconciliation,skill_regenerate:()=>skill_regenerate,skill_retire:()=>skill_retire,skill_improve:()=>skill_improve,spec_write:()=>spec_write,knowledge_receipt:()=>knowledge_receipt,knowledge_receipt_status:()=>knowledge_receipt_status,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_memory_outcome:()=>swarm_memory_outcome,swarm_command:()=>swarm_command,dispatch_lanes:()=>dispatch_lanes,dispatch_lanes_async:()=>dispatch_lanes_async,collect_lane_results:()=>collect_lane_results,summarize_work:()=>summarize_work,write_architecture_supervisor_evidence:()=>write_architecture_supervisor_evidence,lean_turbo_plan_lanes:()=>lean_turbo_plan_lanes,lean_turbo_acquire_locks:()=>lean_turbo_acquire_locks,lean_turbo_critic:()=>lean_turbo_critic,lean_turbo_runner_status:()=>lean_turbo_runner_status,lean_turbo_review:()=>lean_turbo_review,lean_turbo_run_phase:()=>lean_turbo_run_phase,lean_turbo_status:()=>lean_turbo_status,swarm_apply_patch:()=>swarmApplyPatch2,external_skill_discover:()=>external_skill_discover,external_skill_list:()=>external_skill_list,external_skill_inspect:()=>external_skill_inspect,external_skill_promote:()=>external_skill_promote,external_skill_reject:()=>external_skill_reject,external_skill_delete:()=>external_skill_delete,external_skill_revoke:()=>external_skill_revoke,epic_decide_phase:()=>epic_decide_phase,epic_plan_waves:()=>epic_plan_waves,epic_record_divergence:()=>epic_record_divergence});function buildPluginToolObject(agents,config3,evaluationModelDispatcher,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),knowledgeEnabled=config3?.knowledge?.enabled!==!1,knowledgeTools=new Set(["knowledge_add","knowledge_recall","knowledge_remove","knowledge_query","knowledge_receipt","knowledge_archive"]);for(let[name,handler]of Object.entries(TOOL_MANIFEST)){if(!knowledgeEnabled&&knowledgeTools.has(name))continue;tools[name]=handler()}tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.run_phase_review=createRunPhaseReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_critic=createLeanTurboCriticTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames);let tracked={};for(let[name,def]of Object.entries(tools)){let execute2=def.execute;if(typeof execute2==="function")tracked[name]={...def,execute:withStartupFirstToolTracking(name,execute2)};else tracked[name]=def}return tracked}init_package();init_consent();init_vault();var PLUGIN_VERSION=package_default.version,MAX_DEDUP_PER_SESSION=4096,MAX_TRACKED_DEDUP_SESSIONS=500,GUIDANCE_CARRIER_ID_PREFIX2="swarm-guidance:",DIRECTIVE_TEXT_PREFIX="<swarm_system_directive";function safeStringify(value){try{return JSON.stringify(value)??""}catch{return String(value)}}var _internals316={appendRecord:appendTrainingVaultRecord,readConsent:(directory)=>readActiveTrainingConsent(directory),buildRecord:buildTrainingVaultRecord};function kindForRole(role){if(role==="user")return"user_message";if(role==="assistant")return"assistant_message";return null}function createTrainingCaptureObserver(directory){let dedupBySession=new Map;function markSeen(sessionId,recordId){let entry=dedupBySession.get(sessionId);if(!entry){entry={order:[],seen:new Set},dedupBySession.set(sessionId,entry);while(dedupBySession.size>MAX_TRACKED_DEDUP_SESSIONS){let oldest=dedupBySession.keys().next().value;if(oldest===void 0)break;dedupBySession.delete(oldest)}}if(entry.seen.has(recordId))return!1;if(entry.seen.add(recordId),entry.order.push(recordId),entry.order.length>MAX_DEDUP_PER_SESSION){let evicted=entry.order.shift();if(evicted!==void 0)entry.seen.delete(evicted)}return!0}function capture(kind,role,content,sessionId,source){let consent=_internals316.readConsent(directory);if(!consent)return;let record3=_internals316.buildRecord({directory,kind,role,content,sessionId,pluginVersion:PLUGIN_VERSION,source,consent});if(!markSeen(sessionId,record3.record_id))return;_internals316.appendRecord(directory,record3)}return{async observeMessages(output){try{let messages=output?.messages;if(!Array.isArray(messages))return;for(let message of messages)try{let info=message?.info;if(!info)continue;let sessionId=info.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)continue;if(typeof info.id==="string"&&info.id.startsWith(GUIDANCE_CARRIER_ID_PREFIX2))continue;let kind=kindForRole(info.role??"");if(!kind)continue;let parts=message.parts;if(!Array.isArray(parts))continue;for(let part of parts)try{if(part?.type!=="text")continue;let text=typeof part.text==="string"?part.text:"";if(text.length===0)continue;if(text.startsWith(DIRECTIVE_TEXT_PREFIX))continue;capture(kind,info.role??"",text,sessionId,"chat")}catch{}}catch{}}catch{}},async observeToolExecution(event){try{let sessionId=event?.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)return;let tool3=typeof event?.tool==="string"?event.tool:"unknown",inputSummary=safeStringify(event?.input);if(inputSummary.length>0)capture("tool_call","tool",inputSummary,sessionId,"tool");let outputSummary=safeStringify(event?.error??event?.output??"");if(outputSummary.length>0&&outputSummary!=='""')capture("tool_result","tool",`${tool3}
|
|
7859
|
-
${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable();init_project_boundary();init_timeout();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
|
|
7859
|
+
${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable();init_project_boundary();init_provider_error_classification();init_timeout();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
|
|
7860
7860
|
`);if(lines.length<=maxLines)return output;let omittedCount=lines.length-maxLines,headLines=lines.slice(0,maxLines-tailLines),tailContent=lines.slice(-tailLines),footerLines=[];if(footerLines.push(""),footerLines.push(`[... ${omittedCount} line${omittedCount===1?"":"s"} omitted ...]`),toolName)footerLines.push(`Tool: ${toolName}`);return footerLines.push("Use /swarm retrieve <id> to get the full content"),`${headLines.join(`
|
|
7861
7861
|
`)}
|
|
7862
7862
|
${tailContent.join(`
|
|
@@ -7871,6 +7871,6 @@ ${footerLines.join(`
|
|
|
7871
7871
|
`);if(trailingNewline)lines.pop();if(normalized.length===0)lines.length=0;return{lines,trailingNewline}}function applyFilePatch(baseContent,patch2){let split=splitTextLines(baseContent),source=split.lines,output=[],cursor=0,targetHasNoTrailingNewline=!1,previousMarker;for(let hunk of patch2.hunks){let targetIndex=hunk.oldCount===0?hunk.oldStart:hunk.oldStart-1,targetNewIndex=hunk.newCount===0?hunk.newStart:hunk.newStart-1;if(targetIndex<cursor)return null;while(cursor<targetIndex)output.push(source[cursor]),cursor++;if(output.length!==targetNewIndex)return null;for(let rawLine of hunk.lines){if(rawLine==="\"){if(previousMarker==="+"||previousMarker===" ")targetHasNoTrailingNewline=!0;continue}let marker=rawLine[0];previousMarker=marker;let value=rawLine.slice(1);if(marker===" "){if(source[cursor]!==value)return null;output.push(value),cursor++;continue}if(marker==="-"){if(source[cursor]!==value)return null;cursor++;continue}if(marker==="+"){output.push(value);continue}return null}}let patchTouchesOldEof=cursor===source.length;while(cursor<source.length)output.push(source[cursor]),cursor++;let trailingNewline=patchTouchesOldEof?!targetHasNoTrailingNewline:split.trailingNewline;return`${output.join(`
|
|
7872
7872
|
`)}${output.length>0&&trailingNewline?`
|
|
7873
7873
|
`:""}`}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(`
|
|
7874
|
-
`);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 OpenCodeSwarm=async(ctx)=>{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}},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),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,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(`
|
|
7874
|
+
`);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 OpenCodeSwarm=async(ctx)=>{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}},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(`
|
|
7875
7875
|
|
|
7876
|
-
`),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: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})}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",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"){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}}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};export{schedulePostResolutionTasksForTest,recoverPendingCostCorrectionForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,applySoundingBoardResponsePolicy,_resetDelegationTelemetryPairingForTesting};
|
|
7876
|
+
`),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",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};export{schedulePostResolutionTasksForTest,recoverPendingCostCorrectionForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,applySoundingBoardResponsePolicy,_resetDelegationTelemetryPairingForTesting};
|