opencode-swarm 7.188.2 → 7.188.4
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/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{auto-checkpoint-e4r8nfq5.js → auto-checkpoint-gp13e1h5.js} +8 -8
- package/dist/cli/{checkpoint-ejm8n9y5.js → checkpoint-61vy6pjg.js} +16 -16
- package/dist/cli/{coder-settlement-hped4xgs.js → coder-settlement-2s4rr23t.js} +12 -12
- package/dist/cli/{config-doctor-1qp1jmz4.js → config-doctor-0pjjr594.js} +15 -15
- package/dist/cli/{core-j5yff7rq.js → core-qdn60dm0.js} +3 -3
- package/dist/cli/{curation-policy-v64ctcbd.js → curation-policy-2rdbwc6a.js} +6 -6
- package/dist/cli/{curator-jf60p665.js → curator-8yqmmn5w.js} +42 -42
- package/dist/cli/{curator-drift-2sypkddx.js → curator-drift-n4t27md5.js} +8 -8
- package/dist/cli/curator-llm-factory-30n2fnef.js +82 -0
- package/dist/cli/{doctor-knowledge-receipt-phase-id-xyecjehq.js → doctor-knowledge-receipt-phase-id-vk9c6t3k.js} +8 -8
- package/dist/cli/{evidence-summary-service-k2g6hj96.js → evidence-summary-service-xpdx8se9.js} +19 -19
- package/dist/cli/{gate-evidence-vmzyfpsp.js → gate-evidence-px2mexyg.js} +7 -7
- package/dist/cli/guardrail-explain-38hmb1s9.js +83 -0
- package/dist/cli/{guardrail-log-2htm6kes.js → guardrail-log-y61ewh6d.js} +7 -7
- package/dist/cli/{guardrail-reset-dbwzk3p9.js → guardrail-reset-3arv6rfs.js} +42 -42
- package/dist/cli/{hive-promoter-c24qc0e1.js → hive-promoter-5naewxf9.js} +42 -42
- package/dist/cli/{index-bf1meb32.js → index-0yqa3awy.js} +2 -2
- package/dist/cli/{index-m1qy7f1e.js → index-103gsfn1.js} +1 -1
- package/dist/cli/{index-9wfjc4cn.js → index-195msz9x.js} +1 -1
- package/dist/cli/{index-r6e8syr3.js → index-1d51nz8d.js} +1 -1
- package/dist/cli/{index-edf2eztc.js → index-1e4s8cyt.js} +4 -4
- package/dist/cli/{index-rwabrcsg.js → index-2ajapc0r.js} +1 -1
- package/dist/cli/{index-dwm3czmf.js → index-3034m1wv.js} +4 -4
- package/dist/cli/{index-bejxkee0.js → index-4czf0es9.js} +1 -1
- package/dist/cli/{index-wb01w8ex.js → index-4vgvybav.js} +2 -2
- package/dist/cli/{index-0v2svrev.js → index-4zran0jk.js} +1 -1
- package/dist/cli/{index-0rzc71q8.js → index-53me7h10.js} +5 -5
- package/dist/cli/{index-md4xx63t.js → index-64nkt4ek.js} +1 -1
- package/dist/cli/{index-4e3qcwfb.js → index-6kckcdd7.js} +3 -3
- package/dist/cli/{index-1466xg5c.js → index-6kf62j82.js} +1 -1
- package/dist/cli/{index-1hqybe51.js → index-6qtgyzw2.js} +3 -3
- package/dist/cli/{index-jd3hvnqn.js → index-75bm071p.js} +2 -2
- package/dist/cli/{index-mb1reyw3.js → index-8tf5tewn.js} +2 -2
- package/dist/cli/{index-rn5hh7pp.js → index-8zs4v02d.js} +6 -6
- package/dist/cli/{index-51dww7y9.js → index-94b58ssa.js} +82 -82
- package/dist/cli/{index-rx9phqsj.js → index-a5z8eqs0.js} +44 -44
- package/dist/cli/{index-9b86vn97.js → index-bqqyxmpk.js} +7 -7
- package/dist/cli/{index-x2p51ka9.js → index-d3p96wkj.js} +6 -6
- package/dist/cli/{index-41v699sv.js → index-d74wbpqc.js} +7 -7
- package/dist/cli/{index-gd41qkx3.js → index-dka1ra21.js} +7 -7
- package/dist/cli/{index-b02cdy5w.js → index-fm0yan3t.js} +4 -4
- package/dist/cli/{index-b9pz70d0.js → index-ge4hk20b.js} +2 -2
- package/dist/cli/{index-9hsnarbv.js → index-gmmz119k.js} +1 -1
- package/dist/cli/{index-7sbyvk99.js → index-gyhj562n.js} +2 -2
- package/dist/cli/{index-4htcpbs4.js → index-h83221w1.js} +3 -3
- package/dist/cli/{index-wxf5feq2.js → index-j7pqzxyq.js} +2 -2
- package/dist/cli/{index-a8gvszr2.js → index-jc0jxg7y.js} +2 -2
- package/dist/cli/{index-zwgh0gty.js → index-jkz10gm7.js} +1 -1
- package/dist/cli/{index-kxj8bqtj.js → index-ntyc39rv.js} +2 -2
- package/dist/cli/{index-fq78x7th.js → index-p8kv9hh6.js} +11 -11
- package/dist/cli/{index-mf19yqss.js → index-qwrx78m5.js} +2 -2
- package/dist/cli/{index-yay1xxzk.js → index-rqheyf9e.js} +4 -4
- package/dist/cli/{index-pz26qx3x.js → index-sh7se0x5.js} +7 -7
- package/dist/cli/{index-tr901ma3.js → index-tr6kaa6q.js} +5 -5
- package/dist/cli/{index-cc1vzq4m.js → index-v09x4k5h.js} +1 -1
- package/dist/cli/{index-x73e0zkb.js → index-vx59q2ex.js} +1 -1
- package/dist/cli/{index-ea10gcja.js → index-wftdsx38.js} +5 -5
- package/dist/cli/{index-k1aek1xr.js → index-wsab75et.js} +3 -3
- package/dist/cli/{index-9hag235h.js → index-ww91zjzk.js} +1 -1
- package/dist/cli/{index-vhwbxtzt.js → index-xn48kjf4.js} +2 -2
- package/dist/cli/{index-zyc869ys.js → index-yacpp9jq.js} +3 -3
- package/dist/cli/{index-3dvzvhrp.js → index-yctaaj1k.js} +5 -5
- package/dist/cli/{index-m6k9fsae.js → index-ywpn0arj.js} +42 -42
- package/dist/cli/index.js +43 -43
- package/dist/cli/{knowledge-escalator-5sqgd4pg.js → knowledge-escalator-2c4svh7n.js} +14 -14
- package/dist/cli/{knowledge-events-05yp3j0n.js → knowledge-events-7zea5hzr.js} +12 -12
- package/dist/cli/{knowledge-link-9gx2djyd.js → knowledge-link-r9nx1eaj.js} +5 -5
- package/dist/cli/{knowledge-store-zx3qkamt.js → knowledge-store-rdya1anx.js} +6 -6
- package/dist/cli/{knowledge-validator-pc399we4.js → knowledge-validator-qnc4byyh.js} +8 -8
- package/dist/cli/{mcp-8ptynxsv.js → mcp-z21kvvnf.js} +1 -1
- package/dist/cli/{model-preflight-bhxpnrb6.js → model-preflight-jbg35f6e.js} +42 -42
- package/dist/cli/{pending-delegations-6wcwj6sp.js → pending-delegations-c1yjybf1.js} +12 -12
- package/dist/cli/{pr-subscriptions-22q1p6wg.js → pr-subscriptions-2mngc0jg.js} +12 -12
- package/dist/cli/{pr-workflow-gate-5v9yabv2.js → pr-workflow-gate-h4s5w5y0.js} +42 -42
- package/dist/cli/{runner-x8sbydkw.js → runner-3ynjanks.js} +6 -6
- package/dist/cli/{scan-cursor-dkd9jvvq.js → scan-cursor-385k9dkp.js} +7 -7
- package/dist/cli/{schema-nsnc7dm8.js → schema-cp8sqp1b.js} +1 -1
- package/dist/cli/{scope-persistence-hwafwz1n.js → scope-persistence-d587cb6v.js} +15 -15
- package/dist/cli/{server-k52tg8j6.js → server-t0wansfd.js} +51 -43
- package/dist/cli/{skill-generator-ak2vxhqe.js → skill-generator-f2j1jnqf.js} +16 -16
- package/dist/cli/{snapshot-coordination-init-nwh6z0a6.js → snapshot-coordination-init-9gvgq52n.js} +42 -42
- package/dist/cli/{speckit-checkoff-wydtzjmn.js → speckit-checkoff-zw0w6ekx.js} +4 -4
- package/dist/cli/{telemetry-d0j31j5d.js → telemetry-eq1cwq2x.js} +1 -1
- package/dist/cli/{workspace-snapshot-y60ay5eq.js → workspace-snapshot-w60bykdz.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-5fbzrgnm.js → worktree-collision-ownership-0d8xf1d8.js} +13 -13
- package/dist/cli/{worktree-isolation-643nwna7.js → worktree-isolation-ds8n4a16.js} +42 -42
- package/dist/context-map/capsule-builder.d.ts +14 -1
- package/dist/context-map/persistence.d.ts +9 -0
- package/dist/context-map/post-agent-update.d.ts +90 -1
- package/dist/host/v2/agents-commands.d.ts +41 -0
- package/dist/host/v2/events.d.ts +39 -0
- package/dist/host/v2/guidance.d.ts +30 -0
- package/dist/host/v2/hooks.d.ts +31 -0
- package/dist/host/v2/setup.d.ts +61 -0
- package/dist/host/v2/tools.d.ts +41 -0
- package/dist/host/v2/types.d.ts +291 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +14 -13
- package/dist/tools/syntax-check.d.ts +14 -0
- package/dist/types/context-capsule.d.ts +12 -0
- package/dist/types/context-map.d.ts +1 -1
- package/package.json +1 -1
- package/dist/cli/curator-llm-factory-we3t6fqd.js +0 -82
- package/dist/cli/guardrail-explain-cpr1hh21.js +0 -83
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.188.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.188.4",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
|
|
|
@@ -176,7 +176,7 @@ line break`,"required change with\rcarriage return"]),discardedReviewer=encodePr
|
|
|
176
176
|
`);return outside?`${outside}
|
|
177
177
|
${protocol}`:protocol}function declaredCanonicalFamilies(source){let families=[];for(let line of source.split(/\r?\n/)){let family=candidateHeaderFamily(splitPipeFields(line).map((field)=>field.trim()));if(family&&!families.includes(family))families.push(family)}return families}function normalizeCandidateArtifact(rawText,fallbackFamily){let repairKinds=[],summaryDrop=dropNonContractMarkerRows(rawText);if(summaryDrop.dropped)repairKinds.push("summary-row-dropped");let recoveredFence=recoverTerminalProtocolFence(summaryDrop.text,fallbackFamily);if(recoveredFence!==null)repairKinds.push("terminal-protocol-fence");let cleanRepair=repairRedundantCleanConfidence(recoveredFence??removeCandidateCodeFences(summaryDrop.text),fallbackFamily);if(cleanRepair.repaired)repairKinds.push("redundant-clean-confidence");let pipeRepair=repairCleanEvidencePipes(cleanRepair.text);if(pipeRepair.repaired)repairKinds.push("clean-evidence-pipe-tail-merge");let candidatePipeRepair=repairCandidateEvidencePipes(pipeRepair.text,fallbackFamily);if(candidatePipeRepair.repaired)repairKinds.push("candidate-evidence-pipe-recovery-lossy");let lateHeaderRepair=resynchronizeLateCanonicalHeader(candidatePipeRepair.text,fallbackFamily);if(lateHeaderRepair.repaired)repairKinds.push("late-canonical-header-resynchronized");let duplicateHeaderDrop=dropDuplicateHeaderRows(lateHeaderRepair.text);if(duplicateHeaderDrop.dropped)repairKinds.push("duplicate-header-row-dropped");let text=duplicateHeaderDrop.text,header=selectCandidateHeader(text.split(/\r?\n/));if(header?.markerBearing&&header.family!==null)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(text).length>0)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(summaryDrop.text).some((family)=>family!==fallbackFamily))return{text,synthesizedHeader:!1,repairKinds};let lines=text.split(/\r?\n/);if(!lines.some((line)=>{if(analyzeCandidateLine(line,fallbackFamily)?.valid===!0)return!0;let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!==CLEAN_MARKER)return!1;return analyzeCleanFields(fields,fallbackFamily).valid}))return{text,synthesizedHeader:!1,repairKinds};let firstSalvageableIndex=lines.findIndex((line)=>{let marker=splitPipeFields(line)[0]?.trim();return marker===CANDIDATE_MARKER||marker===CLEAN_MARKER});return repairKinds.push("synthesized-header"),{text:[...lines.slice(0,firstSalvageableIndex),CANDIDATE_HEADERS[fallbackFamily],...lines.slice(firstSalvageableIndex)].join(`
|
|
178
178
|
`),synthesizedHeader:!0,repairKinds}}function candidateArtifactCacheKey(rawText,fallbackFamily){return createHash2("sha256").update(`${rawText}\x00${fallbackFamily}`).digest("hex")}function normalizeCandidateArtifactCached(rawText,fallbackFamily){let key=candidateArtifactCacheKey(rawText,fallbackFamily),hit=candidateArtifactCache.get(key);if(hit!==void 0)return candidateArtifactCacheHits++,hit;candidateArtifactCacheMisses++;let result=normalizeCandidateArtifact(rawText,fallbackFamily);if(candidateArtifactCache.size>=CANDIDATE_ARTIFACT_CACHE_CAPACITY){let oldest=candidateArtifactCache.keys().next().value;if(oldest!==void 0)candidateArtifactCache.delete(oldest)}return candidateArtifactCache.set(key,result),result}function analyzeCandidateLaneContext(context){let issues=[],baseBound=Boolean(context.expected_lane||context.expected_lanes),microBound=Boolean(context.expected_micro_lane||context.expected_micro_lanes);if(context.expected_lanes){if(!context.expected_lane)issues.push({field:"expected_lane",message:"expected_lane is required when expected_lanes is supplied"});if(new Set(context.expected_lanes).size!==context.expected_lanes.length)issues.push({field:"expected_lanes",message:"expected_lanes must contain unique lane identities"});if(context.expected_lane&&!context.expected_lanes.includes(context.expected_lane))issues.push({field:"expected_lanes",message:"expected_lanes must contain expected_lane"})}if(context.expected_micro_lanes){if(!context.expected_micro_lane)issues.push({field:"expected_micro_lane",message:"expected_micro_lane is required when expected_micro_lanes is supplied"});if(new Set(context.expected_micro_lanes).size!==context.expected_micro_lanes.length)issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain unique lane identities"});if(context.expected_micro_lane&&!context.expected_micro_lanes.includes(context.expected_micro_lane))issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain expected_micro_lane"})}if(!context.expected_family&&baseBound&µBound)issues.push({field:"expected_family",message:"base and micro ownership fields cannot be combined without one expected_family"});else if(context.expected_family==="base_explorer"&µBound)issues.push({field:"expected_family",message:"base_explorer ownership cannot include expected_micro_lane fields"});else if(context.expected_family==="micro_lane"&&baseBound)issues.push({field:"expected_family",message:"micro_lane ownership cannot include expected_lane fields"});else if(!context.expected_family&&baseBound)issues.push({field:"expected_family",message:"base ownership fields require expected_family base_explorer"});else if(!context.expected_family&µBound)issues.push({field:"expected_family",message:"micro ownership fields require expected_family micro_lane"});return issues}function splitPipeFields(line){let fields=[],current="";for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"&&index+1<line.length&&line[index+1]==="|"){current+="|",index++;continue}if(char==="|"){fields.push(current),current="";continue}current+=char}return fields.push(current),fields}function candidateDiagnosticPreview(value){let normalized=value.replace(/[\r\n\t]+/g," ").trim();if(normalized.length<=CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)return normalized;return`${normalized.slice(0,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)}...`}function isCandidateSeverity(value){return value!==null&&value!==void 0&&CANDIDATE_SEVERITIES.includes(value)}function isCandidateConfidence(value){return value!==null&&value!==void 0&&CANDIDATE_CONFIDENCES.includes(value)}function isCandidateLookingShortRow(fields,_context,explicitCandidateMarker=!1){if(explicitCandidateMarker||fields[0]?.trim()==="[CANDIDATE]")return!0;return fields.length>=2}function analyzeCandidateFields(fields,family){let names=CANDIDATE_FIELDS[family],trimmed=fields.map((field)=>field.trim()),values={},issues=[];if(trimmed.length!==CANDIDATE_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CANDIDATE_FIELD_COUNT} candidate fields, received ${trimmed.length}`});for(let index=0;index<names.length;index++){let name=names[index],value=trimmed[index]?.trim()||null;if(values[name]=value,value===null&&name!=="risk_impact"&&name!=="risk_tags")issues.push({field:name,message:`Missing required field: ${name}`})}let severity=values.severity;if(severity!==null&&!isCandidateSeverity(severity))issues.push({field:"severity",message:`Invalid severity: ${candidateDiagnosticPreview(severity)}; expected ${CANDIDATE_SEVERITIES.join("|")}`});let confidence=values.confidence;if(confidence!==null&&!isCandidateConfidence(confidence))issues.push({field:"confidence",message:`Invalid confidence: ${candidateDiagnosticPreview(confidence)}; expected ${CANDIDATE_CONFIDENCES.join("|")}`});let riskImpact=values.risk_impact;if(riskImpact!==null&&!PR_REVIEW_RISK_IMPACTS.includes(riskImpact))issues.push({field:"risk_impact",message:`Invalid risk_impact: ${candidateDiagnosticPreview(riskImpact)}; expected ${PR_REVIEW_RISK_IMPACTS.join("|")}`});let riskTags=values.risk_tags;if(riskTags!==null){let parsedTags=parsePrReviewRiskTagsField(riskTags),known=new Set(PR_REVIEW_RISK_TAGS);if(riskTags!==""&&(parsedTags.length===0||parsedTags.some((tag)=>!known.has(tag))))issues.push({field:"risk_tags",message:`Invalid risk_tags: ${candidateDiagnosticPreview(riskTags)}; expected a comma-separated subset of ${PR_REVIEW_RISK_TAGS.join("|")}, or empty`})}return{valid:issues.length===0,issues,values,candidateId:values.candidate_id,workflowLane:family==="base_explorer"?values.lane:values.micro_lane}}function analyzeCleanFields(fields,family,expectedLane){let trimmed=fields.map((field)=>field.trim()),issues=[],laneField=family==="base_explorer"?"lane":"micro_lane";if(trimmed.length!==CLEAN_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CLEAN_FIELD_COUNT-1} CLEAN fields after [CLEAN], received ${Math.max(0,trimmed.length-1)}`});if(trimmed[0]!=="[CLEAN]")issues.push({field:"row",message:"CLEAN row must begin with [CLEAN]"});let lane=trimmed[1]||null,coverageScope=trimmed[2]||null,evidence=trimmed[3]||null;if(lane===null)issues.push({field:laneField,message:`Missing required field: ${laneField}`});else if(expectedLane!==void 0&&lane!==expectedLane)issues.push({field:laneField,message:`Expected ${laneField} ${candidateDiagnosticPreview(expectedLane)}, received ${candidateDiagnosticPreview(lane)}`});if(coverageScope===null)issues.push({field:"coverage_scope",message:"Missing required field: coverage_scope"});else if(coverageScope.length<CLEAN_COVERAGE_SCOPE_MIN_CHARS)issues.push({field:"coverage_scope",message:`coverage_scope must contain at least ${CLEAN_COVERAGE_SCOPE_MIN_CHARS} characters`});if(evidence===null)issues.push({field:"evidence",message:"Missing required field: evidence"});else if(evidence.length<CLEAN_EVIDENCE_MIN_CHARS)issues.push({field:"evidence",message:`evidence must contain at least ${CLEAN_EVIDENCE_MIN_CHARS} characters`});return{valid:issues.length===0,issues,lane,coverageScope,evidence}}function analyzeCandidateLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CANDIDATE]")return null;return analyzeCandidateFields(fields.slice(1),family)}var CANDIDATE_SEVERITIES,FINDINGS_SEVERITIES,CANDIDATE_CONFIDENCES,CANDIDATE_FIELD_COUNT=11,CANDIDATE_LEGACY_FIELD_COUNT=9,CLEAN_FIELD_COUNT=4,CLEAN_COVERAGE_SCOPE_MIN_CHARS=12,CLEAN_EVIDENCE_MIN_CHARS=20,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS=160,CANDIDATE_FIELDS,CANDIDATE_REQUIRED_FIELDS,CANDIDATE_MARKER="[CANDIDATE]",CLEAN_MARKER="[CLEAN]",CANDIDATE_HEADERS,CLEAN_TEMPLATES,NON_CONTRACT_MARKER_LINE,CANDIDATE_ARTIFACT_CACHE_CAPACITY=512,candidateArtifactCache,candidateArtifactCacheHits=0,candidateArtifactCacheMisses=0;var init_candidate_contract=__esm(()=>{init_pr_review_contract();init_pr_review_contract();CANDIDATE_SEVERITIES=["INFO","LOW","MEDIUM","HIGH","CRITICAL"],FINDINGS_SEVERITIES=[...CANDIDATE_SEVERITIES,"NONE"],CANDIDATE_CONFIDENCES=["HIGH","MEDIUM","LOW"],CANDIDATE_FIELDS={base_explorer:["candidate_id","lane","severity","category","file_line","claim","evidence_summary","impact_context","confidence","risk_impact","risk_tags"],micro_lane:["candidate_id","micro_lane","severity","category","file_line","claim","invariant_violated","evidence_summary","confidence","risk_impact","risk_tags"]},CANDIDATE_REQUIRED_FIELDS={base_explorer:CANDIDATE_FIELDS.base_explorer.filter((field)=>field!=="risk_impact"&&field!=="risk_tags"),micro_lane:CANDIDATE_FIELDS.micro_lane.filter((field)=>field!=="risk_impact"&&field!=="risk_tags")};CANDIDATE_HEADERS={base_explorer:formatCandidateHeader("base_explorer"),micro_lane:formatCandidateHeader("micro_lane")},CLEAN_TEMPLATES={base_explorer:formatCleanTemplate("base_explorer"),micro_lane:formatCleanTemplate("micro_lane")};NON_CONTRACT_MARKER_LINE=/^\[(?!(?:CANDIDATE|CLEAN)\])[A-Z][A-Z0-9_-]*\]/;candidateArtifactCache=new Map});var require_polyfills=__commonJS((exports,module)=>{var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs4){if(constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs4);if(!fs4.lutimes)patchLutimes(fs4);if(fs4.chown=chownFix(fs4.chown),fs4.fchown=chownFix(fs4.fchown),fs4.lchown=chownFix(fs4.lchown),fs4.chmod=chmodFix(fs4.chmod),fs4.fchmod=chmodFix(fs4.fchmod),fs4.lchmod=chmodFix(fs4.lchmod),fs4.chownSync=chownFixSync(fs4.chownSync),fs4.fchownSync=chownFixSync(fs4.fchownSync),fs4.lchownSync=chownFixSync(fs4.lchownSync),fs4.chmodSync=chmodFixSync(fs4.chmodSync),fs4.fchmodSync=chmodFixSync(fs4.fchmodSync),fs4.lchmodSync=chmodFixSync(fs4.lchmodSync),fs4.stat=statFix(fs4.stat),fs4.fstat=statFix(fs4.fstat),fs4.lstat=statFix(fs4.lstat),fs4.statSync=statFixSync(fs4.statSync),fs4.fstatSync=statFixSync(fs4.fstatSync),fs4.lstatSync=statFixSync(fs4.lstatSync),fs4.chmod&&!fs4.lchmod)fs4.lchmod=function(path6,mode,cb){if(cb)process.nextTick(cb)},fs4.lchmodSync=function(){};if(fs4.chown&&!fs4.lchown)fs4.lchown=function(path6,uid,gid,cb){if(cb)process.nextTick(cb)},fs4.lchownSync=function(){};if(platform==="win32")fs4.rename=typeof fs4.rename!=="function"?fs4.rename:function(fs$rename){function rename2(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs4.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename2,fs$rename);return rename2}(fs4.rename);fs4.read=typeof fs4.read!=="function"?fs4.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs4,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs4,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs4.read),fs4.readSync=typeof fs4.readSync!=="function"?fs4.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs4,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs4.readSync);function patchLchmod(fs5){fs5.lchmod=function(path6,mode,callback){fs5.open(path6,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs5.fchmod(fd,mode,function(err2){fs5.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs5.lchmodSync=function(path6,mode){var fd=fs5.openSync(path6,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs5.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret}}function patchLutimes(fs5){if(constants.hasOwnProperty("O_SYMLINK")&&fs5.futimes)fs5.lutimes=function(path6,at,mt,cb){fs5.open(path6,constants.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs5.futimes(fd,at,mt,function(er2){fs5.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs5.lutimesSync=function(path6,at,mt){var fd=fs5.openSync(path6,constants.O_SYMLINK),ret,threw=!0;try{ret=fs5.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret};else if(fs5.futimes)fs5.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs5.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs4,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs4,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs4,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs4,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs4,target,options,callback):orig.call(fs4,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs4,target,options):orig.call(fs4,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs4){return{ReadStream,WriteStream};function ReadStream(path6,options){if(!(this instanceof ReadStream))return new ReadStream(path6,options);Stream.call(this);var self=this;this.path=path6,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs4.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path6,options){if(!(this instanceof WriteStream))return new WriteStream(path6,options);Stream.call(this),this.path=path6,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs4.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs4=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
|
|
179
|
-
GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path6.sep);try{let st=fs4.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:466"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:695","src/plan/manager.ts:2122","src/plan/manager.ts:2182","src/review/evidence.ts:179","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:163","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:234","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1471","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1377","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1520","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:154","src/tools/write-pr-review-artifact.ts:174","src/tools/write-pr-review-trigger-eval.ts:105"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:2381","src/plan/manager.ts:2443"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:205","src/full-auto/state.ts:636","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:607","src/plan/ledger.ts:1793"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/background/stage-b-dispatch-binding-store.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"migrated","src/tools/record-issue-publication.ts":"migrated","src/tools/record-issue-reproduction.ts":"migrated","src/tools/record-recurrence-sweep.ts":"migrated","src/tools/record-branch-freshness.ts":"migrated","src/tools/record-trace-validation.ts":"migrated","src/tools/record-merge-approval.ts":"migrated","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
|
|
179
|
+
GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path6.sep);try{let st=fs4.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:466"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:695","src/plan/manager.ts:2122","src/plan/manager.ts:2182","src/review/evidence.ts:179","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:163","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:234","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1471","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1377","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1520","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:154","src/tools/write-pr-review-artifact.ts:174","src/tools/write-pr-review-trigger-eval.ts:105"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:2381","src/plan/manager.ts:2443"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:205","src/full-auto/state.ts:636","src/context-map/persistence.ts:135","src/context-map/capsule-persistence.ts:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:607","src/plan/ledger.ts:1793"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/background/stage-b-dispatch-binding-store.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"migrated","src/tools/record-issue-publication.ts":"migrated","src/tools/record-issue-reproduction.ts":"migrated","src/tools/record-recurrence-sweep.ts":"migrated","src/tools/record-branch-freshness.ts":"migrated","src/tools/record-trace-validation.ts":"migrated","src/tools/record-merge-approval.ts":"migrated","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
|
|
180
180
|
→ ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};for(let fn2 of fns)if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");return async(input,output)=>{for(let fn2 of fns)await _internals10.safeHook(fn2)(input,output)}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path8.normalize(path8.resolve(directory,".swarm")),resolved=path8.normalize(path8.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path8.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path8.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs5.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs5.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs5.existsSync(existingPath)){let parent=path8.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs5.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path8.normalize(candidate),normalizedBase=path8.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path8.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path8.sep}`)}async function readSwarmFileAsync(directory,filename,cache2,reader,useArtifactCache=!0){if(cache2!==void 0&&useArtifactCache){let key=`${directory}::${filename}`,cached2=cache2.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename,void 0,reader,useArtifactCache);return cache2.set(key,promise2),promise2}let ENOENT_MAX_ATTEMPTS=5,ENOENT_RETRY_DELAY_MS=10,maxAttempts=6;for(let attempt=0;attempt<maxAttempts;attempt++){let resolvedPath="";try{resolvedPath=_internals10.validateSwarmPath(directory,filename);let read=async()=>{if(reader!==void 0)return reader(resolvedPath);return await bunFile(resolvedPath).text()};return useArtifactCache?await _internals10.readCachedTextFile(resolvedPath,read):await read()}catch(err){let code=err?.code;if(reader!==void 0&&(code===void 0||code==="ERR_ENCODING_INVALID_ENCODED_DATA"))throw err;if(code==="ENOENT"){if(!(resolvedPath!==""&&(wasRecentlyWrittenByThisProcess(resolvedPath,RECENT_WRITE_WINDOW_MS)||wasObservedToExist(resolvedPath))))return null;if(attempt>=ENOENT_MAX_ATTEMPTS-1)return null;await new Promise((resolve6)=>setTimeout(resolve6,ENOENT_RETRY_DELAY_MS));continue}if(!(code==="EBUSY"||code==="EPERM"||code==="EACCES")||attempt===maxAttempts-1)return null;let retryDelayMs=10*2**attempt;await new Promise((resolve6)=>setTimeout(resolve6,retryDelayMs))}}return null}function estimateTokensFromCharCount(chars){if(chars<=0)return 0;return Math.ceil(chars*TOKENS_PER_CHAR)}function estimateCharsForTokens(tokens){if(tokens<=0)return 0;return Math.floor(tokens/TOKENS_PER_CHAR)}function estimateTokens(text){if(!text)return 0;return estimateTokensFromCharCount(text.length)}var _internals10,TOKENS_PER_CHAR=0.33;var init_utils2=__esm(()=>{init_utils();init_atomic_write();init_bun_compat();init_swarm_artifact_cache();_internals10={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});import{createHash as createHash3}from"node:crypto";import{appendFileSync,mkdirSync as mkdirSync2}from"node:fs";import*as path9 from"node:path";function isBidiCodePoint(code){for(let i=0;i<BIDI_RANGES.length;i++){let[lo,hi]=BIDI_RANGES[i];if(code>=lo&&code<=hi)return!0}return!1}function sanitizeString(value){let result="";for(let i=0;i<value.length;i++){let code=value.codePointAt(i)??0;if(code>65535)result+=value[i],i++,result+=value[i];else if(code===0)result+="\\u0000";else if(code===27){if(i+1<value.length&&value[i+1]==="["){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=48&&next<=63)i++;else if(next>=32&&next<=47)i++;else if(next>=64&&next<=126){i++;break}else break}}else if(i+1<value.length&&value[i+1]==="]"){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next===7){i++;break}else if(next===27&&i+2<value.length&&value[i+2]==="\\"){i+=2;break}else i++}}else if(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=32&&next<=47){i++;while(i+1<value.length){let b=value.charCodeAt(i+1);if(b>=48&&b<=126){i++;break}else if(b>=32&&b<=47)i++;else break}}else if(next>=48&&next<=126)i++}}else if(isBidiCodePoint(code));else result+=value[i]}return result}function sanitizeRecord(record2){for(let key of Object.keys(record2)){let value=record2[key];if(typeof value==="string")record2[key]=sanitizeString(value);else if(value!==null&&typeof value==="object")if(Array.isArray(value))for(let i=0;i<value.length;i++){let element=value[i];if(typeof element==="string")value[i]=sanitizeString(element);else if(element!==null&&typeof element==="object")sanitizeRecord(element)}else sanitizeRecord(value)}return record2}function computeBatchDigest(batchId){return createHash3(BATCH_DIGEST_ALGORITHM).update(batchId).digest("hex")}function sidecarRelativePath(batchDigest){return path9.join("lane-results",batchDigest,"candidates.jsonl")}function validateRecord(record2,schema,label){let result=schema.safeParse(record2);if(!result.success)throw Error(`Sidecar ${label} schema validation failed: ${result.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")}`)}function withLockfile(lockDir,write){let lockPath=path9.join(lockDir,".lock"),release=import_proper_lockfile.default.lockSync(lockPath,{realpath:!1});try{return write()}finally{release()}}function appendToSidecar(options,batchId,envelope,candidates,cleanAttestation){let batchDigest=options.batchDigest??computeBatchDigest(batchId),relPath=sidecarRelativePath(batchDigest),absPath=validateSwarmPath(options.projectRoot,relPath);validateRecord(envelope,SidecarEnvelopeSchema,"envelope");for(let i=0;i<candidates.length;i++)validateRecord(candidates[i],SidecarCandidateSchema,`candidate[${i}]`);if(cleanAttestation!==void 0)validateRecord(cleanAttestation,SidecarCleanAttestationSchema,"clean_attestation");mkdirSync2(path9.dirname(absPath),{recursive:!0});let sanitizedEnvelope=sanitizeRecord(structuredClone(envelope)),sanitizedCandidates=candidates.map((c)=>sanitizeRecord(structuredClone(c))),sanitizedCleanAttestation=cleanAttestation===void 0?void 0:sanitizeRecord(structuredClone(cleanAttestation)),lines=[JSON.stringify(sanitizedEnvelope)];if(sanitizedCleanAttestation)lines.push(JSON.stringify(sanitizedCleanAttestation));for(let candidate of sanitizedCandidates)lines.push(JSON.stringify(candidate));let payload=`${lines.join(`
|
|
181
181
|
`)}
|
|
182
182
|
`,doWrite=()=>{appendFileSync(absPath,payload,"utf-8")};if(options.useLockfile)withLockfile(path9.dirname(absPath),doWrite);else doWrite()}var import_proper_lockfile,BATCH_DIGEST_ALGORITHM="sha256",SidecarEnvelopeSchema,SidecarCleanAttestationSchema,SidecarCandidateCommon,SidecarCandidateSchema,BIDI_RANGES;var init_candidate_sidecar_store=__esm(()=>{init_zod();init_utils2();init_candidate_contract();import_proper_lockfile=__toESM(require_proper_lockfile(),1),SidecarEnvelopeSchema=exports_external.object({record_type:exports_external.literal("invocation"),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),produced_at:exports_external.string().min(1),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),format_families_detected:exports_external.array(exports_external.string()),candidate_count:exports_external.number().int().nonnegative(),parse_errors:exports_external.number().int().nonnegative(),malformed_rows:exports_external.number().int().nonnegative(),clean_attestation_count:exports_external.number().int().nonnegative().optional()}).strict(),SidecarCleanAttestationSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("base_explorer"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict(),exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("micro_lane"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),micro_lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict()]),SidecarCandidateCommon={record_type:exports_external.literal("candidate"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),extracted_from_partial_source:exports_external.boolean(),candidate_id:exports_external.string().min(1),severity:exports_external.enum(CANDIDATE_SEVERITIES),category:exports_external.string().min(1),file_line:exports_external.string().min(1),claim:exports_external.string().min(1),evidence_summary:exports_external.string().min(1),confidence:exports_external.enum(CANDIDATE_CONFIDENCES),risk_impact:exports_external.enum(PR_REVIEW_RISK_IMPACTS).optional(),risk_tags:exports_external.array(exports_external.enum(PR_REVIEW_RISK_TAGS)).optional()},SidecarCandidateSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("base_explorer"),lane:exports_external.string().min(1),micro_lane:exports_external.null(),impact_context:exports_external.string().min(1),invariant_violated:exports_external.null()}).strict(),exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("micro_lane"),lane:exports_external.null(),micro_lane:exports_external.string().min(1),impact_context:exports_external.null(),invariant_violated:exports_external.string().min(1)}).strict()]),BIDI_RANGES=[[8234,8238],[8294,8297]]});function detectRowFormatFamily(rowFields){let trimmed=rowFields.map((f)=>f.trim()),hasImpactContext=trimmed.length>7&&trimmed[7]!=="",hasInvariantViolated=trimmed.length>6&&trimmed[6]!=="";if(hasImpactContext&&!hasInvariantViolated)return"base_explorer";if(hasInvariantViolated&&!hasImpactContext)return"micro_lane";if(hasImpactContext&&hasInvariantViolated)return"base_explorer";throw new UnknownFormatFamilyError}function mapFields(fields,family){let trimmed=fields.map((f)=>f.trim()),names=CANDIDATE_FIELDS[family],result={};for(let i=0;i<names.length;i++)result[names[i]]=i<trimmed.length&&trimmed[i]!==""?trimmed[i]:null;if(family==="base_explorer")result.micro_lane=null,result.invariant_violated=null;else result.lane=null,result.impact_context=null;return result}function getRequiredFields(family){return CANDIDATE_REQUIRED_FIELDS[family]}function assertNonNullCandidateId(value){if(value===null||value==="")throw Error("Invariant violation: null/empty candidate_id reached candidate builder")}function buildInvocationEnvelope(input,flags,formatFamiliesDetected,candidateCount,parseErrors,malformedRows,cleanAttestationCount=0){return{record_type:"invocation",source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,row_format_version:flags.row_format_version,sessionId:input.sessionId,parentSessionId:input.parentSessionId,...flags.producer?{producer:flags.producer}:{},produced_at:input.produced_at,record_version:RECORD_VERSION,format_families_detected:formatFamiliesDetected,candidate_count:candidateCount,parse_errors:parseErrors,malformed_rows:malformedRows,clean_attestation_count:cleanAttestationCount}}function buildEmptyDiagnostics(input,flags){return{candidate_count:0,parse_errors:0,parse_error_details:[],malformed_rows:0,duplicate_id_count:0,duplicate_id_warnings:[],degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:[],clean_attestation_count:0}}function refusalResult(errorCode,errorMessage,input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0);return{error:errorMessage,error_code:errorCode,candidates:[],invocation_envelope:envelope,diagnostics:buildEmptyDiagnostics(input,flags)}}function detectFormatMismatchHint(text){if(text.trim()==="")return;let severityPattern=/\b(CRITICAL|HIGH|MEDIUM|LOW|INFO)\b/,fileLinePattern=/\b\S+\.[a-z]{1,4}:\d+\b/,hasSeverity=severityPattern.test(text),textForFileLine=text.replace(/\b\w+:\/\/\S*/g,""),hasFileLine=fileLinePattern.test(textForFileLine);if(hasSeverity&&hasFileLine)return"Lane output contains severity keywords and file:line references but no parseable [CANDIDATE] rows. The explorer may have emitted findings in prose format instead of pipe-delimited candidate rows.";if(hasSeverity)return"Lane output contains severity keywords but no parseable [CANDIDATE] rows. The explorer may have emitted findings in an unstructured format.";return}function emptyTextResult(input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0),diagnostics=buildEmptyDiagnostics(input,flags),hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint;return{candidates:[],invocation_envelope:envelope,diagnostics}}function parseCandidates(input,flags){let inputParse=ArtifactInputSchema.safeParse(input);if(!inputParse.success)throw Error(`Invalid ArtifactInput: ${inputParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let flagsParse=ParseFlagsSchema.safeParse(flags);if(!flagsParse.success)throw Error(`Invalid ParseFlags: ${flagsParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let validatedInput=inputParse.data,validatedFlags=flagsParse.data;if(validatedInput.artifact_status==="ref-not-found")return refusalResult("ref-not-found","Artifact reference not found in store",validatedInput,validatedFlags);if(validatedInput.artifact_status==="artifact-corrupted")return refusalResult("artifact-corrupted","Artifact data is corrupted",validatedInput,validatedFlags);if(validatedFlags.degraded&&!validatedFlags.accept_degraded)return refusalResult("degraded-source-refused","Degraded source refused by caller",validatedInput,validatedFlags);if(validatedInput.transcriptIncomplete===!0&&!validatedFlags.accept_partial)return refusalResult("partial-source-refused","Partial transcript refused by caller",validatedInput,validatedFlags);if(validatedInput.text.trim()==="")return emptyTextResult(validatedInput,validatedFlags);return parseText(validatedInput,validatedFlags)}function parseText(input,flags){let lines=removeCandidateCodeFences(input.text).split(`
|
|
@@ -471,7 +471,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
|
|
|
471
471
|
lease_expires_at = excluded.lease_expires_at, payload = excluded.payload,
|
|
472
472
|
updated_at = excluded.updated_at`,[input.namespace,input.entityKey,input.generation,input.ownerToken,input.leaseExpiresAt,input.payload,now]),{outcome:"acquired"}})}function releaseCoordinationLease(directory,namespace,entityKey,generation,ownerToken){return withCoordinationTransaction(directory,()=>{return getProjectDb(directory).run(`DELETE FROM coordination_lease
|
|
473
473
|
WHERE namespace = ? AND entity_key = ? AND generation = ? AND owner_token = ?`,[namespace,entityKey,generation,ownerToken]).changes===1})}function importCoordinationOnce(directory,input,importer){if(boundedText(input.source,"source",MAX_KEY_CHARS),boundedText(input.sourceDigest,"sourceDigest",MAX_KEY_CHARS),boundedText(input.emptyNamespace,"emptyNamespace",MAX_KEY_CHARS),!Number.isSafeInteger(input.rowCount)||input.rowCount<0)throw Error("rowCount must be a nonnegative safe integer");let result=withCoordinationTransaction(directory,()=>{let db=getProjectDb(directory);if(db.query("SELECT 1 AS present FROM coordination_import WHERE source = ?").get(input.source))return"already_imported";if((db.query("SELECT COUNT(*) AS count FROM coordination_state WHERE namespace = ?").get(input.emptyNamespace)?.count??0)!==0)return"state_exists";return importer(),db.run(`INSERT INTO coordination_import
|
|
474
|
-
(source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals14.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals14;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals14={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals15.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals15;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals15={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:405"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:465"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:452"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:291"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:678",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:682",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:686",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:746",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:794",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:976",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:984",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1009",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:690",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:700",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_read_uncertain",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:733",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts: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:827",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:841",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:755",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:772",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:759",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:782",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:689",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1178",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:798",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:817",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1411",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:864",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:868",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:964",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:972",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:994",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:882",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:903",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:917",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:934",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:951",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1392",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1024",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1038",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1051",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1065",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1090",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:388",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:2207",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1620",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_recovery_superseded",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1428",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:NO_WORKFLOW_IDS,forbiddenWorkflowIds:FORBID_SESSION,allowsLinks:!1}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1127",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:199",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1149",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1193",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1230",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1256",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1280",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1303",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1332",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1376",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["execution_attempt_recorded",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/services/execution-attempt.ts:265",consumers:["src/commands/report.ts:60"],retentionOwnerIssue:2676,requiredWorkflowIds:REQUIRE_SESSION,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND,otelMapping:"none"}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),callId:exports_external.string().optional(),invocationId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let callId=nonEmptyString(record2.callId);if(callId!==void 0)ids.callId=callId;let invocationId=nonEmptyString(record2.invocationId);if(invocationId!==void 0)ids.invocationId=invocationId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance was `delegation_end` (`src/telemetry.ts` `delegationEnd`): before issue #2789 it coerced token axes with `?? 0`, so they could never appear in `unknown`; it now emits held-null token axes (`?? null`), matching `cost_usd`, and `cost_source: 'unavailable'` still records absence of a cost basis.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),execution_attempt_recorded:Object.freeze(["sessionId","taskId","callId","invocationId","attemptClass","generation","retryIndex","laneId","knowledgeTraceId","outcomeStatus","captured","unknown","cost","duplicateOf"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),plan_recovery_superseded:Object.freeze(["count","trigger"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals16,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals16.createObservation(event,data),content=_internals16.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals16.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals16;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals16.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals16.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals16.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals16.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals16.emit("delegation_end",{sessionId,agentName,taskId,result,...costFields,tokens_input:costFields?.tokens_input??null,tokens_output:costFields?.tokens_output??null,tokens_reasoning:costFields?.tokens_reasoning??null,tokens_cache:costFields?.tokens_cache??null,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals16.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals16.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals16.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals16.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals16.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals16.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals16.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals16.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals16.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals16.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals16.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals16.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals16.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals16.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals16.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals16.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals16.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals16.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals16.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals16.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals16.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals16.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals16.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals16.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals16.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals16.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals16.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},prmHardStopTerminal(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_terminal",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals16.emit("close_archive_result",data)},residueHealth(data){_internals16.emit("residue_health",data)},trainingVaultHealth(data){_internals16.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals16.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals16.emit("skill_usage_health",data)},coreEventsHealth(data){_internals16.emit("core_events_health",data)},shellAuditHealth(data){_internals16.emit("shell_audit_health",data)},trajectoryHealth(data){_internals16.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals16.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals16.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals16.emit("retrieval_routed",{sessionId,...data})},planRecoverySuperseded(data){_internals16.emit("plan_recovery_superseded",data)}},_internals16={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals17.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function walkProjectBoundary(resolved,dependencies){if(hasExplicitProjectBoundary(resolved))return{outcome:"marker-root"};let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)return{outcome:"fail-closed",reason:"depth"};depth++;let parent=path14.dirname(current);if(parent===current)return{outcome:"unclaimed"};if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}return{outcome:"fail-closed",reason:"ancestor-swarm",path:parentSwarm}}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")return{outcome:"fail-closed",reason:"ancestor-indicators",path:parent};if(indicatorState==="present")return{outcome:"claimed",ancestor:parent}}current=parent}}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return;if(walk.outcome==="claimed")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${walk.ancestor}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${walk.ancestor}" already contains a .swarm/ folder. Runtime state must be written to the project root.`);if(walk.reason==="depth")throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);if(walk.reason==="ancestor-swarm")throw warn(`[project-boundary] Cannot inspect ancestor state "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${walk.path}" is inaccessible`);throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${walk.path}" are inaccessible`)}function resolveProjectRootDecision(directory,dependencies=fs8){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{return{kind:"fail-closed",directory,reason:`cannot canonicalize directory "${directory}" — it may not exist or is inaccessible`}}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return{kind:"root",directory:resolved};if(walk.outcome==="claimed")return{kind:"redirect",directory:resolved,owningRoot:walk.ancestor};let reason=walk.reason==="depth"?`ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`:walk.reason==="ancestor-swarm"?`ancestor state "${walk.path}" is inaccessible`:`project indicators in ancestor "${walk.path}" are inaccessible`;return{kind:"fail-closed",directory:resolved,reason}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals17;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals17={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
|
|
474
|
+
(source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals14.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals14;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals14={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals15.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals15;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals15={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:405"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:465"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:452"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:291"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:678",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:682",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:686",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:746",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:794",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:976",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:984",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1009",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:690",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:700",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_read_uncertain",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:733",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:991",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:2120",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:2140",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:827",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:841",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:755",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:772",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:759",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:782",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:689",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1178",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:798",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:817",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1411",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:864",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:868",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:964",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:972",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:994",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:882",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:903",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:917",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:934",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:951",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1392",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1024",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1038",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1051",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1065",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1090",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:388",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:2207",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1620",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_recovery_superseded",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1428",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:NO_WORKFLOW_IDS,forbiddenWorkflowIds:FORBID_SESSION,allowsLinks:!1}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1127",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:199",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1149",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1193",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1230",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1256",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1280",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1303",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1332",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1376",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["execution_attempt_recorded",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/services/execution-attempt.ts:265",consumers:["src/commands/report.ts:60"],retentionOwnerIssue:2676,requiredWorkflowIds:REQUIRE_SESSION,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND,otelMapping:"none"}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),callId:exports_external.string().optional(),invocationId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let callId=nonEmptyString(record2.callId);if(callId!==void 0)ids.callId=callId;let invocationId=nonEmptyString(record2.invocationId);if(invocationId!==void 0)ids.invocationId=invocationId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance was `delegation_end` (`src/telemetry.ts` `delegationEnd`): before issue #2789 it coerced token axes with `?? 0`, so they could never appear in `unknown`; it now emits held-null token axes (`?? null`), matching `cost_usd`, and `cost_source: 'unavailable'` still records absence of a cost basis.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),execution_attempt_recorded:Object.freeze(["sessionId","taskId","callId","invocationId","attemptClass","generation","retryIndex","laneId","knowledgeTraceId","outcomeStatus","captured","unknown","cost","duplicateOf"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),plan_recovery_superseded:Object.freeze(["count","trigger"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals16,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals16.createObservation(event,data),content=_internals16.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals16.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals16;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals16.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals16.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals16.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals16.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals16.emit("delegation_end",{sessionId,agentName,taskId,result,...costFields,tokens_input:costFields?.tokens_input??null,tokens_output:costFields?.tokens_output??null,tokens_reasoning:costFields?.tokens_reasoning??null,tokens_cache:costFields?.tokens_cache??null,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals16.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals16.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals16.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals16.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals16.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals16.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals16.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals16.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals16.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals16.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals16.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals16.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals16.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals16.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals16.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals16.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals16.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals16.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals16.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals16.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals16.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals16.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals16.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals16.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals16.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals16.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals16.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},prmHardStopTerminal(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_terminal",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals16.emit("close_archive_result",data)},residueHealth(data){_internals16.emit("residue_health",data)},trainingVaultHealth(data){_internals16.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals16.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals16.emit("skill_usage_health",data)},coreEventsHealth(data){_internals16.emit("core_events_health",data)},shellAuditHealth(data){_internals16.emit("shell_audit_health",data)},trajectoryHealth(data){_internals16.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals16.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals16.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals16.emit("retrieval_routed",{sessionId,...data})},planRecoverySuperseded(data){_internals16.emit("plan_recovery_superseded",data)}},_internals16={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals17.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function walkProjectBoundary(resolved,dependencies){if(hasExplicitProjectBoundary(resolved))return{outcome:"marker-root"};let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)return{outcome:"fail-closed",reason:"depth"};depth++;let parent=path14.dirname(current);if(parent===current)return{outcome:"unclaimed"};if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}return{outcome:"fail-closed",reason:"ancestor-swarm",path:parentSwarm}}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")return{outcome:"fail-closed",reason:"ancestor-indicators",path:parent};if(indicatorState==="present")return{outcome:"claimed",ancestor:parent}}current=parent}}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return;if(walk.outcome==="claimed")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${walk.ancestor}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${walk.ancestor}" already contains a .swarm/ folder. Runtime state must be written to the project root.`);if(walk.reason==="depth")throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);if(walk.reason==="ancestor-swarm")throw warn(`[project-boundary] Cannot inspect ancestor state "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${walk.path}" is inaccessible`);throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${walk.path}" are inaccessible`)}function resolveProjectRootDecision(directory,dependencies=fs8){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{return{kind:"fail-closed",directory,reason:`cannot canonicalize directory "${directory}" — it may not exist or is inaccessible`}}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return{kind:"root",directory:resolved};if(walk.outcome==="claimed")return{kind:"redirect",directory:resolved,owningRoot:walk.ancestor};let reason=walk.reason==="depth"?`ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`:walk.reason==="ancestor-swarm"?`ancestor state "${walk.path}" is inaccessible`:`project indicators in ancestor "${walk.path}" are inaccessible`;return{kind:"fail-closed",directory:resolved,reason}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals17;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals17={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
|
|
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(`
|
|
@@ -7184,8 +7184,8 @@ ${modeSignal}`:message,usePromptDelivery=config3.event_delivery==="prompt"&&_int
|
|
|
7184
7184
|
`);if(audience==="coder")return[header,policy.avoidPosixExamples?"- Command policy: Prefer PowerShell-native commands and Node.js APIs. Do not start with POSIX commands (ls, grep, rm, cat, export, pwd) unless the environment profile indicates Docker, WSL, or a POSIX shell.":"- Command policy: Use POSIX-native commands and Node.js APIs.","","EXECUTION ENVIRONMENT AWARENESS","- This session includes a runtime environment profile. Follow it exactly.","- Decision ladder when shell commands are necessary:"," 1. Prefer swarm tools and Node.js fs/path APIs."," 2. Use shell only when the task truly requires it."," 3. When shell commands are needed, match the active shell family above."].join(`
|
|
7185
7185
|
`);return[header,"- Test execution policy: Always execute tests via the swarm test runner tool.",policy.avoidPosixExamples?" Do not describe POSIX shell setup commands unless the profile indicates Docker, WSL, or POSIX shell.":" Use POSIX semantics for test commands.","","ENVIRONMENT-SPECIFIC TEST EXECUTION RULES",profile.isWindowsNative?"- Native Windows + PowerShell: Assume PowerShell semantics for paths and env vars. Prefer Pester for PowerShell modules where appropriate.":profile.isWindowsDocker?"- Windows + Docker: Host paths are Windows-style; in-container operations use POSIX semantics.":"- Linux/macOS: Use POSIX semantics for all shell-related reasoning.","- In all modes: prefer the swarm test runner over ad hoc shell commands.","- When tests are skipped due to environment issues, explicitly mention the environment profile assumptions in your verdict."].join(`
|
|
7186
7186
|
`)}var init_prompt_renderer=()=>{};function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync160,readdirSync as readdirSync46,readFileSync as readFileSync131,statSync as statSync93}from"node:fs";import*as path301 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path301.resolve(directory),resolved=path301.resolve(baseDir,concrete),rel3=path301.relative(baseDir,resolved);if(rel3.startsWith("..")||path301.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path301.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path301.join(dir,name);if(existsSync160(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve116)=>setTimeout(()=>resolve116("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync46(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path301.join(dir,entry.name),relPath=path301.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync93(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync131(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path301.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path301.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals245.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals245.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals245.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals245.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals245,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals245={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash102}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash102("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash102("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash102("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash102("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals257,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs180 from"node:fs";import*as path315 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals257.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals257.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals257.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??""),recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},attemptClass:"attempt",outcomeStatus:"unknown"})}catch{}}function terminalAttemptClass(status2){if(status2==="cancelled")return"cancelled";return"result"}function terminalAttemptOutcome(status2){if(status2==="completed")return"success";if(status2==="error"||status2==="failed")return"failure";return"unknown"}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals257.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields);let usageAttested=costFields.cost_source==="reported";recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},...record3.callID?{callId:record3.callID}:{},...record3.laneId?{laneId:record3.laneId}:{},attemptClass:terminalAttemptClass(terminalStatus),outcomeStatus:terminalAttemptOutcome(terminalStatus),cost:{...observations.startedAt!==void 0?{latencyMs:Math.max(0,Date.now()-observations.startedAt)}:{},...usageAttested?{...typeof costFields.tokens_input==="number"?{inputTokens:costFields.tokens_input}:{},...typeof costFields.tokens_output==="number"?{outputTokens:costFields.tokens_output}:{},...typeof costFields.tokens_cache==="number"?{cacheReadTokens:costFields.tokens_cache}:{}}:{},...costFields.cost_source==="reported"&&costFields.cost_usd!==null?{billedCostUsd:costFields.cost_usd}:{},...costFields.cost_source==="estimated"&&costFields.cost_usd!==null?{estimatedCostUsd:costFields.cost_usd}:{}}})}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path315.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs180.existsSync(filePath))return null;let parsed=JSON.parse(fs180.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path315.join(directory,".swarm");fs180.mkdirSync(swarmDir,{recursive:!0});let filePath=path315.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs180.rmSync(filePath,{force:!0});else fs180.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals257;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_execution_attempt();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals257={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals287});import*as fs208 from"node:fs";import*as path346 from"node:path";function mtimeMsOrNull(absPath){try{return fs208.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path346.resolve(directory),resolved=path346.resolve(root,anchor),rel3=path346.relative(root,resolved);if(rel3.startsWith("..")||path346.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path346.resolve(directory),outAbs=path346.resolve(root,outDir),outRel=path346.relative(root,outAbs);if(outRel.startsWith("..")||path346.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path346.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path346.join(outDir,relFile));else checkedDocs.push(path346.join(outDir,relFile))}let traceabilityAbs=path346.join(outAbs,TRACEABILITY_REL),registry4=null;try{if((await fs208.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs208.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry4=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry4=null}let noDocs=checkedDocs.length===0||registry4===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry4?.sections))for(let section2 of registry4.sections){if(!section2||typeof section2.section_id!=="string")continue;if(typeof section2.doc!=="string"||!docMtimes.has(section2.doc))continue;let docMtime=docMtimes.get(section2.doc)??null;if(docMtime===null){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section2.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section2.spec_frs?.length??0)>0)staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals287;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path346.join("reference","reference-impl.md"),"idiom-notes":path346.join("reference","idiom-notes.md")},TRACEABILITY_REL=path346.join("reference","traceability.json");_internals287={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals320,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs236 from"node:fs";import*as path382 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs236.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs236.accessSync(path382.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs236.readFileSync(path382.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals320.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals320.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals320;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals320={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash119}from"node:crypto";import{mkdirSync as mkdirSync101,writeFileSync as writeFileSync66}from"node:fs";import*as path383 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath8}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs153 from"node:fs";import*as path278 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path278.resolve(this.directory,".swarm")}getPlanJsonPath(){return path278.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs153.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs153.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs153.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs153.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs153.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals56.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals56.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path278.join(swarmDir,"plan.json"),markerPath=path278.join(swarmDir,".plan-write-marker"),planStats=fs153.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs153.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve108,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve108(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_feedback_loop_runtime();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash98}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash97}from"node:crypto";import*as fs155 from"node:fs";import*as path280 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey2(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha25610(value){return createHash97("sha256").update(value).digest("hex")}function policyDigest(policy){return sha25610(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey2(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey2(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:receiptStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs155.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs155.openSync(filePath,fs155.constants.O_RDONLY|(fs155.constants.O_NOFOLLOW??0));let openedStat=fs155.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs155.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs155.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs155.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs155.promises.open(filePath,fs155.constants.O_RDONLY|(fs155.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha25610(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs155.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs155.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs155.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs155.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs155.promises.mkdir(path280.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function receiptStructureHash(plan){return computePlanStructureHash({...plan,current_phase:void 0})}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===receiptStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha25610(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha25610(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha25610(correlationKey2(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&¤tPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory),cursorPhase=getCurrentPhase(plan);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receipt.phase===cursorPhase&&cursorPhase<phase))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),cursorPhase=getCurrentPhase(plan),peek=readRawStore(directory);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;if(match[1]==="APPROVED"||match[1]==="PASS")return"pass";if(match[1]==="SKIPPED")return"skip";return"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace,directory);return{...check3,ok:!check3.stale}}var BARE_TASK_ID=/^\d+(?:\.\d+)*$/,SCOPE_CASE_FOLD=process.platform==="win32";function scopeMatchKey(normalized){return SCOPE_CASE_FOLD?normalized.toLowerCase():normalized}function deriveScopeFiles(scope){if(!scope)return null;let files=new Set;for(let fragment of scope.split(",")){let normalized=normalizeAttributionPath(fragment);if(normalized===null||BARE_TASK_ID.test(normalized))continue;files.add(scopeMatchKey(normalized))}return files.size>0?files:null}function scopeDirtySlice(files,scopeFiles){let slice=new Set;for(let file3 of files){let normalized=normalizeAttributionPath(file3);if(normalized!==null&&scopeFiles.has(scopeMatchKey(normalized)))slice.add(normalized)}return slice}function compareStageBWorkspace(record3,actualWorkspace,directory){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;if(!expectedWorkspace)return{stale:!1};if(record3.normalizedAgent==="docs")return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let scopeFiles=deriveScopeFiles(expectedWorkspace.scope),expectedHead=expectedWorkspace.gitHead,currentHead=actualWorkspace.gitHead,expectedChanged=expectedWorkspace.changedFiles,currentChanged=actualWorkspace.changedFiles;if(scopeFiles===null||expectedHead==null||currentHead==null||expectedChanged==null||currentChanged==null||directory===void 0)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let identity=workspaceSnapshotMatches({...expectedWorkspace,gitHead:null,dirtyHash:null},{...actualWorkspace,gitHead:null,dirtyHash:null});if(!identity.ok)return{stale:!0,reason:identity.reason};let committed=committedFilesBetween(directory,expectedHead,currentHead);if(committed===null)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let committedInScope=committed.filter((file3)=>scopeFiles.has(scopeMatchKey(normalizeAttributionPath(file3)??"")));if(committedInScope.length>0){let shown=committedInScope.slice(0,5).join(", "),extra=committedInScope.length>5?` (+${committedInScope.length-5} more)`:"";return{stale:!0,reason:`in-scope committed change: ${shown}${extra}`}}let dispatchDirty=scopeDirtySlice(expectedChanged,scopeFiles),currentDirty=scopeDirtySlice(currentChanged,scopeFiles),dirtied=[...currentDirty].filter((file3)=>!dispatchDirty.has(file3)),cleaned=[...dispatchDirty].filter((file3)=>!currentDirty.has(file3));if(dirtied.length>0||cleaned.length>0)return{stale:!0,reason:`in-scope dirty set changed: +[${dirtied.join(", ")}] -[${cleaned.join(", ")}]`};return{stale:!1}}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles,args2.directory))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict==="skip")return{ok:!1,consumed:!0,skipped:!0,reason:`background ${stageBRole} skipped task ${taskId} — tests not run; re-dispatch the test gate (task stays Stage B eligible; reviewer proof preserved)`};if(stageBRole&&verdict!=="pass"){let rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve108)=>setTimeout(resolve108,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,applied2.skipped?"skipped (tests not run) — re-dispatch the test gate; reviewer proof preserved; task remains Stage B eligible":legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode2(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&¤t.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode2(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash98("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash98("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_package();init_constants();import*as fs156 from"node:fs";import*as path281 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path281.join(projectDirectory,".swarm"),dest=path281.join(swarmDir,"config.example.json");if(fs156.existsSync(dest))return;if(!fs156.existsSync(swarmDir))fs156.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs156.writeFileSync(dest,`${JSON.stringify(example,null,2)}
|
|
7187
|
-
`,"utf-8")}catch{}}init_schema();init_schema();init_core_events();init_delegation_gate();init_utils2();init_injection_budget();init_utils();var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{appendCoreEventSync(directory,{event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100})}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries2,targetRole,directory,options={}){if(!entries2||entries2.length===0)return[];let filtered=[];for(let entry of entries2){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries2.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=input.agent??getActiveAgentName(input.sessionID);if(!targetRole)return;let entries2=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries2,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content),keptRemaining=new Map;for(let content of kept)keptRemaining.set(content,(keptRemaining.get(content)??0)+1);let removedTokens=0;for(let{content}of entries2){let remaining=keptRemaining.get(content)??0;if(remaining>0)keptRemaining.set(content,remaining-1);else removedTokens+=estimateTokens(content)}if(removedTokens>0)deductProducerEmission(input.sessionID,"system-enhancer",removedTokens,{expectedGeneration:input.expectedGeneration});output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs159 from"node:fs";import*as path284 from"node:path";import*as fs158 from"node:fs";import*as path283 from"node:path";import*as crypto13 from"node:crypto";import*as fs157 from"node:fs";import*as path282 from"node:path";var _internals222={readFileSync:fs157.readFileSync,writeFileSync:fs157.writeFileSync,mkdirSync:fs157.mkdirSync,renameSync:fs157.renameSync,existsSync:fs157.existsSync,statSync:fs157.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals222.createHash("sha256").update(content,"utf-8").digest("hex")}function createEmptyContextMap(){return{schema_version:1,generated_at:new Date().toISOString(),repo_fingerprint:"",files:{},task_history:{},decisions:[]}}function loadContextMap(directory){let filePath=path282.join(directory,".swarm","context-map.json");try{if(!_internals222.existsSync(filePath))return null;let raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.schema_version!==1)return null;return parsed}catch{return null}}function saveContextMap(map3,directory){let swarmDir=path282.join(directory,".swarm"),tmpPath=path282.join(swarmDir,"context-map.tmp"),finalPath=path282.join(swarmDir,"context-map.json");_internals222.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals222.writeFileSync(tmpPath,json3,"utf-8"),_internals222.renameSync(tmpPath,finalPath)}function appendTaskHistory(map3,summary){return{...map3,task_history:{...map3.task_history,[summary.task_id]:summary}}}function appendDecision(map3,decision){return{...map3,decisions:[...map3.decisions,decision]}}var EXTENSION_LANGUAGE_MAP={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".rs":"rust",".go":"go",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml",".css":"css",".scss":"scss",".html":"html",".sh":"shell",".bash":"shell",".ps1":"powershell"};function detectLanguage(filePath){let ext=path283.extname(filePath).toLowerCase();return EXTENSION_LANGUAGE_MAP[ext]}var RE_EXPORT_NAMED=/export\s+(?:function|class|interface|type|const|let|var|enum)\s+(\w+)/g,RE_EXPORT_BRACE=/export\s*\{\s*([\w,\s]+)\s*\}/g,RE_IMPORT_FROM=/import\s+.*?\s+from\s+['"](.+?)['"]/g,RE_IMPORT_REQUIRE=/require\(\s*['"](.+?)['"]\s*\)/g,RE_FIRST_COMMENT=/\/\*(.+?)\*\//s,MAX_KEY_SYMBOLS=10,MAX_PURPOSE_LENGTH=200;function extractFileSummary(filePath,content,absolutePath2,existingEntry){let contentHash=computeContentHash3(content),language=detectLanguage(filePath),exportsList=extractExports(content),importsList=extractImports6(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs158.statSync(absolutePath2).mtimeMs}catch{}let base={path:filePath,content_hash:contentHash,mtime_ms:mtimeMs,language,purpose,exports:exportsList.length>0?exportsList:void 0,imports:importsList.length>0?importsList:void 0,key_symbols:keySymbols.length>0?keySymbols:void 0,summary:purpose};if(existingEntry)return{...base,invariants:existingEntry.invariants,risks:existingEntry.risks,tests:existingEntry.tests,last_seen_task_ids:existingEntry.last_seen_task_ids};return base}function isFileStale(entry,currentContent){let currentHash=computeContentHash3(currentContent);return entry.content_hash!==currentHash}function extractExports(content){let symbols2=[],namedRe=new RegExp(RE_EXPORT_NAMED.source,"g"),match;match=namedRe.exec(content);while(match!==null)symbols2.push(match[1]),match=namedRe.exec(content);let braceRe=new RegExp(RE_EXPORT_BRACE.source,"g");match=braceRe.exec(content);while(match!==null){let list=match[1];for(let name of list.split(",")){let trimmed=name.trim();if(trimmed)symbols2.push(trimmed)}match=braceRe.exec(content)}return symbols2}function extractImports6(content){let specifiers=[],fromRe=new RegExp(RE_IMPORT_FROM.source,"g"),match;match=fromRe.exec(content);while(match!==null)specifiers.push(match[1]),match=fromRe.exec(content);let requireRe=new RegExp(RE_IMPORT_REQUIRE.source,"g");match=requireRe.exec(content);while(match!==null)specifiers.push(match[1]),match=requireRe.exec(content);return specifiers}function extractPurpose(content){let match=RE_FIRST_COMMENT.exec(content);if(!match)return"No summary available";let body=match[1].split(`
|
|
7188
|
-
`).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var decisionCounter=0;function nextDecisionId(){return decisionCounter+=1,`A${decisionCounter}`}function deriveFinalStatus(params){if(params.rejection_reasons&¶ms.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals223.existsSync(absolutePath2))return null;return _internals223.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals223.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals223={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs159.existsSync,readFileSync:fs159.readFileSync,readdirSync:fs159.readdirSync,realpathSync:fs159.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path284.join(directory,".swarm","evidence",taskId);if(!_internals223.existsSync(evidenceDir))return result;let evidenceFiles=_internals223.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path284.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals223.loadContextMap(params.directory);if(map3===null)map3=_internals223.createEmptyContextMap();let root=path284.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals223.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path284.resolve(root,filePath),realResolved=_internals223.realpathSync(resolved),relative66=path284.relative(realRoot,realResolved);if(relative66.startsWith("..")||path284.isAbsolute(relative66))continue;let normalizedRelative=relative66.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals223.appendTaskHistory(map3,taskSummary),params.decisions)for(let entry of params.decisions){let decision={id:nextDecisionId(),decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id};map3=_internals223.appendDecision(map3,decision)}return _internals223.saveContextMap(map3,params.directory),map3}catch{try{return _internals223.loadContextMap(params.directory)??_internals223.createEmptyContextMap()}catch{return _internals223.createEmptyContextMap()}}}init_dashboard();init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals224.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals224.now(),hydrated:!0};try{let row=_internals224.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals224.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals224.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate=input.ratePerSecond;if(!(rate>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals224.now();if(refill(bucket,rate,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate*1000);await _internals224.sleep(Math.min(waitMs,1000))}}var _internals224={now:()=>Date.now(),sleep:(ms)=>new Promise((resolve109)=>setTimeout(resolve109,ms)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals225=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals176.boundedAbort,set:(value)=>{_internals176.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals176.boundedDelete,set:(value)=>{_internals176.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals176.log,set:(value)=>{_internals176.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve109,reject)=>{let onAbort=()=>reject(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve109,reject).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId),agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state3();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName2(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName2(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state3();init_task_file();init_invocation_failure();init_state2();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path285=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path285,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
|
|
7187
|
+
`,"utf-8")}catch{}}init_schema();init_schema();init_core_events();init_delegation_gate();init_utils2();init_injection_budget();init_utils();var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{appendCoreEventSync(directory,{event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100})}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries2,targetRole,directory,options={}){if(!entries2||entries2.length===0)return[];let filtered=[];for(let entry of entries2){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries2.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=input.agent??getActiveAgentName(input.sessionID);if(!targetRole)return;let entries2=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries2,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content),keptRemaining=new Map;for(let content of kept)keptRemaining.set(content,(keptRemaining.get(content)??0)+1);let removedTokens=0;for(let{content}of entries2){let remaining=keptRemaining.get(content)??0;if(remaining>0)keptRemaining.set(content,remaining-1);else removedTokens+=estimateTokens(content)}if(removedTokens>0)deductProducerEmission(input.sessionID,"system-enhancer",removedTokens,{expectedGeneration:input.expectedGeneration});output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs159 from"node:fs";import*as path284 from"node:path";import*as fs158 from"node:fs";import*as path283 from"node:path";import*as crypto13 from"node:crypto";import*as fs157 from"node:fs";import*as path282 from"node:path";var _internals222={readFileSync:fs157.readFileSync,writeFileSync:fs157.writeFileSync,mkdirSync:fs157.mkdirSync,renameSync:fs157.renameSync,existsSync:fs157.existsSync,statSync:fs157.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals222.createHash("sha256").update(content,"utf-8").digest("hex")}function createEmptyContextMap(){return{schema_version:1,generated_at:new Date().toISOString(),repo_fingerprint:"",files:{},task_history:{},decisions:[]}}function loadContextMap(directory){let filePath=path282.join(directory,".swarm","context-map.json");try{if(!_internals222.existsSync(filePath))return null;let raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.schema_version!==1||!Array.isArray(parsed.decisions)||typeof parsed.files!=="object"||parsed.files===null||Array.isArray(parsed.files)||typeof parsed.task_history!=="object"||parsed.task_history===null||Array.isArray(parsed.task_history))return null;return parsed}catch{return null}}function saveContextMap(map3,directory){let swarmDir=path282.join(directory,".swarm"),tmpPath=path282.join(swarmDir,"context-map.tmp"),finalPath=path282.join(swarmDir,"context-map.json");_internals222.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals222.writeFileSync(tmpPath,json3,"utf-8"),_internals222.renameSync(tmpPath,finalPath)}function appendTaskHistory(map3,summary){return{...map3,task_history:{...map3.task_history,[summary.task_id]:summary}}}function appendDecision(map3,decision){return{...map3,decisions:[...map3.decisions,decision]}}var EXTENSION_LANGUAGE_MAP={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".rs":"rust",".go":"go",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml",".css":"css",".scss":"scss",".html":"html",".sh":"shell",".bash":"shell",".ps1":"powershell"};function detectLanguage(filePath){let ext=path283.extname(filePath).toLowerCase();return EXTENSION_LANGUAGE_MAP[ext]}var RE_EXPORT_NAMED=/export\s+(?:function|class|interface|type|const|let|var|enum)\s+(\w+)/g,RE_EXPORT_BRACE=/export\s*\{\s*([\w,\s]+)\s*\}/g,RE_IMPORT_FROM=/import\s+.*?\s+from\s+['"](.+?)['"]/g,RE_IMPORT_REQUIRE=/require\(\s*['"](.+?)['"]\s*\)/g,RE_FIRST_COMMENT=/\/\*(.+?)\*\//s,MAX_KEY_SYMBOLS=10,MAX_PURPOSE_LENGTH=200;function extractFileSummary(filePath,content,absolutePath2,existingEntry){let contentHash=computeContentHash3(content),language=detectLanguage(filePath),exportsList=extractExports(content),importsList=extractImports6(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs158.statSync(absolutePath2).mtimeMs}catch{}let base={path:filePath,content_hash:contentHash,mtime_ms:mtimeMs,language,purpose,exports:exportsList.length>0?exportsList:void 0,imports:importsList.length>0?importsList:void 0,key_symbols:keySymbols.length>0?keySymbols:void 0,summary:purpose};if(existingEntry)return{...base,invariants:existingEntry.invariants,risks:existingEntry.risks,tests:existingEntry.tests,last_seen_task_ids:existingEntry.last_seen_task_ids};return base}function isFileStale(entry,currentContent){let currentHash=computeContentHash3(currentContent);return entry.content_hash!==currentHash}function extractExports(content){let symbols2=[],namedRe=new RegExp(RE_EXPORT_NAMED.source,"g"),match;match=namedRe.exec(content);while(match!==null)symbols2.push(match[1]),match=namedRe.exec(content);let braceRe=new RegExp(RE_EXPORT_BRACE.source,"g");match=braceRe.exec(content);while(match!==null){let list=match[1];for(let name of list.split(",")){let trimmed=name.trim();if(trimmed)symbols2.push(trimmed)}match=braceRe.exec(content)}return symbols2}function extractImports6(content){let specifiers=[],fromRe=new RegExp(RE_IMPORT_FROM.source,"g"),match;match=fromRe.exec(content);while(match!==null)specifiers.push(match[1]),match=fromRe.exec(content);let requireRe=new RegExp(RE_IMPORT_REQUIRE.source,"g");match=requireRe.exec(content);while(match!==null)specifiers.push(match[1]),match=requireRe.exec(content);return specifiers}function extractPurpose(content){let match=RE_FIRST_COMMENT.exec(content);if(!match)return"No summary available";let body=match[1].split(`
|
|
7188
|
+
`).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var MAX_CONTEXT_MD_DECISIONS=50,MAX_CONTEXT_MD_CONTENT_CHARS=1e6;function allocateDecisionId(decisions){let max=0n;for(let entry of decisions){if(typeof entry?.id!=="string")continue;let match=/^A(\d+)$/.exec(entry.id);if(!match)continue;let value=BigInt(match[1]);if(value>max)max=value}return`A${(max+1n).toString()}`}function isArchitectRole(role){return role==="architect"||role.endsWith("_architect")}function extractContextDecisionsFromContextMd(directory,options){if(options?.agent_role!==void 0&&!isArchitectRole(options.agent_role))return[];try{let contextMdPath=path284.join(directory,".swarm","context.md");if(!_internals223.existsSync(contextMdPath))return[];let content=_internals223.readFileSync(contextMdPath,"utf-8"),bounded=content.length>MAX_CONTEXT_MD_CONTENT_CHARS?content.slice(content.length-MAX_CONTEXT_MD_CONTENT_CHARS):content,extracted=extractContextDecisions(bounded),decisions=[];for(let entry of extracted){let separatorIndex=entry.text.indexOf(": "),decision=separatorIndex===-1?entry.text:entry.text.slice(0,separatorIndex),rationale=separatorIndex===-1?"":entry.text.slice(separatorIndex+2);if(decision.trim()===""||/^[\s✅]*$/.test(decision))continue;decisions.push({decision:sanitizeContextText(decision),rationale:sanitizeContextText(rationale),...entry.phase===null?{}:{phase:entry.phase}})}if(decisions.length>MAX_CONTEXT_MD_DECISIONS)return decisions.slice(decisions.length-MAX_CONTEXT_MD_DECISIONS);return decisions}catch{return[]}}var MAX_PERSISTED_DECISIONS=200;function deriveFinalStatus(params){if(params.rejection_reasons&¶ms.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals223.existsSync(absolutePath2))return null;return _internals223.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals223.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals223={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs159.existsSync,readFileSync:fs159.readFileSync,readdirSync:fs159.readdirSync,realpathSync:fs159.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path284.join(directory,".swarm","evidence",taskId);if(!_internals223.existsSync(evidenceDir))return result;let evidenceFiles=_internals223.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path284.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals223.loadContextMap(params.directory);if(map3===null)map3=_internals223.createEmptyContextMap();let root=path284.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals223.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path284.resolve(root,filePath),realResolved=_internals223.realpathSync(resolved),relative66=path284.relative(realRoot,realResolved);if(relative66.startsWith("..")||path284.isAbsolute(relative66))continue;let normalizedRelative=relative66.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals223.appendTaskHistory(map3,taskSummary),params.decisions&¶ms.decisions.length>0){let batch=params.decisions.filter((entry)=>(entry.decision??"").trim()!==""),existingTexts=new Set(map3.decisions.map((entry)=>String(entry?.decision??"").trim())),nextSuffix=BigInt(allocateDecisionId(map3.decisions).slice(1));for(let entry of batch){let text=String(entry.decision).trim();if(existingTexts.has(text))continue;existingTexts.add(text);let decision={id:`A${nextSuffix.toString()}`,decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id,...entry.phase===void 0?{}:{phase:entry.phase}};map3=_internals223.appendDecision(map3,decision),nextSuffix+=1n}}if(map3.decisions.length>MAX_PERSISTED_DECISIONS)map3={...map3,decisions:map3.decisions.slice(map3.decisions.length-MAX_PERSISTED_DECISIONS)};return _internals223.saveContextMap(map3,params.directory),map3}catch{try{return _internals223.loadContextMap(params.directory)??_internals223.createEmptyContextMap()}catch{return _internals223.createEmptyContextMap()}}}init_dashboard();init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals224.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals224.now(),hydrated:!0};try{let row=_internals224.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals224.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals224.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate=input.ratePerSecond;if(!(rate>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals224.now();if(refill(bucket,rate,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate*1000);await _internals224.sleep(Math.min(waitMs,1000))}}var _internals224={now:()=>Date.now(),sleep:(ms)=>new Promise((resolve109)=>setTimeout(resolve109,ms)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals225=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals176.boundedAbort,set:(value)=>{_internals176.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals176.boundedDelete,set:(value)=>{_internals176.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals176.log,set:(value)=>{_internals176.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve109,reject)=>{let onAbort=()=>reject(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve109,reject).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId),agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state3();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName2(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName2(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state3();init_task_file();init_invocation_failure();init_state2();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path285=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path285,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
|
|
7189
7189
|
`);lines.push("| Tool | Calls | Success | Failed | Avg Duration |"),lines.push("|------|-------|---------|--------|--------------|");let sorted2=[...swarmState.toolAggregates.values()].sort((a,b)=>b.count-a.count);for(let agg of sorted2){let avgDuration=agg.count>0?Math.round(agg.totalDuration/agg.count):0;lines.push(`| ${agg.tool} | ${agg.count} | ${agg.successCount} | ${agg.failureCount} | ${avgDuration}ms |`)}return lines.join(`
|
|
7190
7190
|
`)}function replaceOrAppendSection(content,heading,newSection){let headingIndex=content.indexOf(heading);if(headingIndex===-1)return`${content.trimEnd()}
|
|
7191
7191
|
|
|
@@ -7206,11 +7206,11 @@ ${COMPACTION_FACTS_CLOSE}`,remaining=MAX_COMPACTION_CONTEXT_CHARS-prefix.length-
|
|
|
7206
7206
|
`;else if(usagePercent>warnThreshold)warningText=`[CONTEXT WARNING: ~${pct}% of context budget used. Consider summarizing to .swarm/context.md]
|
|
7207
7207
|
|
|
7208
7208
|
`;if(warningText){let originalText=lastUserMessage.parts[textPartIndex].text??"";lastUserMessage.parts[textPartIndex].text=`${warningText}${originalText}`}}}function creditTokenReduction(estimatedReduction,currentTokens,targetTokens,usageSource){let availableCredit=usageSource==="provider"?Math.max(0,currentTokens-targetTokens):Math.max(0,currentTokens);return Math.min(Math.max(0,estimatedReduction),availableCredit)}function computeProtectedIndices(messages,preserveLastNTurns){let protectedIndices=new Set,turnCount=0;for(let i=messages.length-1;i>=0&&turnCount<preserveLastNTurns*2;i--){let role=messages[i]?.info?.role;if(role==="user"||role==="assistant"){if(protectedIndices.add(i),role==="user")turnCount++}}let lastUserIdx=-1,lastAssistantIdx=-1;for(let i=messages.length-1;i>=0;i--){let role=messages[i]?.info?.role;if(role==="user"&&lastUserIdx===-1)lastUserIdx=i;if(role==="assistant"&&lastAssistantIdx===-1)lastAssistantIdx=i;if(lastUserIdx!==-1&&lastAssistantIdx!==-1)break}if(lastUserIdx!==-1)protectedIndices.add(lastUserIdx);if(lastAssistantIdx!==-1)protectedIndices.add(lastAssistantIdx);return protectedIndices}function identifyRemovableMessages(messages,priorities,preserveLastNTurns){let protectedIndices=computeProtectedIndices(messages,preserveLastNTurns),HIGH=MessagePriority.HIGH,MEDIUM=MessagePriority.MEDIUM,LOW=MessagePriority.LOW,DISPOSABLE=MessagePriority.DISPOSABLE,byPriority=[[],[],[],[],[]];for(let i=0;i<priorities.length;i++){let priority=priorities[i];if(!protectedIndices.has(i)&&priority>HIGH)byPriority[priority].push(i)}return[...byPriority[DISPOSABLE],...byPriority[LOW],...byPriority[MEDIUM]]}function applyObservationMasking(messages,toRemove){let actualFreedTokens=0,prunedMessages=0,prunedTextParts=0,prunedToolParts=0;for(let idx of toRemove){let msg=messages[idx];if(!msg?.parts||!Array.isArray(msg.parts))continue;let mutatedThisMessage=!1;for(let i=0;i<msg.parts.length;i++){let part=msg.parts[i];if(part.type==="text"&&part.text){if(part.text.includes("[Context pruned")||part.text.includes("[Tool output masked"))continue;let replacement=buildPrunedReplacement(part.text,estimateTokens(part.text),idx);if(!replacement)continue;part.text=replacement.placeholder,actualFreedTokens+=replacement.freedTokens,prunedTextParts++,mutatedThisMessage=!0}else if(part.type==="tool"&&part.state?.status==="completed"&&typeof part.state.output==="string"){let partToolName=typeof part.tool==="string"?part.tool.toLowerCase():"";if(partToolName&&SUMMARIZER_EXEMPT_TOOL_NAMES.includes(partToolName))continue;let output=part.state.output;if(output.includes("[Context pruned")||output.includes("[Tool output masked"))continue;let replacement=buildPrunedReplacement(output,estimateVisibleToolPartTokens(part),idx);if(!replacement)continue;msg.parts[i]={type:"text",text:replacement.placeholder},actualFreedTokens+=replacement.freedTokens,prunedToolParts++,mutatedThisMessage=!0}}if(mutatedThisMessage)prunedMessages++}return{freedTokens:actualFreedTokens,prunedMessages,prunedTextParts,prunedToolParts}}function buildPrunedReplacement(recoveryText,originalTokens,turnIndex){let placeholder=`[Context pruned — message from turn ${turnIndex}, original payload ~${originalTokens} tokens. ${recoveryHint(recoveryText)}]`,maskedTokens=estimateTokens(placeholder);if(maskedTokens>=originalTokens)return;return{placeholder,freedTokens:originalTokens-maskedTokens}}function estimateObservationMaskingReduction(message,turnIndex){if(!message?.parts||!Array.isArray(message.parts))return 0;let reduction=0;for(let part of message.parts){if(part.type==="text"&&part.text){if(part.text.includes("[Context pruned")||part.text.includes("[Tool output masked"))continue;let replacement2=buildPrunedReplacement(part.text,estimateTokens(part.text),turnIndex);if(replacement2)reduction+=replacement2.freedTokens;continue}if(part.type!=="tool"||part.state?.status!=="completed"||typeof part.state.output!=="string")continue;let partToolName=typeof part.tool==="string"?part.tool.toLowerCase():"";if(partToolName&&SUMMARIZER_EXEMPT_TOOL_NAMES.includes(partToolName))continue;let output=part.state.output;if(output.includes("[Context pruned")||output.includes("[Tool output masked"))continue;let replacement=buildPrunedReplacement(output,estimateVisibleToolPartTokens(part),turnIndex);if(replacement)reduction+=replacement.freedTokens}return reduction}var LANE_OUTPUT_REF_PATTERN=/L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}/,GENERIC_RECOVERY_HINT="Use retrieve_summary if needed.";function recoveryHint(originalText){let match=LANE_OUTPUT_REF_PATTERN.exec(originalText);if(match)return`Use retrieve_lane_output with ref ${match[0]} if needed.`;return GENERIC_RECOVERY_HINT}function extractMessageText2(msg){if(!msg?.parts)return"";let chunks=[];for(let part of msg.parts)if(part.type==="text"&&part.text)chunks.push(part.text);else if(part.type==="tool"){let visibleToolText=getVisibleToolPartText(part);if(visibleToolText)chunks.push(visibleToolText)}return chunks.join(`
|
|
7209
|
-
`)}function shouldMaskToolOutput(msg,index,totalMessages,recentWindowSize,threshold){let toolParts=getToolParts(msg);if(toolParts.length===0)return!1;if(toolParts.filter((p)=>p.state?.status==="completed"&&typeof p.state.output==="string").length===0)return!1;let text=extractMessageText2(msg);if(text.includes("[Tool output masked")||text.includes("[Context pruned"))return!1;let exemptList=SUMMARIZER_EXEMPT_TOOL_NAMES,toolNames=getToolNames(msg).map((n)=>n.toLowerCase());if(toolNames.length>0&&toolNames.every((n)=>exemptList.includes(n)))return!1;return totalMessages-1-index>recentWindowSize||text.length>threshold}function maskToolOutput(msg,_threshold){if(!msg?.parts||!Array.isArray(msg.parts))return{freedTokens:0,maskedParts:0};let exemptList=SUMMARIZER_EXEMPT_TOOL_NAMES,freedTokens=0,maskedParts=0;for(let i=0;i<msg.parts.length;i++){let part=msg.parts[i];if(part?.type!=="tool"||part.state?.status!=="completed"||typeof part.state?.output!=="string")continue;let partToolName=typeof part.tool==="string"?part.tool.toLowerCase():"";if(partToolName&&exemptList.includes(partToolName))continue;let output=part.state.output;if(output.includes("[Tool output masked")||output.includes("[Context pruned"))continue;let originalTokens=estimateVisibleToolPartTokens(part),toolName=part.tool||"unknown",excerpt=output.substring(0,200).replace(/\n/g," "),placeholder=`[Tool output masked — ${toolName} original payload ~${originalTokens} tokens. First 200 chars: "${excerpt}..." ${recoveryHint(output)}]`,maskedTokens=estimateTokens(placeholder);if(maskedTokens>=originalTokens)continue;msg.parts[i]={type:"text",text:placeholder},freedTokens+=originalTokens-maskedTokens,maskedParts++}return{freedTokens,maskedParts}}import*as fs163 from"node:fs";import*as path287 from"node:path";import*as fs161 from"node:fs";import*as path285 from"node:path";init_schema();init_core_events();init_extractors();init_knowledge_store();init_utils2();init_atomic_write();init_bun_compat();init_logger();init_path_security();init_swarm_artifact_cache();async function readFileOrEmpty(filePath){for(let attempt=0;attempt<5;attempt++)try{return await readCachedTextFile(filePath,async()=>bunFile(filePath).text())??""}catch(err){if(err?.code!=="ENOENT"||attempt===4)return"";if(!wasRecentlyWrittenByThisProcess(filePath,RECENT_WRITE_WINDOW_MS)&&!wasObservedToExist(filePath))return"";await new Promise((resolve109)=>setTimeout(resolve109,10))}return""}var DEFAULT_CONTEXT_BUDGET_CONFIG={enabled:!0,budgetTokens:DEFAULT_MODEL_CONTEXT_TOKENS,warningPct:70,criticalPct:90,warningMode:"once",warningIntervalTurns:20},COST_PER_1K_TOKENS=0.003;function estimateTokens2(text){if(!text||typeof text!=="string")return 0;return estimateTokens(text)}async function readBudgetState(directory){let content=await readSwarmFileAsync(directory,"session/budget-state.json");if(!content)return null;try{return JSON.parse(content)}catch{return null}}async function writeBudgetState(directory,state2){try{let resolvedPath=validateSwarmPath(directory,"session/budget-state.json"),content=JSON.stringify(state2,null,2);await bunWrite(resolvedPath,content),invalidateCachedArtifact(resolvedPath)}catch(error93){log("[context-budget] Failed to write budget state:",error93 instanceof Error?error93.message:String(error93))}}async function countEvents(directory){return getCoreEventLifetimeCount(directory)}async function getPlanCursorContent(directory,planCursor){let controls=resolvePlanCursorControls(planCursor);if(!controls.enabled)return"";let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent)return"";return extractPlanCursor(planContent,{maxTokens:controls.maxTokens,lookaheadTasks:controls.lookaheadTasks})}async function getContextBudgetReport(directory,assembledSystemPrompt,config3,planCursor){validateProjectDirectory(directory);let timestamp=new Date().toISOString(),systemPromptTokens=estimateTokens2(assembledSystemPrompt),planCursorContent=await getPlanCursorContent(directory,planCursor),planCursorTokens=estimateTokens2(planCursorContent),knowledgeContent=await readFileOrEmpty(resolveSwarmKnowledgePath(directory)),knowledgeTokens=estimateTokens2(knowledgeContent),runMemoryContent=await readSwarmFileAsync(directory,"run-memory.jsonl"),runMemoryTokens=estimateTokens2(runMemoryContent||""),handoffContent=await readSwarmFileAsync(directory,"handoff.md"),handoffTokens=estimateTokens2(handoffContent||""),contextMdContent=await readSwarmFileAsync(directory,"context.md"),contextMdTokens=estimateTokens2(contextMdContent||""),swarmTotalTokens=systemPromptTokens+planCursorTokens+knowledgeTokens+runMemoryTokens+handoffTokens+contextMdTokens,estimatedTurnCount=await countEvents(directory),budgetPct=swarmTotalTokens/config3.budgetTokens*100,status2,recommendation=null;if(budgetPct<config3.warningPct)status2="ok";else if(budgetPct<config3.criticalPct)status2="warning",recommendation="Consider reducing injected context before starting new work.";else status2="critical",recommendation="Reduce injected context or start a fresh session before continuing.";let estimatedSessionTokens=swarmTotalTokens*Math.max(1,estimatedTurnCount);return{timestamp,systemPromptTokens,planCursorTokens,knowledgeTokens,runMemoryTokens,handoffTokens,contextMdTokens,swarmTotalTokens,estimatedTurnCount,estimatedSessionTokens,budgetPct,status:status2,recommendation}}async function formatBudgetWarning(report,directory,config3){if(validateProjectDirectory(directory),report.status==="ok")return null;let state2=await readBudgetState(directory)||{warningFiredAtTurn:null,criticalFiredAtTurn:null,lastInjectedAtTurn:null},currentTurn=report.estimatedTurnCount;if(report.status==="warning"){if(config3.warningMode==="once"&&state2.warningFiredAtTurn!==null)return null;if(config3.warningMode==="interval"&&state2.warningFiredAtTurn!==null&¤tTurn-state2.warningFiredAtTurn<config3.warningIntervalTurns)return null;state2.warningFiredAtTurn=currentTurn,state2.lastInjectedAtTurn=currentTurn,await writeBudgetState(directory,state2)}else if(report.status==="critical")state2.criticalFiredAtTurn=currentTurn,state2.lastInjectedAtTurn=currentTurn;return formatWarningMessage(report)}function formatWarningMessage(report){let budgetPctStr=report.budgetPct.toFixed(1),tokensPerTurn=report.swarmTotalTokens.toLocaleString();if(report.status==="warning")return`[SWARM INJECTION FOOTPRINT: ${budgetPctStr}% of model window — swarm injection footprint ~${tokensPerTurn} tokens/turn (intermediate measurement of per-turn injections, not total prompt pressure). Consider reducing injected context before starting new work.]`;let costPerTurn=(report.swarmTotalTokens/1000*COST_PER_1K_TOKENS).toFixed(3);return`[SWARM INJECTION FOOTPRINT: ${budgetPctStr}% CRITICAL — swarm injection footprint ~${tokensPerTurn} tokens/turn (intermediate measurement of per-turn injections, not total prompt pressure). Reduce injected context or start a fresh session before continuing. Approximate current prompt cost from swarm injections: ~$${costPerTurn}/turn.]`}function estimateTokens3(content){return Math.max(1,estimateTokens2(content))}var _internals227={loadContextMap,createEmptyContextMap,computeContentHash:computeContentHash3,isFileStale,extractFileSummary,estimateTokens:estimateTokens3,readFileSync:fs161.readFileSync,existsSync:fs161.existsSync},DEFAULT_ROLE_PROFILES={coder:{role:"coder",strategy:"scoped_files_plus_rejection",max_files:15,include_rejection:!0,include_coverage:!1,include_claims:!1},reviewer:{role:"reviewer",strategy:"full_scope_plus_checklist",max_files:20,include_rejection:!0,include_coverage:!1,include_claims:!0},critic:{role:"critic",strategy:"plan_context_only",max_files:5,include_rejection:!1,include_coverage:!1,include_claims:!1},test_engineer:{role:"test_engineer",strategy:"code_plus_coverage_targets",max_files:15,include_rejection:!0,include_coverage:!0,include_claims:!1},sme:{role:"sme",strategy:"domain_facts_only",max_files:3,include_rejection:!1,include_coverage:!1,include_claims:!1}};function buildReadPolicy(files,map3,directory,invalidateOnHashChange=!0,contentCache){let policy=[];for(let filePath of files){let entry=map3.files[filePath];if(!entry){policy.push({file_path:filePath,trust_summary:!1,read_original:!0,reason:"file not in context map"});continue}let absolutePath2=path285.join(directory,filePath),currentContent;try{if(_internals227.existsSync(absolutePath2))currentContent=_internals227.readFileSync(absolutePath2,"utf-8")}catch{}if(contentCache!==void 0)contentCache.set(filePath,currentContent);if(currentContent===void 0||invalidateOnHashChange&&_internals227.isFileStale(entry,currentContent))policy.push({file_path:filePath,trust_summary:!1,read_original:!0,reason:"summary is stale (content changed)"});else policy.push({file_path:filePath,trust_summary:!0,read_original:!1,reason:"summary is current"})}return policy}function formatReadPolicyLine(entry){let action2=entry.read_original?"READ original":"TRUST summary";return`- ${entry.file_path}: ${action2} (${entry.reason})`}function formatFileDetails(filePath,entry){let language=entry.language??"unknown",exports=entry.exports?.join(", ")??"none",keySymbols=entry.key_symbols?.join(", ")??"none",summary=entry.summary||entry.purpose||"No summary available";return[`### ${filePath}`,`Language: ${language}`,`Exports: ${exports}`,`Key Symbols: ${keySymbols}`,`Summary: ${summary}`].join(`
|
|
7210
|
-
`)}var PRUNE_ORDER=["## File Details","## Coverage Targets","## Review Checklist","## Required Fix","## Prior Rejection","## Relevant Facts"];function pruneCapsuleContent(sections,tokenEstimate,maxTokens,estimateFn){if(tokenEstimate<=maxTokens)return{prunedSections:sections,prunedTokenEstimate:tokenEstimate};let remaining=[...sections],currentEstimate=tokenEstimate;for(let heading of PRUNE_ORDER){if(currentEstimate<=maxTokens)break;let headingIndex=remaining.indexOf(heading);if(headingIndex===-1)continue;let endIndex=remaining.length;for(let i=headingIndex+1;i<remaining.length;i++)if(remaining[i].startsWith("## ")){endIndex=i;break}remaining=[...remaining.slice(0,headingIndex),...remaining.slice(endIndex)],currentEstimate=estimateFn(remaining.join(`
|
|
7211
|
-
`))}return{prunedSections:remaining,prunedTokenEstimate:currentEstimate}}function buildCapsule(params){let{task_id,agent_role,delegation_reason,directory}=params,generatedAt=new Date().toISOString(),map3=_internals227.loadContextMap(directory)??_internals227.createEmptyContextMap(),profile=DEFAULT_ROLE_PROFILES[agent_role];if(params.mode==="conservative")profile={...profile,max_files:Math.ceil(profile.max_files*1.5)};else if(params.mode==="aggressive")profile={...profile,max_files:Math.max(3,Math.floor(profile.max_files*0.6))};if(params.agent_profiles?.[agent_role]){let customStrategy=params.agent_profiles[agent_role];profile={...profile,strategy:customStrategy}}let filesInScope=params.files_in_scope.slice(0,profile.max_files),contentCache=new Map,readPolicy=buildReadPolicy(filesInScope,map3,directory,params.invalidate_on_hash_change??!0,contentCache),cacheHits=0,cacheMisses=0,staleEntries=0,fileSummaries=[],fileDetailsSections=[];for(let filePath of filesInScope){let entry=map3.files[filePath];if(entry){if(cacheHits++,params.invalidate_on_hash_change!==!1){let currentContent=contentCache.get(filePath);if(currentContent===void 0||_internals227.isFileStale(entry,currentContent))staleEntries++,fileSummaries.push(`- ${filePath} — ${entry.purpose||"No summary available"} (stale)`);else fileSummaries.push(`- ${filePath} — ${entry.purpose||"No summary available"}`)}else fileSummaries.push(`- ${filePath} — ${entry.purpose||"No summary available"}`);fileDetailsSections.push(formatFileDetails(filePath,entry))}else cacheMisses++,fileSummaries.push(`- ${filePath} — No summary available`)}let recommendedReads=readPolicy.filter((p)=>p.read_original).map((p)=>p.file_path),skippedReads=readPolicy.filter((p)=>p.trust_summary).map((p)=>p.file_path),sections=[];if(sections.push(`# Context Capsule: Task ${task_id}`,`Role: ${agent_role} | Reason: ${delegation_reason} | Generated: ${generatedAt}`,""),sections.push("## Task Goal",params.task_goal,""),sections.push(`## Files in Scope (${filesInScope.length} file${filesInScope.length===1?"":"s"})`,...fileSummaries,""),sections.push("## Read Policy",...readPolicy.map(formatReadPolicyLine),""),params.relevant_facts&¶ms.relevant_facts.length>0)sections.push("## Relevant Facts",...params.relevant_facts.map((f)=>`- ${f}`),"");if(profile.include_rejection&¶ms.prior_rejection)sections.push("## Prior Rejection",params.prior_rejection,"");if(profile.include_rejection&¶ms.required_fix)sections.push("## Required Fix",params.required_fix,"");if(profile.include_claims&¶ms.review_checklist&¶ms.review_checklist.length>0)sections.push("## Review Checklist",...params.review_checklist.map((item)=>`- ${item}`),"");if(profile.include_coverage&¶ms.coverage_targets&¶ms.coverage_targets.length>0)sections.push("## Coverage Targets",...params.coverage_targets.map((t)=>`- ${t}`),"");if(fileDetailsSections.length>0)sections.push("## File Details",...fileDetailsSections,"");let content=sections.join(`
|
|
7209
|
+
`)}function shouldMaskToolOutput(msg,index,totalMessages,recentWindowSize,threshold){let toolParts=getToolParts(msg);if(toolParts.length===0)return!1;if(toolParts.filter((p)=>p.state?.status==="completed"&&typeof p.state.output==="string").length===0)return!1;let text=extractMessageText2(msg);if(text.includes("[Tool output masked")||text.includes("[Context pruned"))return!1;let exemptList=SUMMARIZER_EXEMPT_TOOL_NAMES,toolNames=getToolNames(msg).map((n)=>n.toLowerCase());if(toolNames.length>0&&toolNames.every((n)=>exemptList.includes(n)))return!1;return totalMessages-1-index>recentWindowSize||text.length>threshold}function maskToolOutput(msg,_threshold){if(!msg?.parts||!Array.isArray(msg.parts))return{freedTokens:0,maskedParts:0};let exemptList=SUMMARIZER_EXEMPT_TOOL_NAMES,freedTokens=0,maskedParts=0;for(let i=0;i<msg.parts.length;i++){let part=msg.parts[i];if(part?.type!=="tool"||part.state?.status!=="completed"||typeof part.state?.output!=="string")continue;let partToolName=typeof part.tool==="string"?part.tool.toLowerCase():"";if(partToolName&&exemptList.includes(partToolName))continue;let output=part.state.output;if(output.includes("[Tool output masked")||output.includes("[Context pruned"))continue;let originalTokens=estimateVisibleToolPartTokens(part),toolName=part.tool||"unknown",excerpt=output.substring(0,200).replace(/\n/g," "),placeholder=`[Tool output masked — ${toolName} original payload ~${originalTokens} tokens. First 200 chars: "${excerpt}..." ${recoveryHint(output)}]`,maskedTokens=estimateTokens(placeholder);if(maskedTokens>=originalTokens)continue;msg.parts[i]={type:"text",text:placeholder},freedTokens+=originalTokens-maskedTokens,maskedParts++}return{freedTokens,maskedParts}}import*as fs163 from"node:fs";import*as path287 from"node:path";import*as fs161 from"node:fs";import*as path285 from"node:path";init_schema();init_core_events();init_extractors();init_knowledge_store();init_utils2();init_atomic_write();init_bun_compat();init_logger();init_path_security();init_swarm_artifact_cache();async function readFileOrEmpty(filePath){for(let attempt=0;attempt<5;attempt++)try{return await readCachedTextFile(filePath,async()=>bunFile(filePath).text())??""}catch(err){if(err?.code!=="ENOENT"||attempt===4)return"";if(!wasRecentlyWrittenByThisProcess(filePath,RECENT_WRITE_WINDOW_MS)&&!wasObservedToExist(filePath))return"";await new Promise((resolve109)=>setTimeout(resolve109,10))}return""}var DEFAULT_CONTEXT_BUDGET_CONFIG={enabled:!0,budgetTokens:DEFAULT_MODEL_CONTEXT_TOKENS,warningPct:70,criticalPct:90,warningMode:"once",warningIntervalTurns:20},COST_PER_1K_TOKENS=0.003;function estimateTokens2(text){if(!text||typeof text!=="string")return 0;return estimateTokens(text)}async function readBudgetState(directory){let content=await readSwarmFileAsync(directory,"session/budget-state.json");if(!content)return null;try{return JSON.parse(content)}catch{return null}}async function writeBudgetState(directory,state2){try{let resolvedPath=validateSwarmPath(directory,"session/budget-state.json"),content=JSON.stringify(state2,null,2);await bunWrite(resolvedPath,content),invalidateCachedArtifact(resolvedPath)}catch(error93){log("[context-budget] Failed to write budget state:",error93 instanceof Error?error93.message:String(error93))}}async function countEvents(directory){return getCoreEventLifetimeCount(directory)}async function getPlanCursorContent(directory,planCursor){let controls=resolvePlanCursorControls(planCursor);if(!controls.enabled)return"";let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent)return"";return extractPlanCursor(planContent,{maxTokens:controls.maxTokens,lookaheadTasks:controls.lookaheadTasks})}async function getContextBudgetReport(directory,assembledSystemPrompt,config3,planCursor){validateProjectDirectory(directory);let timestamp=new Date().toISOString(),systemPromptTokens=estimateTokens2(assembledSystemPrompt),planCursorContent=await getPlanCursorContent(directory,planCursor),planCursorTokens=estimateTokens2(planCursorContent),knowledgeContent=await readFileOrEmpty(resolveSwarmKnowledgePath(directory)),knowledgeTokens=estimateTokens2(knowledgeContent),runMemoryContent=await readSwarmFileAsync(directory,"run-memory.jsonl"),runMemoryTokens=estimateTokens2(runMemoryContent||""),handoffContent=await readSwarmFileAsync(directory,"handoff.md"),handoffTokens=estimateTokens2(handoffContent||""),contextMdContent=await readSwarmFileAsync(directory,"context.md"),contextMdTokens=estimateTokens2(contextMdContent||""),swarmTotalTokens=systemPromptTokens+planCursorTokens+knowledgeTokens+runMemoryTokens+handoffTokens+contextMdTokens,estimatedTurnCount=await countEvents(directory),budgetPct=swarmTotalTokens/config3.budgetTokens*100,status2,recommendation=null;if(budgetPct<config3.warningPct)status2="ok";else if(budgetPct<config3.criticalPct)status2="warning",recommendation="Consider reducing injected context before starting new work.";else status2="critical",recommendation="Reduce injected context or start a fresh session before continuing.";let estimatedSessionTokens=swarmTotalTokens*Math.max(1,estimatedTurnCount);return{timestamp,systemPromptTokens,planCursorTokens,knowledgeTokens,runMemoryTokens,handoffTokens,contextMdTokens,swarmTotalTokens,estimatedTurnCount,estimatedSessionTokens,budgetPct,status:status2,recommendation}}async function formatBudgetWarning(report,directory,config3){if(validateProjectDirectory(directory),report.status==="ok")return null;let state2=await readBudgetState(directory)||{warningFiredAtTurn:null,criticalFiredAtTurn:null,lastInjectedAtTurn:null},currentTurn=report.estimatedTurnCount;if(report.status==="warning"){if(config3.warningMode==="once"&&state2.warningFiredAtTurn!==null)return null;if(config3.warningMode==="interval"&&state2.warningFiredAtTurn!==null&¤tTurn-state2.warningFiredAtTurn<config3.warningIntervalTurns)return null;state2.warningFiredAtTurn=currentTurn,state2.lastInjectedAtTurn=currentTurn,await writeBudgetState(directory,state2)}else if(report.status==="critical")state2.criticalFiredAtTurn=currentTurn,state2.lastInjectedAtTurn=currentTurn;return formatWarningMessage(report)}function formatWarningMessage(report){let budgetPctStr=report.budgetPct.toFixed(1),tokensPerTurn=report.swarmTotalTokens.toLocaleString();if(report.status==="warning")return`[SWARM INJECTION FOOTPRINT: ${budgetPctStr}% of model window — swarm injection footprint ~${tokensPerTurn} tokens/turn (intermediate measurement of per-turn injections, not total prompt pressure). Consider reducing injected context before starting new work.]`;let costPerTurn=(report.swarmTotalTokens/1000*COST_PER_1K_TOKENS).toFixed(3);return`[SWARM INJECTION FOOTPRINT: ${budgetPctStr}% CRITICAL — swarm injection footprint ~${tokensPerTurn} tokens/turn (intermediate measurement of per-turn injections, not total prompt pressure). Reduce injected context or start a fresh session before continuing. Approximate current prompt cost from swarm injections: ~$${costPerTurn}/turn.]`}function estimateTokens3(content){return Math.max(1,estimateTokens2(content))}var _internals227={loadContextMap,createEmptyContextMap,computeContentHash:computeContentHash3,isFileStale,extractFileSummary,estimateTokens:estimateTokens3,readFileSync:fs161.readFileSync,existsSync:fs161.existsSync},DEFAULT_ROLE_PROFILES={coder:{role:"coder",strategy:"scoped_files_plus_rejection",max_files:15,include_rejection:!0,include_coverage:!1,include_claims:!1,include_decisions:!1},reviewer:{role:"reviewer",strategy:"full_scope_plus_checklist",max_files:20,include_rejection:!0,include_coverage:!1,include_claims:!0,include_decisions:!1},critic:{role:"critic",strategy:"plan_context_only",max_files:5,include_rejection:!1,include_coverage:!1,include_claims:!1,include_decisions:!0},test_engineer:{role:"test_engineer",strategy:"code_plus_coverage_targets",max_files:15,include_rejection:!0,include_coverage:!0,include_claims:!1,include_decisions:!1},sme:{role:"sme",strategy:"domain_facts_only",max_files:3,include_rejection:!1,include_coverage:!1,include_claims:!1,include_decisions:!1}};function buildReadPolicy(files,map3,directory,invalidateOnHashChange=!0,contentCache){let policy=[];for(let filePath of files){let entry=map3.files[filePath];if(!entry){policy.push({file_path:filePath,trust_summary:!1,read_original:!0,reason:"file not in context map"});continue}let absolutePath2=path285.join(directory,filePath),currentContent;try{if(_internals227.existsSync(absolutePath2))currentContent=_internals227.readFileSync(absolutePath2,"utf-8")}catch{}if(contentCache!==void 0)contentCache.set(filePath,currentContent);if(currentContent===void 0||invalidateOnHashChange&&_internals227.isFileStale(entry,currentContent))policy.push({file_path:filePath,trust_summary:!1,read_original:!0,reason:"summary is stale (content changed)"});else policy.push({file_path:filePath,trust_summary:!0,read_original:!1,reason:"summary is current"})}return policy}function formatReadPolicyLine(entry){let action2=entry.read_original?"READ original":"TRUST summary";return`- ${entry.file_path}: ${action2} (${entry.reason})`}function formatFileDetails(filePath,entry){let language=entry.language??"unknown",exports=entry.exports?.join(", ")??"none",keySymbols=entry.key_symbols?.join(", ")??"none",summary=entry.summary||entry.purpose||"No summary available";return[`### ${filePath}`,`Language: ${language}`,`Exports: ${exports}`,`Key Symbols: ${keySymbols}`,`Summary: ${summary}`].join(`
|
|
7210
|
+
`)}var MAX_CAPSULE_DECISIONS=10;function selectCapsuleDecisions(decisions,taskId){let scoped=[],others=[];for(let entry of decisions){if(entry===null||typeof entry!=="object")continue;if(entry.task_id===taskId)scoped.push(entry);else others.push(entry)}let scopedRecent=scoped.slice(Math.max(0,scoped.length-MAX_CAPSULE_DECISIONS)),remaining=Math.max(0,MAX_CAPSULE_DECISIONS-scopedRecent.length),recentOthers=others.slice(Math.max(0,others.length-remaining));return[...scopedRecent,...recentOthers]}function formatDecisionLine(entry){let id=String(entry.id??"").trim()!==""?entry.id:"?",text=String(entry.decision??"").trim()!==""?entry.decision:"(malformed entry)",line=`- [${id}] ${text}`;if(String(entry.rationale??"").trim()!=="")line+=` — ${entry.rationale}`;if(String(entry.task_id??"").trim()!=="")line+=` (task ${entry.task_id})`;return line}var PRUNE_ORDER=["## File Details","## Coverage Targets","## Review Checklist","## Required Fix","## Prior Rejection","## Relevant Facts","## Decisions"];function pruneCapsuleContent(sections,tokenEstimate,maxTokens,estimateFn){if(tokenEstimate<=maxTokens)return{prunedSections:sections,prunedTokenEstimate:tokenEstimate};let remaining=[...sections],currentEstimate=tokenEstimate;for(let heading of PRUNE_ORDER){if(currentEstimate<=maxTokens)break;let headingIndex=remaining.indexOf(heading);if(headingIndex===-1)continue;let endIndex=remaining.length;for(let i=headingIndex+1;i<remaining.length;i++)if(remaining[i].startsWith("## ")){endIndex=i;break}remaining=[...remaining.slice(0,headingIndex),...remaining.slice(endIndex)],currentEstimate=estimateFn(remaining.join(`
|
|
7211
|
+
`))}return{prunedSections:remaining,prunedTokenEstimate:currentEstimate}}function buildCapsule(params){let{task_id,agent_role,delegation_reason,directory}=params,generatedAt=new Date().toISOString(),map3=_internals227.loadContextMap(directory)??_internals227.createEmptyContextMap(),profile=DEFAULT_ROLE_PROFILES[agent_role];if(params.mode==="conservative")profile={...profile,max_files:Math.ceil(profile.max_files*1.5)};else if(params.mode==="aggressive")profile={...profile,max_files:Math.max(3,Math.floor(profile.max_files*0.6))};if(params.agent_profiles?.[agent_role]){let customStrategy=params.agent_profiles[agent_role];profile={...profile,strategy:customStrategy}}let filesInScope=params.files_in_scope.slice(0,profile.max_files),contentCache=new Map,readPolicy=buildReadPolicy(filesInScope,map3,directory,params.invalidate_on_hash_change??!0,contentCache),cacheHits=0,cacheMisses=0,staleEntries=0,fileSummaries=[],fileDetailsSections=[];for(let filePath of filesInScope){let entry=map3.files[filePath];if(entry){if(cacheHits++,params.invalidate_on_hash_change!==!1){let currentContent=contentCache.get(filePath);if(currentContent===void 0||_internals227.isFileStale(entry,currentContent))staleEntries++,fileSummaries.push(`- ${filePath} — ${entry.purpose||"No summary available"} (stale)`);else fileSummaries.push(`- ${filePath} — ${entry.purpose||"No summary available"}`)}else fileSummaries.push(`- ${filePath} — ${entry.purpose||"No summary available"}`);fileDetailsSections.push(formatFileDetails(filePath,entry))}else cacheMisses++,fileSummaries.push(`- ${filePath} — No summary available`)}let recommendedReads=readPolicy.filter((p)=>p.read_original).map((p)=>p.file_path),skippedReads=readPolicy.filter((p)=>p.trust_summary).map((p)=>p.file_path),selectedDecisions=profile.include_decisions&&map3.decisions.length>0?selectCapsuleDecisions(map3.decisions,task_id):void 0,sections=[];if(sections.push(`# Context Capsule: Task ${task_id}`,`Role: ${agent_role} | Reason: ${delegation_reason} | Generated: ${generatedAt}`,""),sections.push("## Task Goal",params.task_goal,""),sections.push(`## Files in Scope (${filesInScope.length} file${filesInScope.length===1?"":"s"})`,...fileSummaries,""),sections.push("## Read Policy",...readPolicy.map(formatReadPolicyLine),""),selectedDecisions&&selectedDecisions.length>0)sections.push("## Decisions",...selectedDecisions.map(formatDecisionLine),"");if(params.relevant_facts&¶ms.relevant_facts.length>0)sections.push("## Relevant Facts",...params.relevant_facts.map((f)=>`- ${f}`),"");if(profile.include_rejection&¶ms.prior_rejection)sections.push("## Prior Rejection",params.prior_rejection,"");if(profile.include_rejection&¶ms.required_fix)sections.push("## Required Fix",params.required_fix,"");if(profile.include_claims&¶ms.review_checklist&¶ms.review_checklist.length>0)sections.push("## Review Checklist",...params.review_checklist.map((item)=>`- ${item}`),"");if(profile.include_coverage&¶ms.coverage_targets&¶ms.coverage_targets.length>0)sections.push("## Coverage Targets",...params.coverage_targets.map((t)=>`- ${t}`),"");if(fileDetailsSections.length>0)sections.push("## File Details",...fileDetailsSections,"");let content=sections.join(`
|
|
7212
7212
|
`),tokenEstimate=_internals227.estimateTokens(content),maxCapsuleTokens=params.max_capsule_tokens??2000,prunedContent=content;if(tokenEstimate>maxCapsuleTokens){let{prunedSections,prunedTokenEstimate}=pruneCapsuleContent(sections,tokenEstimate,maxCapsuleTokens,_internals227.estimateTokens);prunedContent=prunedSections.join(`
|
|
7213
|
-
`),tokenEstimate=prunedTokenEstimate}return{capsule:{task_id,agent_role,delegation_reason,generated_at:generatedAt,files_in_scope:filesInScope,task_goal:params.task_goal,prior_rejection:params.prior_rejection,required_fix:params.required_fix,relevant_facts:params.relevant_facts??[],review_checklist:params.review_checklist,coverage_targets:params.coverage_targets,read_policy:readPolicy,content:prunedContent},metadata:{success:!0,capsule_path:"",token_estimate:tokenEstimate,cache_hits:cacheHits,cache_misses:cacheMisses,stale_entries:staleEntries,recommended_reads:recommendedReads,skipped_reads:skippedReads}}}init_utils2();init_caps();import*as fs162 from"node:fs";import*as path286 from"node:path";var _internals228={writeFileSync:fs162.writeFileSync,readFileSync:fs162.readFileSync,existsSync:fs162.existsSync,mkdirSync:fs162.mkdirSync,readdirSync:fs162.readdirSync,statSync:fs162.statSync,unlinkSync:fs162.unlinkSync,renameSync:fs162.renameSync},TASK_ID_RE=/^\d+(?:\.\d+)+$/;function isValidTaskId3(taskId){return TASK_ID_RE.test(taskId)}function capsulePath(taskId,directory){return path286.join(directory,".swarm","capsules",`${taskId}.json`)}function estimateCapsuleTokens(content){return Math.max(1,estimateTokens(content))}function saveCapsule(capsule,directory){try{if(!isValidTaskId3(capsule.task_id))return{success:!1,capsule_path:"",token_estimate:0,cache_hits:0,cache_misses:0,stale_entries:0,recommended_reads:[],skipped_reads:[]};let capsulesDir=path286.join(directory,".swarm","capsules"),finalPath=capsulePath(capsule.task_id,directory),tmpPath=path286.join(capsulesDir,`capsule-${capsule.task_id}.tmp`);_internals228.mkdirSync(capsulesDir,{recursive:!0});let json3=JSON.stringify(capsule,null,2);return _internals228.writeFileSync(tmpPath,json3,"utf-8"),_internals228.renameSync(tmpPath,finalPath),{success:!0,capsule_path:finalPath,token_estimate:estimateCapsuleTokens(capsule.content),cache_hits:0,cache_misses:0,stale_entries:0,recommended_reads:capsule.read_policy.filter((p)=>p.read_original).map((p)=>p.file_path),skipped_reads:capsule.read_policy.filter((p)=>p.trust_summary).map((p)=>p.file_path)}}catch{return{success:!1,capsule_path:"",token_estimate:0,cache_hits:0,cache_misses:0,stale_entries:0,recommended_reads:[],skipped_reads:[]}}}init_telemetry2();init_utils2();init_telemetry();function estimateTokensFromBytes(bytes){if(!Number.isFinite(bytes)||bytes<=0)return 0;return Math.ceil(bytes/4)}function measureCitedFileTokens(filePaths,statFn,maxFiles=32){let total=0,unmeasured=0,cap2=Math.min(filePaths.length,maxFiles);for(let i=0;i<cap2;i++)try{total+=estimateTokensFromBytes(statFn(filePaths[i]).size)}catch{unmeasured+=1}if(filePaths.length>maxFiles)unmeasured+=filePaths.length-maxFiles;return{total,unmeasured}}var _internals229={emit};function recordContextSourceAttribution(input){try{if(input.citedFileTokensTotal===void 0||input.citedFileTokensTotal===null||!Number.isFinite(input.citedFileTokensTotal)||input.citedFileTokensTotal<=0||!Number.isFinite(input.tokensReturned)||input.tokensReturned<0)return!1;let savedEstimate=Math.max(0,input.citedFileTokensTotal-input.tokensReturned);return _internals229.emit("context_source_attribution",{sessionId:input.sessionId,...input.taskId!==void 0&&input.taskId!==""?{taskId:input.taskId}:{},source:input.source,tokensReturned:Math.ceil(input.tokensReturned),tokensSavedEstimate:savedEstimate,estimate:!0}),!0}catch{return!1}}init_injection_budget();init_state2();init_logger();function resolveCapsuleDelegationReason(session,agentRole,taskId){if(agentRole==="critic")return"critic_plan_review";if(!session)return"new_task";let workflowState=session.taskWorkflowStates?.get(taskId);if(workflowState==="tests_run")return"test_failure_fix";if(workflowState==="reviewer_run")return"reviewer_rejection_fix";return"new_task"}function extractTaskGoal(taskId,directory){try{let planPath=path287.join(directory,".swarm","plan.json"),raw=fs163.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan.phases))return"";for(let phase of plan.phases){if(!Array.isArray(phase.tasks))continue;for(let task2 of phase.tasks)if(task2.id===taskId&&typeof task2.description==="string")return task2.description}return""}catch{return""}}var _internals230={buildCapsule,recordTelemetry,saveCapsule,measureCitedFileTokens,recordContextSourceAttribution,getActiveAgent:(sessionID)=>swarmState.activeAgent.get(sessionID),getSession:(sessionID)=>swarmState.agentSessions.get(sessionID),getCurrentTaskId:(sessionID)=>{return swarmState.agentSessions.get(sessionID)?.currentTaskId??null},readScopeFile:(taskId,dir)=>{try{let scopePath=path287.join(dir,".swarm","scopes",`scope-${taskId}.json`),raw=fs163.readFileSync(scopePath,"utf-8"),parsed=JSON.parse(raw);return Array.isArray(parsed.files)?parsed.files:[]}catch{return[]}},resolveCapsuleDelegationReason,extractTaskGoal},OPENCODE_NATIVE_AGENTS2=new Set(["build","plan","general","explore","compaction","title","summary"]),VALID_AGENT_ROLES=new Set(["coder","reviewer","critic","test_engineer","sme"]);function extractCapsuleRole(agentName){let normalized=agentName.toLowerCase();if(normalized==="architect"||OPENCODE_NATIVE_AGENTS2.has(normalized))return;for(let role of VALID_AGENT_ROLES)if(normalized===role||normalized.endsWith(`_${role}`))return role;return}function createContextCapsuleInjectHook(config3,directory){if(config3.context_map?.enabled!==!0)return{};return{"experimental.chat.system.transform":async(_input,output)=>{try{await injectCapsule(_input,output,config3,directory)}catch{}}}}async function injectCapsule(input,output,config3,directory){let sessionID=input.sessionID;if(!sessionID)return;let agentName=_internals230.getActiveAgent(sessionID);if(!agentName)return;let role=extractCapsuleRole(agentName);if(!role)return;let effectiveTaskId=_internals230.getCurrentTaskId(sessionID)??"unknown",files=_internals230.readScopeFile(effectiveTaskId,directory);if(files.length===0)return;let localMaxCapsuleTokens=config3.context_map?.max_capsule_tokens??2000,claim=claimTurnBudget(sessionID,"context-capsule",localMaxCapsuleTokens,{localMaxTokens:localMaxCapsuleTokens,surface:"system"});if(!claim.ledgerPresent)log("context-capsule: no injection ledger this turn — failing open to local max_capsule_tokens; unified hard ceiling unavailable");let grantedCapsuleTokens=claim.granted,maxTokens=grantedCapsuleTokens,delegationReason=_internals230.resolveCapsuleDelegationReason(_internals230.getSession(sessionID),role,effectiveTaskId),taskGoal=_internals230.extractTaskGoal(effectiveTaskId,directory),{capsule,metadata}=_internals230.buildCapsule({task_id:effectiveTaskId,agent_role:role,delegation_reason:delegationReason,files_in_scope:files,task_goal:taskGoal,directory,max_capsule_tokens:maxTokens,mode:config3.context_map?.mode,invalidate_on_hash_change:config3.context_map?.invalidate_on_hash_change,agent_profiles:config3.context_map?.agent_profiles});if(!capsule.content.trim())return;output.system.push(capsule.content),recordProducerEmission(sessionID,"context-capsule",estimateTokens(capsule.content),Math.max(0,grantedCapsuleTokens-estimateTokens(capsule.content)),"system");try{let cited=_internals230.measureCitedFileTokens(files,(p)=>fs163.statSync(path287.join(directory,p)));if(cited.total>0)_internals230.recordContextSourceAttribution({sessionId:sessionID,taskId:effectiveTaskId,source:"context_pack",tokensReturned:metadata.token_estimate,citedFileTokensTotal:cited.total})}catch{}try{_internals230.saveCapsule(capsule,directory)}catch{}let telemetryEntry={timestamp:new Date().toISOString(),task_id:effectiveTaskId,agent_role:role,delegation_reason:capsule.delegation_reason,token_estimate:metadata.token_estimate,cache_hits:metadata.cache_hits,cache_misses:metadata.cache_misses,stale_entries:metadata.stale_entries,recommended_reads:metadata.recommended_reads.length,skipped_reads:metadata.skipped_reads.length,success:metadata.success};try{_internals230.recordTelemetry(telemetryEntry,directory)}catch{}}init_curator_llm_factory();init_delegation_gate();init_core_events();init_utils2();var SANITIZATION_PATTERNS=[/\b\d+(st|nd|rd|th)\s+(attempt|try|time)\b/gi,/\b(5th|fifth|final|last)\s+attempt\b/gi,/attempt\s+\d+\s*\/\s*\d+/gi,/\bthis\s+is\s+(the\s+)?(5th|fifth|final|last)\b/gi,/\bwe('re|\s+are)\s+(behind|late)\b/gi,/\buser\s+is\s+waiting\b/gi,/\bship\s+(this|it)\s+now\b/gi,/\bor\s+I('ll|\s+will)\s+(stop|halt|alert)\b/gi,/\bor\s+all\s+work\s+stops\b/gi,/\bthis\s+will\s+(delay|block)\s+everything\b/gi,/\b(I'm|I\s+am)\s+(frustrated|disappointed)\b/gi];function sanitizeMessage(text,patterns=SANITIZATION_PATTERNS){let sanitized=text,stripped=[];for(let pattern of patterns){let matches=sanitized.match(pattern);if(matches)stripped.push(...matches),sanitized=sanitized.replace(pattern,"")}return sanitized=sanitized.replace(/\s+/g," ").trim(),{sanitized,modified:stripped.length>0,stripped}}function isGateAgentMessage(agentName){let gateAgents=["reviewer","test_engineer","critic","test-engineer"],normalized=agentName.toLowerCase().replace(/-/g,"_");return gateAgents.includes(normalized)}function createDelegationSanitizerHook(directory){return safeHook(async(_input,output)=>{let messages=output?.messages;if(!messages||!Array.isArray(messages))return;for(let message of messages){let info=message?.info;if(!info)continue;let agent=info.agent;if(!agent||!isGateAgentMessage(agent))continue;if(!message.parts||!Array.isArray(message.parts))continue;for(let part of message.parts){if(part?.type!=="text"||!part.text)continue;let originalText=part.text,result=sanitizeMessage(originalText);if(result.modified){part.text=result.sanitized;try{let event={event:"message_sanitized",agent,original_length:originalText.length,stripped_count:result.stripped.length,stripped_patterns:result.stripped,timestamp:new Date().toISOString()};appendCoreEventSync(directory,event)}catch{}}}}})}init_constants();init_schema();init_state2();function createDelegationTrackerHook(config3,guardrailsEnabled=!0,directory){return async(input,_output)=>{let now2=Date.now();if(!input.agent||input.agent===""){let session2=ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME,directory);if(session2.delegationActive=!1,swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),updateAgentEventTime(input.sessionID),guardrailsEnabled)beginInvocation(input.sessionID,ORCHESTRATOR_NAME);return}let agentName=input.agent,previousAgent=swarmState.activeAgent.get(input.sessionID);swarmState.activeAgent.set(input.sessionID,agentName);let isArchitect=stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME,session=ensureAgentSession(input.sessionID,agentName,directory);if(session.delegationActive=!isArchitect,!isArchitect)session.lastDelegationReason="normal_delegation";if(recordPhaseAgentDispatch(input.sessionID,agentName),guardrailsEnabled)beginInvocation(input.sessionID,agentName);let delegationTrackerEnabled=config3?.hooks?.delegation_tracker===!0,delegationGateEnabled=config3?.hooks?.delegation_gate!==!1;if((delegationTrackerEnabled||delegationGateEnabled)&&previousAgent&&previousAgent!==agentName){let entry={from:previousAgent,to:agentName,timestamp:now2};if(!swarmState.delegationChains.has(input.sessionID))swarmState.delegationChains.set(input.sessionID,[]);if(swarmState.delegationChains.get(input.sessionID)?.push(entry),delegationTrackerEnabled)swarmState.pendingEvents++}}}init_extractors();init_agent_model();init_injection_budget();init_state2();init_logger();init_model_limits();init_system_guidance_carrier();init_utils2();function createFinalContextAccountingStep(options){let{config:config3,resolveAgentModelFn}=options;return async(_input,output)=>{let messages=output?.messages;if(!messages||messages.length===0)return;try{let sessionID=extractSessionId2(messages);if(!sessionID)return;if(config3.context_budget?.enabled===!1)return;let agentName;for(let i=messages.length-1;i>=0;i--){let info=messages[i]?.info;if(isGuidanceCarrier(messages[i]))continue;if(info?.role==="user"&&info.agent){agentName=info.agent;break}}let configuredTargetModel=agentName&&resolveAgentModelFn?resolveAgentModelFn(agentName):void 0,targetModelInfo=configuredTargetModel?parseAgentModel(configuredTargetModel):void 0,liveModelInfo=getLiveContextModelIdentity(sessionID),{modelID,providerID}=targetModelInfo??liveModelInfo??extractModelInfo(messages),liveContextLimit=getLiveContextWindow(sessionID,{modelID,providerID}),modelLimit=resolveModelLimit(modelID,providerID,config3.context_budget?.model_limits??{},liveContextLimit,options.directory).limit;if(modelLimit<=0)return;let usage=computeContextUsage(messages),ledger=getTurnLedgerSummary(sessionID),systemSurfaceTokens=0;if(ledger){for(let producer of ledger.producers)if(producer.surface==="system")systemSurfaceTokens+=producer.emitted}let usedTokens=usage.tokensUsed+systemSurfaceTokens,warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,pctWithout=usedTokens/modelLimit*100,band=pctWithout/100>criticalThreshold?"critical":pctWithout/100>warnThreshold?"warn":"ok",warningText="";if(band!=="ok"){if(!getFinalAccountingWarningBand(sessionID,band)){let pctStr=Math.min(999,Math.round(pctWithout)).toString(),limitK=Math.round(modelLimit/1000),source=usage.source==="provider"?"provider-reported usage + estimated tail":"chars→tokens heuristic estimate";warningText=band==="critical"?`[CONTEXT PRESSURE — CRITICAL (estimated): ~${pctStr}% of the ~${limitK}K-token window (${source}). Consider compacting now or offloading detail to .swarm/context.md. Advisory only — this message removed no content.]
|
|
7213
|
+
`),tokenEstimate=prunedTokenEstimate}return{capsule:{task_id,agent_role,delegation_reason,generated_at:generatedAt,files_in_scope:filesInScope,task_goal:params.task_goal,prior_rejection:params.prior_rejection,required_fix:params.required_fix,relevant_facts:params.relevant_facts??[],review_checklist:params.review_checklist,coverage_targets:params.coverage_targets,decisions:selectedDecisions,read_policy:readPolicy,content:prunedContent},metadata:{success:!0,capsule_path:"",token_estimate:tokenEstimate,cache_hits:cacheHits,cache_misses:cacheMisses,stale_entries:staleEntries,recommended_reads:recommendedReads,skipped_reads:skippedReads}}}init_utils2();init_caps();import*as fs162 from"node:fs";import*as path286 from"node:path";var _internals228={writeFileSync:fs162.writeFileSync,readFileSync:fs162.readFileSync,existsSync:fs162.existsSync,mkdirSync:fs162.mkdirSync,readdirSync:fs162.readdirSync,statSync:fs162.statSync,unlinkSync:fs162.unlinkSync,renameSync:fs162.renameSync},TASK_ID_RE=/^\d+(?:\.\d+)+$/;function isValidTaskId3(taskId){return TASK_ID_RE.test(taskId)}function capsulePath(taskId,directory){return path286.join(directory,".swarm","capsules",`${taskId}.json`)}function estimateCapsuleTokens(content){return Math.max(1,estimateTokens(content))}function saveCapsule(capsule,directory){try{if(!isValidTaskId3(capsule.task_id))return{success:!1,capsule_path:"",token_estimate:0,cache_hits:0,cache_misses:0,stale_entries:0,recommended_reads:[],skipped_reads:[]};let capsulesDir=path286.join(directory,".swarm","capsules"),finalPath=capsulePath(capsule.task_id,directory),tmpPath=path286.join(capsulesDir,`capsule-${capsule.task_id}.tmp`);_internals228.mkdirSync(capsulesDir,{recursive:!0});let json3=JSON.stringify(capsule,null,2);return _internals228.writeFileSync(tmpPath,json3,"utf-8"),_internals228.renameSync(tmpPath,finalPath),{success:!0,capsule_path:finalPath,token_estimate:estimateCapsuleTokens(capsule.content),cache_hits:0,cache_misses:0,stale_entries:0,recommended_reads:capsule.read_policy.filter((p)=>p.read_original).map((p)=>p.file_path),skipped_reads:capsule.read_policy.filter((p)=>p.trust_summary).map((p)=>p.file_path)}}catch{return{success:!1,capsule_path:"",token_estimate:0,cache_hits:0,cache_misses:0,stale_entries:0,recommended_reads:[],skipped_reads:[]}}}init_telemetry2();init_utils2();init_telemetry();function estimateTokensFromBytes(bytes){if(!Number.isFinite(bytes)||bytes<=0)return 0;return Math.ceil(bytes/4)}function measureCitedFileTokens(filePaths,statFn,maxFiles=32){let total=0,unmeasured=0,cap2=Math.min(filePaths.length,maxFiles);for(let i=0;i<cap2;i++)try{total+=estimateTokensFromBytes(statFn(filePaths[i]).size)}catch{unmeasured+=1}if(filePaths.length>maxFiles)unmeasured+=filePaths.length-maxFiles;return{total,unmeasured}}var _internals229={emit};function recordContextSourceAttribution(input){try{if(input.citedFileTokensTotal===void 0||input.citedFileTokensTotal===null||!Number.isFinite(input.citedFileTokensTotal)||input.citedFileTokensTotal<=0||!Number.isFinite(input.tokensReturned)||input.tokensReturned<0)return!1;let savedEstimate=Math.max(0,input.citedFileTokensTotal-input.tokensReturned);return _internals229.emit("context_source_attribution",{sessionId:input.sessionId,...input.taskId!==void 0&&input.taskId!==""?{taskId:input.taskId}:{},source:input.source,tokensReturned:Math.ceil(input.tokensReturned),tokensSavedEstimate:savedEstimate,estimate:!0}),!0}catch{return!1}}init_injection_budget();init_state2();init_logger();function resolveCapsuleDelegationReason(session,agentRole,taskId){if(agentRole==="critic")return"critic_plan_review";if(!session)return"new_task";let workflowState=session.taskWorkflowStates?.get(taskId);if(workflowState==="tests_run")return"test_failure_fix";if(workflowState==="reviewer_run")return"reviewer_rejection_fix";return"new_task"}function extractTaskGoal(taskId,directory){try{let planPath=path287.join(directory,".swarm","plan.json"),raw=fs163.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan.phases))return"";for(let phase of plan.phases){if(!Array.isArray(phase.tasks))continue;for(let task2 of phase.tasks)if(task2.id===taskId&&typeof task2.description==="string")return task2.description}return""}catch{return""}}var _internals230={buildCapsule,recordTelemetry,saveCapsule,measureCitedFileTokens,recordContextSourceAttribution,getActiveAgent:(sessionID)=>swarmState.activeAgent.get(sessionID),getSession:(sessionID)=>swarmState.agentSessions.get(sessionID),getCurrentTaskId:(sessionID)=>{return swarmState.agentSessions.get(sessionID)?.currentTaskId??null},readScopeFile:(taskId,dir)=>{try{let scopePath=path287.join(dir,".swarm","scopes",`scope-${taskId}.json`),raw=fs163.readFileSync(scopePath,"utf-8"),parsed=JSON.parse(raw);return Array.isArray(parsed.files)?parsed.files:[]}catch{return[]}},resolveCapsuleDelegationReason,extractTaskGoal},OPENCODE_NATIVE_AGENTS2=new Set(["build","plan","general","explore","compaction","title","summary"]),VALID_AGENT_ROLES=new Set(["coder","reviewer","critic","test_engineer","sme"]);function extractCapsuleRole(agentName){let normalized=agentName.toLowerCase();if(normalized==="architect"||OPENCODE_NATIVE_AGENTS2.has(normalized))return;for(let role of VALID_AGENT_ROLES)if(normalized===role||normalized.endsWith(`_${role}`))return role;return}function createContextCapsuleInjectHook(config3,directory){if(config3.context_map?.enabled!==!0)return{};return{"experimental.chat.system.transform":async(_input,output)=>{try{await injectCapsule(_input,output,config3,directory)}catch{}}}}async function injectCapsule(input,output,config3,directory){let sessionID=input.sessionID;if(!sessionID)return;let agentName=_internals230.getActiveAgent(sessionID);if(!agentName)return;let role=extractCapsuleRole(agentName);if(!role)return;let effectiveTaskId=_internals230.getCurrentTaskId(sessionID)??"unknown",files=_internals230.readScopeFile(effectiveTaskId,directory);if(files.length===0)return;let localMaxCapsuleTokens=config3.context_map?.max_capsule_tokens??2000,claim=claimTurnBudget(sessionID,"context-capsule",localMaxCapsuleTokens,{localMaxTokens:localMaxCapsuleTokens,surface:"system"});if(!claim.ledgerPresent)log("context-capsule: no injection ledger this turn — failing open to local max_capsule_tokens; unified hard ceiling unavailable");let grantedCapsuleTokens=claim.granted,maxTokens=grantedCapsuleTokens,delegationReason=_internals230.resolveCapsuleDelegationReason(_internals230.getSession(sessionID),role,effectiveTaskId),taskGoal=_internals230.extractTaskGoal(effectiveTaskId,directory),{capsule,metadata}=_internals230.buildCapsule({task_id:effectiveTaskId,agent_role:role,delegation_reason:delegationReason,files_in_scope:files,task_goal:taskGoal,directory,max_capsule_tokens:maxTokens,mode:config3.context_map?.mode,invalidate_on_hash_change:config3.context_map?.invalidate_on_hash_change,agent_profiles:config3.context_map?.agent_profiles});if(!capsule.content.trim())return;output.system.push(capsule.content),recordProducerEmission(sessionID,"context-capsule",estimateTokens(capsule.content),Math.max(0,grantedCapsuleTokens-estimateTokens(capsule.content)),"system");try{let cited=_internals230.measureCitedFileTokens(files,(p)=>fs163.statSync(path287.join(directory,p)));if(cited.total>0)_internals230.recordContextSourceAttribution({sessionId:sessionID,taskId:effectiveTaskId,source:"context_pack",tokensReturned:metadata.token_estimate,citedFileTokensTotal:cited.total})}catch{}try{_internals230.saveCapsule(capsule,directory)}catch{}let telemetryEntry={timestamp:new Date().toISOString(),task_id:effectiveTaskId,agent_role:role,delegation_reason:capsule.delegation_reason,token_estimate:metadata.token_estimate,cache_hits:metadata.cache_hits,cache_misses:metadata.cache_misses,stale_entries:metadata.stale_entries,recommended_reads:metadata.recommended_reads.length,skipped_reads:metadata.skipped_reads.length,success:metadata.success};try{_internals230.recordTelemetry(telemetryEntry,directory)}catch{}}init_curator_llm_factory();init_delegation_gate();init_core_events();init_utils2();var SANITIZATION_PATTERNS=[/\b\d+(st|nd|rd|th)\s+(attempt|try|time)\b/gi,/\b(5th|fifth|final|last)\s+attempt\b/gi,/attempt\s+\d+\s*\/\s*\d+/gi,/\bthis\s+is\s+(the\s+)?(5th|fifth|final|last)\b/gi,/\bwe('re|\s+are)\s+(behind|late)\b/gi,/\buser\s+is\s+waiting\b/gi,/\bship\s+(this|it)\s+now\b/gi,/\bor\s+I('ll|\s+will)\s+(stop|halt|alert)\b/gi,/\bor\s+all\s+work\s+stops\b/gi,/\bthis\s+will\s+(delay|block)\s+everything\b/gi,/\b(I'm|I\s+am)\s+(frustrated|disappointed)\b/gi];function sanitizeMessage(text,patterns=SANITIZATION_PATTERNS){let sanitized=text,stripped=[];for(let pattern of patterns){let matches=sanitized.match(pattern);if(matches)stripped.push(...matches),sanitized=sanitized.replace(pattern,"")}return sanitized=sanitized.replace(/\s+/g," ").trim(),{sanitized,modified:stripped.length>0,stripped}}function isGateAgentMessage(agentName){let gateAgents=["reviewer","test_engineer","critic","test-engineer"],normalized=agentName.toLowerCase().replace(/-/g,"_");return gateAgents.includes(normalized)}function createDelegationSanitizerHook(directory){return safeHook(async(_input,output)=>{let messages=output?.messages;if(!messages||!Array.isArray(messages))return;for(let message of messages){let info=message?.info;if(!info)continue;let agent=info.agent;if(!agent||!isGateAgentMessage(agent))continue;if(!message.parts||!Array.isArray(message.parts))continue;for(let part of message.parts){if(part?.type!=="text"||!part.text)continue;let originalText=part.text,result=sanitizeMessage(originalText);if(result.modified){part.text=result.sanitized;try{let event={event:"message_sanitized",agent,original_length:originalText.length,stripped_count:result.stripped.length,stripped_patterns:result.stripped,timestamp:new Date().toISOString()};appendCoreEventSync(directory,event)}catch{}}}}})}init_constants();init_schema();init_state2();function createDelegationTrackerHook(config3,guardrailsEnabled=!0,directory){return async(input,_output)=>{let now2=Date.now();if(!input.agent||input.agent===""){let session2=ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME,directory);if(session2.delegationActive=!1,swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),updateAgentEventTime(input.sessionID),guardrailsEnabled)beginInvocation(input.sessionID,ORCHESTRATOR_NAME);return}let agentName=input.agent,previousAgent=swarmState.activeAgent.get(input.sessionID);swarmState.activeAgent.set(input.sessionID,agentName);let isArchitect=stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME,session=ensureAgentSession(input.sessionID,agentName,directory);if(session.delegationActive=!isArchitect,!isArchitect)session.lastDelegationReason="normal_delegation";if(recordPhaseAgentDispatch(input.sessionID,agentName),guardrailsEnabled)beginInvocation(input.sessionID,agentName);let delegationTrackerEnabled=config3?.hooks?.delegation_tracker===!0,delegationGateEnabled=config3?.hooks?.delegation_gate!==!1;if((delegationTrackerEnabled||delegationGateEnabled)&&previousAgent&&previousAgent!==agentName){let entry={from:previousAgent,to:agentName,timestamp:now2};if(!swarmState.delegationChains.has(input.sessionID))swarmState.delegationChains.set(input.sessionID,[]);if(swarmState.delegationChains.get(input.sessionID)?.push(entry),delegationTrackerEnabled)swarmState.pendingEvents++}}}init_extractors();init_agent_model();init_injection_budget();init_state2();init_logger();init_model_limits();init_system_guidance_carrier();init_utils2();function createFinalContextAccountingStep(options){let{config:config3,resolveAgentModelFn}=options;return async(_input,output)=>{let messages=output?.messages;if(!messages||messages.length===0)return;try{let sessionID=extractSessionId2(messages);if(!sessionID)return;if(config3.context_budget?.enabled===!1)return;let agentName;for(let i=messages.length-1;i>=0;i--){let info=messages[i]?.info;if(isGuidanceCarrier(messages[i]))continue;if(info?.role==="user"&&info.agent){agentName=info.agent;break}}let configuredTargetModel=agentName&&resolveAgentModelFn?resolveAgentModelFn(agentName):void 0,targetModelInfo=configuredTargetModel?parseAgentModel(configuredTargetModel):void 0,liveModelInfo=getLiveContextModelIdentity(sessionID),{modelID,providerID}=targetModelInfo??liveModelInfo??extractModelInfo(messages),liveContextLimit=getLiveContextWindow(sessionID,{modelID,providerID}),modelLimit=resolveModelLimit(modelID,providerID,config3.context_budget?.model_limits??{},liveContextLimit,options.directory).limit;if(modelLimit<=0)return;let usage=computeContextUsage(messages),ledger=getTurnLedgerSummary(sessionID),systemSurfaceTokens=0;if(ledger){for(let producer of ledger.producers)if(producer.surface==="system")systemSurfaceTokens+=producer.emitted}let usedTokens=usage.tokensUsed+systemSurfaceTokens,warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,pctWithout=usedTokens/modelLimit*100,band=pctWithout/100>criticalThreshold?"critical":pctWithout/100>warnThreshold?"warn":"ok",warningText="";if(band!=="ok"){if(!getFinalAccountingWarningBand(sessionID,band)){let pctStr=Math.min(999,Math.round(pctWithout)).toString(),limitK=Math.round(modelLimit/1000),source=usage.source==="provider"?"provider-reported usage + estimated tail":"chars→tokens heuristic estimate";warningText=band==="critical"?`[CONTEXT PRESSURE — CRITICAL (estimated): ~${pctStr}% of the ~${limitK}K-token window (${source}). Consider compacting now or offloading detail to .swarm/context.md. Advisory only — this message removed no content.]
|
|
7214
7214
|
|
|
7215
7215
|
`:`[CONTEXT PRESSURE (estimated): ~${pctStr}% of the ~${limitK}K-token window (${source}). Consider compaction at the next phase boundary. Advisory only — this message removed no content.]
|
|
7216
7216
|
|
|
@@ -7425,7 +7425,8 @@ ${findingText}
|
|
|
7425
7425
|
Review before proceeding.`;injectSystemMessage(input.sessionID,message)}}}init_core_events();init_utils2();function createSteeringConsumedHook(directory){return safeHook(async()=>{try{let window2=readCoreEvents(directory);if(!window2.text.trim())return;let lines=window2.text.trim().split(`
|
|
7426
7426
|
`),directiveIds=new Set,consumedIds=new Set;for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directiveIds.add(parsed.directiveId);else if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}}let unconsumed=[...directiveIds].filter((id)=>!consumedIds.has(id));if(unconsumed.length>0)appendCoreEventsSync(directory,unconsumed.map((directiveId)=>({type:"steering-consumed",directiveId,timestamp:new Date().toISOString()})),{ensureSwarmDir:!1})}catch{}})}init_system_guidance_carrier();init_logger();var CACHE_CAPABLE_PROVIDER_PREFIXES=["anthropic"],STRICT_FAMILY_PATTERN=/(?:^|[^a-z0-9])(?:qwen|gemma)/i;function readModelStringField(model,key2){if(typeof model!=="object"||model===null)return"";let value=model[key2];return typeof value==="string"?value:""}function resolveSystemRenderCapability(model){let providerID=readModelStringField(model,"providerID").toLowerCase();if(CACHE_CAPABLE_PROVIDER_PREFIXES.some((prefix)=>providerID.startsWith(prefix)))return"multi-system";let modelID=readModelStringField(model,"id");if(modelID.length>0&&STRICT_FAMILY_PATTERN.test(modelID))return"strict-single-system";return"multi-system"}function applySystemRenderBoundary(model,system){let capability=resolveSystemRenderCapability(model);if(!Array.isArray(system))return{capability,entriesBefore:-1,entriesAfter:-1,collapsed:!1};let entriesBefore=system.length;if(capability!=="strict-single-system"||entriesBefore<=1)return{capability,entriesBefore,entriesAfter:entriesBefore,collapsed:!1};let nonEmpty2=system.filter((entry)=>typeof entry==="string"&&entry.length>0);if(nonEmpty2.length===0)return{capability,entriesBefore,entriesAfter:entriesBefore,collapsed:!1};let joined=nonEmpty2.join(`
|
|
7427
7427
|
|
|
7428
|
-
`);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
|
|
7428
|
+
`);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_zod();init_state2();init_utils();init_project_boundary();init_timeout();init_utils();init_timeout();var V2_REGISTRATION_TIMEOUT_MS=60000;function mapV1AgentToV2(name,config3){let info={id:name,name,mode:config3.mode==="primary"||config3.mode==="subagent"||config3.mode==="all"?config3.mode:"subagent",hidden:!1,request:{settings:{},headers:{},body:{}}};if(typeof config3.prompt==="string"&&config3.prompt.length>0)info.system=config3.prompt;if(typeof config3.description==="string"&&config3.description.length>0)info.description=config3.description;if(typeof config3.model==="string"&&config3.model.includes("/")){let separator=config3.model.indexOf("/");info.model={providerID:config3.model.slice(0,separator),id:config3.model.slice(separator+1)}}let rules=[];if(Array.isArray(config3.tools)){for(let tool3 of config3.tools)if(typeof tool3==="string"&&tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}else if(config3.tools&&typeof config3.tools==="object")for(let[tool3,enabled]of Object.entries(config3.tools)){if(enabled===!1)continue;if(tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}if(rules.length>0)info.permissions=rules;return info}function expandV1Template(template,argumentsText){return template.replaceAll("$ARGUMENTS",argumentsText).trim()}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations){if(typeof hooks2.config!=="function")return;let syntheticConfig={};await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"));let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{Object.assign(agent,mapped)})}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration);let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key2,entry]of Object.entries(commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key2,description:typeof entry.description==="string"?entry.description:void 0,execute:async(invocation)=>{let text=expandV1Template(template,invocation?.prompt?.text??""),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key2});return}await withTimeout(Promise.resolve(prompt(invocation.sessionID,{text})),V2_REGISTRATION_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key2} prompt exceeded budget`))}};editor.add(definition)}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length})}init_utils();init_timeout();var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function mapV2EventToV1(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelope.data??{},sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;let mapped=mapV2EventToV1(envelope);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function toV1MessageView(message,sessionID){let textParts=[];for(let part of message.content??[])if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID},parts:textParts}}function writeBackTextParts(message,parts){let kept=(message.content??[]).filter((part)=>!(part&&typeof part==="object"&&part.type==="text")),texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text}));message.content=[...kept,...texts]}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let views=(event.messages??[]).map((m)=>toV1MessageView(m,sessionID)),originalMessages=[...event.messages??[]];await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)});for(let i=0;i<originalMessages.length;i+=1)views[i]=toV1MessageView(originalMessages[i],sessionID)});let originalById=new Map,originalsWithoutId=[];for(let message of originalMessages){let id=typeof message.id==="string"?message.id:void 0;if(id!==void 0&&id.length>0)originalById.set(id,message);else originalsWithoutId.push(message)}let usedIds=new Set,nextIdless=0,keptParts=[];event.system=event.system??[];for(let view of views){let id=view.info.id;if(typeof id==="string"&&id.startsWith(GUIDANCE_CARRIER_ID_PREFIX)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});continue}let message;if(typeof id==="string"&&id.length>0&&originalById.has(id)&&!usedIds.has(id))message=originalById.get(id),usedIds.add(id);else if((id===void 0||id.length===0)&&nextIdless<originalsWithoutId.length)message=originalsWithoutId[nextIdless],nextIdless+=1;if(message)keptParts.push({message,parts:view.parts})}for(let{message,parts}of keptParts)writeBackTextParts(message,parts);event.messages.length=0,event.messages.push(...keptParts.map((k)=>k.message))}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_utils();init_timeout();var V2_HOOK_TIMEOUT_MS=60000;async function onV2ToolBefore(event,hooks2,directory){let handler=hooks2["tool.execute.before"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let output={args:event.input};await withTimeout(Promise.resolve(handler({tool:event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.before exceeded budget")),event.input=output.args}async function onV2ToolAfter(event,hooks2,directory){let handler=hooks2["tool.execute.after"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let output=translateV2ResultToV1Output(event);await withTimeout(Promise.resolve(handler({tool:event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.after exceeded budget")).catch((err)=>{log("v2 tool.execute.after failed (non-fatal)",{tool:event.tool,error:err instanceof Error?err.message:String(err)})})}function translateV2ResultToV1Output(event){if(event.status==="error")return{title:"error",state:"error",output:event.error&&typeof event.error.message==="string"?event.error.message:"tool error",metadata:{}};let result=event.result;return{title:"",state:"completed",output:typeof result?.content==="string"?result.content:Array.isArray(result?.content)?(result?.content).filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>p.text).join(`
|
|
7429
|
+
`):"",metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget"));registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget"));registrations.push(after)}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget"));registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget"));registrations.push(prompt)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},permissionBridge=buildPermissionBridge(ctx),registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,permissionBridge))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx){let permission=ctx.permission;if(!permission||typeof permission.reply!=="function")return;return async(input)=>{let askInput=input;log("v2 permission bridge invoked (best-effort passthrough)",{permission:typeof askInput?.permission==="string"?askInput.permission:"unknown",patternCount:Array.isArray(askInput?.patterns)?askInput.patterns.length:0}),await withTimeout(Promise.resolve(permission.reply?.(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}var V2_SETUP_TIMEOUT_MS=60000;function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2={registrations:[]},input={client:void 0,directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget"));await withTimeout(registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: agent/command registration exceeded budget")).catch((err)=>{log("v2 agent/command registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2Tools(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool registration exceeded budget")).catch((err)=>{log("v2 tool registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ContextHook(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: guidance registration exceeded budget")).catch((err)=>{log("v2 context-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ToolHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool-hook registration exceeded budget")).catch((err)=>{log("v2 tool-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2SessionHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: prompt-hook registration exceeded budget")).catch((err)=>{log("v2 prompt-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(typeof state2.pumpStop==="function")state2.pumpStop();for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;try{ensureAgentSession(sessionID,agentName,directory)}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
|
|
7429
7430
|
`).slice(0,SCREENING_PROMPT_CAP)}async function screenCandidate(candidate2,deps){let perCandidateMs=deps.llmTimeoutMs??0;if(!deps.llmDelegate||perCandidateMs<=0||!deps.sessionID)return!0;let llmDelegate=deps.llmDelegate;if(!deps.llmBudget)return!0;let remainingMs2=deps.remainingBudgetMs?.()??Number.POSITIVE_INFINITY,timeoutMs=Math.min(perCandidateMs,Math.max(0,remainingMs2));if(timeoutMs<=0)return!0;if(!reserveLlmBudget(deps.sessionID,SCREENING_TOKEN_ESTIMATE,deps.llmBudget))return!0;return!/\bREJECT\b/i.test(await withTimeoutSignal((signal2)=>llmDelegate("",buildScreeningPrompt(candidate2),signal2),timeoutMs,Error(`Knowledge admission screening timed out after ${timeoutMs}ms`)))}async function admitCandidate(directory,candidate2,deps){let candidateId2=resolveInsightCandidateId(candidate2),marker=insightAdmissionMarker(candidateId2),now2=deps.now??(()=>Date.now());if(!validateActionableFields({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks,triggers:candidate2.triggers,directive_priority:candidate2.directive_priority}).valid)return{outcome:"rejected",reason:"invalid_shape",marker};let actionability=validateActionability({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks});if(!actionability.actionable)return{outcome:"rejected",reason:actionability.reason??"unactionable",marker};if(!await screenCandidate(candidate2,deps))return{outcome:"rejected",reason:"screened_out",marker};let provenance=stampLearningProvenance({mechanism:candidate2.source?.kind==="prm_pattern"?"prm_pattern":"micro_reflection",sourceKnowledgeIds:[marker],sourceTaskIds:candidate2.source?.task_id?[candidate2.source.task_id]:[],sourceEvidenceRefs:candidate2.source_refs??[]},{sessionId:deps.sessionID,agentRole:candidate2.source?.agent,producedAt:new Date(now2()).toISOString()}),knowledgePath=(deps.resolveKnowledgePath??resolveSwarmKnowledgePath)(directory),entry=insightCandidateToEntry(candidate2,deps.projectName,deps.phaseNumber,deps.knowledgeConfig);if(unionSourceKnowledgeIds(entry,provenance.sourceKnowledgeIds),provenance.sourceEvidenceRefs.length>0){let refs=new Set([...entry.source_refs??[],...provenance.sourceEvidenceRefs]);entry.source_refs=[...refs]}let outcome="rejected",reason="no_change",entryId;if(await transactKnowledge(knowledgePath,(current)=>{if(findActiveEntryWithMarker(current,marker))return outcome="rejected",reason="already_admitted",null;let duplicate=findActiveSwarmNearDuplicate(entry.lesson,current,deps.knowledgeConfig.dedup_threshold);if(duplicate){let result=reinforceSwarmKnowledgeEntry(duplicate,{phase_number:deps.phaseNumber,confirmed_at:new Date(now2()).toISOString(),project_name:deps.projectName});return unionSourceKnowledgeIds(duplicate,[marker]),outcome="reinforced",reason=result.reason,entryId=duplicate.id,current}return current.push(entry),outcome="admitted",reason=void 0,entryId=entry.id,current}),outcome!=="rejected")deps.onKnowledgeChanged?.();return{outcome,reason,entryId,marker,provenance}}async function realtimeAdmissionAfter(directory,input,config3,resolveDeps){if(!isTaskTool(input.tool))return;if(!config3?.enabled)return;let sessionID=typeof input.sessionID==="string"&&input.sessionID.length>0?input.sessionID:void 0;if(!sessionID)return;if(getQueueDepth(sessionID)===0)return;let deps=await resolveDeps();return drainSessionQueue(directory,sessionID,config3,deps)}function emptySummary(){return{attempted:0,admitted:0,reinforced:0,rejected:0,deferred:0,failed:0,retries:0}}async function drainSessionQueue(directory,sessionID,config3,deps){let summary=emptySummary();if(!config3.enabled)return summary;let now2=deps.now??(()=>Date.now()),stats2=getQueueStats(sessionID);if(stats2.depth===0)return summary;let velocity=computeArrivalVelocity(stats2,now2()),size=computeDrainSize(stats2.depth,velocity,{minDrain:config3.min_drain,maxDrain:config3.max_drain,drainDepthFactor:config3.drain_depth_factor,drainVelocityFactor:config3.drain_velocity_factor});if(size<=0)return summary;let batch=takeDrainBatch(sessionID,size);if(batch.length===0)return summary;summary.attempted=batch.length;let startedAt=now2(),wallTimeMs=Math.max(0,Number(config3.max_drain_wall_time_ms)||0),deadline=wallTimeMs>0?startedAt+wallTimeMs:Number.POSITIVE_INFINITY,budgetExhausted=()=>now2()>=deadline,maxRetries=Math.max(0,Math.floor(Number(config3.max_retries_per_candidate)||0)),limit=pLimit(Math.max(1,Math.floor(Number(config3.max_concurrent_admissions)||1))),admissionDeps={...deps,sessionID,llmTimeoutMs:config3.max_llm_calls_per_session>0?deps.llmTimeoutMs??config3.per_candidate_llm_timeout_ms:0,llmBudget:deps.llmBudget??{maxLlmCallsPerSession:config3.max_llm_calls_per_session,maxTokensPerSession:config3.max_tokens_per_session},remainingBudgetMs:()=>deadline-now2()},deferOrAbandon=(item)=>{if(item.attempts>=MAX_CANDIDATE_DRAIN_ATTEMPTS){summary.failed++,warn(`[learning-admission] candidate abandoned after ${item.attempts} drain attempt(s) without completing`);return}requeueCandidate(sessionID,item,{maxQueueSize:config3.max_queue_size}),summary.deferred++};return await Promise.all(batch.map((item)=>limit(async()=>{if(budgetExhausted()){deferOrAbandon(item);return}for(let attempt=0;;attempt++)try{let result=await admitCandidate(directory,item.candidate,admissionDeps);if(result.outcome==="admitted")summary.admitted++;else if(result.outcome==="reinforced")summary.reinforced++;else summary.rejected++;return}catch(err){if(attempt>=maxRetries){warn(`[learning-admission] candidate failed after ${attempt+1} attempt(s): ${isAbortError(err)?"cancelled":err instanceof Error?err.message:String(err)}`),deferOrAbandon(item);return}if(summary.retries++,recordRetry(sessionID),budgetExhausted()){deferOrAbandon(item);return}}}))),summary}init_memory();init_provider_pool();init_task_model_routing();init_observability();init_otlp_exporter();init_startup_contract();init_manager();init_prm();init_trajectory_store();init_sweep();init_ephemeral_agent_dispatcher();function createReviewModelDispatcher(client,pricing){return{dispatch:(request)=>dispatchEphemeralAgent({client,directory:request.directory,parentSessionId:request.parentSessionId,agentName:request.agentName,model:request.model,system:request.system,prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:request.title,timeoutMs:request.timeoutMs&&request.timeoutMs>0?request.timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,promptByteLimit:request.promptByteLimit,responseByteLimit:request.responseByteLimit,abortSignal:request.abortSignal,pricing})}}init_finding_validator();init_runtime3();init_compaction_service();init_config_doctor();init_cost_accounting();init_injection_budget();init_model_preflight();init_version_check();init_snapshot_coordination_init();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();init_state2();init_telemetry();init_startup_contract();init_zod();init_agents2();init_schema();init_runtime3();init_state2();init_telemetry();init_ephemeral_session_teardown();init_model_dispatch_fallback();init_provider_error_classification();init_swarm_artifact_cache();import*as fs175 from"node:fs/promises";import*as path306 from"node:path";init_bun_compat();init_swarm_artifact_cache();import{rmSync as rmSync32}from"node:fs";import*as fs174 from"node:fs/promises";import*as path305 from"node:path";function leanTurboEvidenceDir(directory,phase){return path305.join(directory,".swarm","evidence",String(phase),"lean-turbo")}function validateLaneId(laneId){if(laneId.length===0)throw Error("Invalid laneId: empty string is not allowed");if(laneId.length>128)throw Error(`Invalid laneId: exceeds maximum length of 128 characters (got ${laneId.length})`);if(laneId.includes("/")||laneId.includes("\\"))throw Error(`Invalid laneId: path separators are not allowed (got "${laneId}")`);if(laneId.includes(".."))throw Error(`Invalid laneId: parent-directory references are not allowed (got "${laneId}")`);if(laneId.startsWith("/")||/^[a-zA-Z]:/i.test(laneId))throw Error(`Invalid laneId: absolute paths are not allowed (got "${laneId}")`)}function laneEvidencePath(directory,phase,laneId){validateLaneId(laneId);let expectedDir=leanTurboEvidenceDir(directory,phase),resolvedPath=path305.resolve(path305.join(expectedDir,`${laneId}.json`)),resolvedDir=path305.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path305.sep)&&resolvedPath!==resolvedDir)throw Error(`Invalid laneId: path traversal detected (got "${laneId}")`);return resolvedPath}async function atomicWriteJson(filePath,data){let content=JSON.stringify(data,null,2),dir=path305.dirname(filePath);await fs174.mkdir(dir,{recursive:!0});let tempPath=`${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await bunWrite(tempPath,content),await fs174.rename(tempPath,filePath),invalidateCachedArtifact(filePath)}catch(error93){try{rmSync32(tempPath,{force:!0})}catch{}throw error93}}function phaseEvidencePath(directory,phase){return path305.join(leanTurboEvidenceDir(directory,phase),"lean-turbo-phase.json")}async function writeLaneEvidence(directory,phase,evidence2){let targetPath=laneEvidencePath(directory,phase,evidence2.laneId);await atomicWriteJson(targetPath,evidence2)}async function writePhaseEvidence(directory,evidence2){let targetPath=phaseEvidencePath(directory,evidence2.phase);await atomicWriteJson(targetPath,evidence2)}async function readPhaseEvidence(directory,phase){let targetPath=phaseEvidencePath(directory,phase),content;try{content=await fs174.readFile(targetPath,"utf-8")}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw error93}try{return JSON.parse(content)}catch{return null}}async function listLaneEvidence(directory,phase){let evidenceDir=leanTurboEvidenceDir(directory,phase),entries2;try{entries2=await fs174.readdir(evidenceDir)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw error93}entries2.sort();let lanes=[];for(let entry of entries2){if(!entry.endsWith(".json"))continue;if(entry==="lean-turbo-phase.json")continue;let filePath=path305.join(evidenceDir,entry),content;try{content=await fs174.readFile(filePath,"utf-8")}catch{continue}try{let parsed=JSON.parse(content);lanes.push(parsed)}catch{}}return lanes}var DEFAULT_CONFIG2={criticAgent:"",timeoutMs:0};function resolveDefaultCriticAgent(generatedAgentNames,activeAgentName){return resolveAgentForActiveSwarm(generatedAgentNames,"critic",activeAgentName)}function resolveLegacyCriticModelConfig(agentName,config3){if(config3?.dispatcher||config3?.agentModelRegistry)return;let agentBaseName=stripKnownSwarmPrefix(agentName),swarmId=agentBaseName!==agentName?agentName.slice(0,agentName.length-agentBaseName.length-1):void 0;return{agentBaseName,swarmAgents:getSwarmAgents(swarmId)}}async function readReviewerEvidence(directory,phase){let evidencePath=path306.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json"),content;try{content=await fs175.readFile(evidencePath,"utf-8")}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw error93}try{return JSON.parse(content)}catch{return null}}async function compileCriticPackage(directory,phase,sessionID){let lanes=await listLaneEvidence(directory,phase),phaseEvidence=await readPhaseEvidence(directory,phase),reviewerEvidence=await readReviewerEvidence(directory,phase),filesChangedSet=new Set;for(let lane of lanes)for(let file3 of lane.files)filesChangedSet.add(file3);let completedLanes=lanes.filter((l)=>l.status==="completed").length,failedLanes=lanes.filter((l)=>l.status==="failed").length,laneSummaries=lanes.map((lane)=>({laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:lane.status,agent:lane.agent})),degradedTasks=phaseEvidence?.degradedTasks??[],pendingDegraded=degradedTasks.filter((dt)=>!lanes.some((l)=>l.taskIds.includes(dt.taskId)&&l.status==="completed")).length,safetyConcerns=[];if(!reviewerEvidence)safetyConcerns.push("Reviewer evidence is missing — critic cannot verify reviewer assessment");else if(reviewerEvidence.verdict==="REJECTED")safetyConcerns.push(`Reviewer verdict is REJECTED: ${reviewerEvidence.reason??"no reason provided"}`);else if(reviewerEvidence.verdict==="NEEDS_REVISION")safetyConcerns.push(`Reviewer verdict is NEEDS_REVISION: ${reviewerEvidence.reason??"no reason provided"}`);if(pendingDegraded>0)safetyConcerns.push(`${pendingDegraded} degraded task(s) remain unresolved`);if(failedLanes>0)safetyConcerns.push(`${failedLanes} lane(s) failed`);let pkg={phase,sessionID,reviewerVerdict:reviewerEvidence?.verdict,reviewerMissing:!reviewerEvidence,safetyConcerns,laneSummaries,filesChanged:[...filesChangedSet],testResults:{totalLanes:lanes.length,completedLanes,failedLanes},degradationSummary:{totalDegraded:degradedTasks.length,resolvedDegraded:degradedTasks.length-pendingDegraded,pendingDegraded}};if(phaseEvidence?.validationArtifacts)pkg.validationArtifacts=phaseEvidence.validationArtifacts;return pkg}function parseCriticVerdict2(responseText){let verdictMatch=responseText.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED|ESCALATE_TO_HUMAN)/);if(!verdictMatch)return null;let verdict=verdictMatch[1],lines=responseText.split(`
|
|
7430
7431
|
`),verdictIndex=lines.findIndex((l)=>l.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED|ESCALATE_TO_HUMAN)/i)),reason;if(verdictIndex>=0&&verdictIndex+1<lines.length){let reasonMatch=lines[verdictIndex+1].match(/^REASON\s*:\s*(.+)/i);if(reasonMatch)reason=reasonMatch[1].trim()}return{verdict,reason}}async function writeCriticEvidence(directory,phase,verdict,reason){let evidenceDir=path306.join(directory,".swarm","evidence",String(phase));await fs175.mkdir(evidenceDir,{recursive:!0});let evidencePath=path306.join(evidenceDir,"lean-turbo-critic.json"),content=JSON.stringify({phase,verdict,reason:reason??null,timestamp:new Date().toISOString()},null,2),tempPath=`${evidencePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await fs175.writeFile(tempPath,content,"utf-8"),await fs175.rename(tempPath,evidencePath),invalidateCachedArtifact(evidencePath)}catch(error93){try{await fs175.unlink(tempPath)}catch{}throw error93}return evidencePath}async function dispatchCriticWithReviewDispatcher(dispatcher,directory,criticPackage,agentName,timeoutMs,parentSessionId,model){let result=await dispatcher.dispatch({directory,parentSessionId,agentName,model,system:"You are a read-only phase critic for Lean Turbo execution. Evaluate phase-boundary safety, lane integrity, degraded tasks, and the reviewer verdict. Conclude with exactly one verdict marker and a REASON line.",prompt:`Review this boundary evidence and conclude with VERDICT: APPROVED, NEEDS_REVISION, REJECTED, or ESCALATE_TO_HUMAN plus a REASON line.
|
|
7431
7432
|
|
|
@@ -7827,7 +7828,7 @@ ${content}
|
|
|
7827
7828
|
`),diff2+=`
|
|
7828
7829
|
`,diff2}function validateOldContent(lines,contextMatch,oldContent){if(!oldContent)return{valid:!0};let expectedLines=splitDiffLines(oldContent),removalStartIdx=contextMatch.startLineIndex+contextMatch.matchedBefore.length,actualLines=lines.slice(removalStartIdx,removalStartIdx+expectedLines.length);if(!arraysEqual2(actualLines,expectedLines))return{valid:!1,expected:expectedLines.join(`
|
|
7829
7830
|
`),actual:actualLines.join(`
|
|
7830
|
-
`)};return{valid:!0}}var suggestPatch=createSwarmTool({description:'Suggest a structured patch for specified files without modifying them. Returns context-based patch proposals with anchors for reviewer use. When format="unified", also produces a unified diff string consumable by apply_patch. '+"This is a read-only tool — it does not modify any files.",args:{targetFiles:exports_external.array(exports_external.string()).describe("Array of file paths to patch").min(1),changes:exports_external.array(exports_external.object({file:exports_external.string().describe("Path to the file this change applies to"),contextBefore:exports_external.array(exports_external.string()).optional().describe("Lines before the change region (anchor)"),contextAfter:exports_external.array(exports_external.string()).optional().describe("Lines after the change region (anchor)"),oldContent:exports_external.string().optional().describe("Current content to be replaced"),newContent:exports_external.string().describe("New content to replace with")})).describe("Array of change descriptions with context anchors").min(1),format:exports_external.enum(["json","unified"]).optional().default("json").describe('Output format: "json" (default, existing structured output) or "unified" (unified diff string for apply_patch)')},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"Could not parse suggest-patch arguments"},null,2);let obj=args2,targetFiles=obj.targetFiles??[],changes=obj.changes??[],format=obj.format??"json";if(!targetFiles||targetFiles.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"targetFiles cannot be empty"},null,2);if(!changes||changes.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"changes cannot be empty"},null,2);if(!fs221.existsSync(directory))return JSON.stringify({success:!1,error:!0,type:"file-not-found",message:"Workspace directory does not exist"},null,2);let patches=[],filesModifiedSet=new Set,errors5=[],unifiedDiffEntries=[],targetFileSet=new Set(targetFiles),skippedBinaryFiles=new Set;if(format==="unified"){for(let change of changes)if(isBinaryFile4(change.file))errors5.push({success:!1,error:!0,type:"parse-error",message:`Binary files are not supported in unified diff mode: ${change.file}`,details:{location:change.file}}),skippedBinaryFiles.add(change.file)}for(let changeIndex=0;changeIndex<changes.length;changeIndex++){let change=changes[changeIndex];if(format==="unified"&&skippedBinaryFiles.has(change.file))continue;if(!targetFileSet.has(change.file)){errors5.push({success:!1,error:!0,type:"parse-error",message:`File "${change.file}" is not in targetFiles`,details:{location:change.file}});continue}if(!validateFilePath2(change.file,directory)){errors5.push({success:!1,error:!0,type:"parse-error",message:`Invalid file path: ${change.file}`,details:{location:change.file}});continue}let fullPath=path364.resolve(directory,change.file);if(!fs221.existsSync(fullPath)){errors5.push({success:!1,error:!0,type:"file-not-found",message:`File not found: ${change.file}`,details:{location:change.file}});continue}let content;try{content=fs221.readFileSync(fullPath,"utf-8")}catch(err2){errors5.push({success:!1,error:!0,type:"unknown",message:`Could not read file: ${err2 instanceof Error?err2.message:String(err2)}`,details:{location:`${change.file}:0`}});continue}let contextMatch=findContextMatch(content,change.contextBefore,change.contextAfter,change.oldContent);if(!contextMatch){errors5.push({success:!1,error:!0,type:"context-mismatch",message:`Could not find context anchor in ${change.file}. Provide contextBefore/contextAfter lines to locate the change region.`,details:{location:change.file}});continue}let lines=splitDiffLines(content),oldContentValidation=validateOldContent(lines,contextMatch,change.oldContent);if(!oldContentValidation.valid){errors5.push({success:!1,error:!0,type:"context-mismatch",message:"Content at the specified location does not match oldContent",details:{expected:oldContentValidation.expected,actual:oldContentValidation.actual,location:`${change.file}:${contextMatch.startLineIndex+1}-${contextMatch.endLineIndex+1}`}});continue}let originalContext=[...contextMatch.matchedBefore,...contextMatch.matchedAfter.length>0?["..."]:[],...contextMatch.matchedAfter];if(patches.push({file:change.file,originalContext,newContent:change.newContent,hunkIndex:changeIndex}),filesModifiedSet.add(change.file),format==="unified")unifiedDiffEntries.push({file:change.file,contextMatch,oldContent:change.oldContent,newContent:change.newContent})}if(patches.length>0){let baseResult={success:!0,patches,filesModified:Array.from(filesModifiedSet),...errors5.length>0&&{errors:errors5}};if(format==="unified"){let fileGroups=new Map;for(let entry of unifiedDiffEntries){let group=fileGroups.get(entry.file)??[];group.push(entry),fileGroups.set(entry.file,group)}let unifiedParts=[];for(let[file3,entries2]of fileGroups){entries2.sort((a,b)=>a.contextMatch.startLineIndex-b.contextMatch.startLineIndex);let entryFullPath=path364.resolve(directory,file3),entryContent;try{entryContent=fs221.readFileSync(entryFullPath,"utf-8")}catch{continue}unifiedParts.push(generateFileHeader(file3));for(let entry of entries2)unifiedParts.push(generateHunk(entryContent,entry.contextMatch,entry.oldContent,entry.newContent))}let unifiedPatch=unifiedParts.join("");return JSON.stringify({...baseResult,unifiedPatch},null,2)}return JSON.stringify(baseResult,null,2)}if(errors5.length===1)return JSON.stringify(errors5[0],null,2);return JSON.stringify({success:!1,error:!0,type:"context-mismatch",message:`All ${errors5.length} patch suggestions failed`,errors:errors5},null,2)}});init_zod();init_loader();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();function getContextAgent2(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}var ArgsSchema5=exports_external.object({phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),parent_agent:exports_external.string().min(1).optional(),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()}),summarize_work=createSwarmTool({description:`Emit a short structured summary of the work you just completed (key decisions, assumptions, risks, constraints observed/violated). Call this once at task completion. Keep the summary under ${MAX_AGENT_SUMMARY_WORDS} words and each list to ${MAX_LIST_ITEMS} items — longer content is truncated, not rejected. These `+"summaries roll up per phase and are reviewed by the architecture supervisor to catch cross-task contradictions, drift, and repeated failure loops. Advisory only.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number this work belongs to."),summary:exports_external.string().min(1).describe(`One-paragraph summary of what you did (<= ${MAX_AGENT_SUMMARY_WORDS} words).`),task_id:exports_external.string().min(1).optional().describe('Task ID this summary covers (e.g. "1.2").'),parent_agent:exports_external.string().min(1).optional().describe("The agent that delegated this task, if any."),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()},execute:async(rawArgs,directory,ctx)=>{let parsed=ArgsSchema5.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,sessionId=ctx?.sessionID??"unknown-session",agent=getContextAgent2(ctx)??"unknown-agent",maxWords=MAX_AGENT_SUMMARY_WORDS;try{maxWords=loadPluginConfig(workingDir).architectural_supervision?.max_agent_summary_words??maxWords}catch{}let summary=normalizeAgentWorkSummary({phase:args2.phase,task_id:args2.task_id,session_id:sessionId,agent,parent_agent:args2.parent_agent,summary:args2.summary,key_decisions:args2.key_decisions,constraints_observed:args2.constraints_observed,constraints_violated:args2.constraints_violated,assumptions:args2.assumptions,risks:args2.risks,files_touched:args2.files_touched,evidence_refs:args2.evidence_refs},maxWords),storedTaskId=await writeAgentSummary(workingDir,summary);return JSON.stringify({success:!0,stored_task_id:storedTaskId,phase:summary.phase,agent:summary.agent,truncated:summary.truncated??!1},null,2)}});init_zod();init_command_dispatch();init_tool_policy();init_create_tool();function createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Run supported /swarm commands through the canonical opencode-swarm command registry. Return the tool output verbatim to the user.",args:{command:exports_external.enum(SWARM_COMMAND_TOOL_COMMANDS).describe("The /swarm subcommand to run, without the /swarm prefix."),args:exports_external.array(exports_external.string()).default([]).describe("Additional command arguments as separate tokens.")},async execute(rawArgs,directory,ctx){let args2=rawArgs;return(await executeSwarmCommand({directory,agents,sessionID:ctx?.sessionID??"",tokens:[args2.command,...args2.args??[]],policy:classifySwarmCommandToolUse,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,activeAgentName:getActiveAgentName?.(ctx?.sessionID??"")})).text}})}var swarm_command=createSwarmCommandTool({});init_zod();init_config();init_memory();init_state2();init_create_tool();import{createHash as createHash115}from"node:crypto";var OutcomeArgsSchema=exports_external.object({memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional(),question:exports_external.string().trim().min(1).max(2000).optional(),outcome:exports_external.enum(["useful","dead_end","corrected"]),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional(),correction:exports_external.string().trim().min(1).max(4000).optional()}).strict().superRefine((value,context)=>{if(Boolean(value.memory_id)===Boolean(value.question))context.addIssue({code:"custom",message:"exactly one of memory_id or question is required"});if(value.outcome==="corrected"&&!value.correction)context.addIssue({code:"custom",message:"corrected outcomes require correction text"})}),swarm_memory_outcome=createSwarmTool({description:"Record whether recalled memory or a graph answer was useful, a dead end, or corrected; when reflection is enabled, synchronously refresh deterministic reflection artifacts.",args:{memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional().describe("Existing memory id to update"),question:exports_external.string().trim().min(1).max(2000).optional().describe("Question for a lightweight result memory when no id is known"),outcome:exports_external.enum(["useful","dead_end","corrected"]).describe("Observed result"),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional().describe("Repository-relative file and optional symbol anchors"),correction:exports_external.string().trim().min(1).max(4000).optional().describe("Required corrected claim text for corrected outcomes")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals300.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=OutcomeArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=typeof ctx?.agent==="string"?ctx.agent:void 0,taskId=ctx?.sessionID?_internals300.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals300.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId:taskId},{config:config3.memory}),eventId=ctx?.sessionID&&ctx.messageID?`tool-${createHash115("sha256").update(JSON.stringify({sessionID:ctx.sessionID,messageID:ctx.messageID,args:parsed.data})).digest("hex").slice(0,32)}`:void 0;try{let result=await _internals300.recordOutcomeWithReflection(directory,config3.memory,gateway,{memoryId:parsed.data.memory_id,question:parsed.data.question,outcome:parsed.data.outcome,anchors:parsed.data.anchors,correction:parsed.data.correction,eventId}),reflectionUpdated=result.reflectionUpdated,reflectionAttempted=result.reflectionAttempted,partial3=result.reflectionEnabled===!0&&reflectionAttempted&&!reflectionUpdated,reflectionError="error"in result?result.error:void 0;return JSON.stringify({success:!0,status:partial3?"partial":"complete",partial:partial3,outcome_recorded:result.outcomeRecorded,event_id:result.eventId,memory_id:result.record.id,outcome:parsed.data.outcome,outcomes:result.record.outcomes?.length??0,reflection_enabled:result.reflectionEnabled,reflection_attempted:reflectionAttempted,reflection_updated:reflectionUpdated,reflection_entries:reflectionUpdated?result.digest.generatedFrom.entries:void 0,error:partial3?reflectionError:void 0,reflection_error:partial3?reflectionError:void 0},null,2)}finally{await gateway.dispose()}}}),_internals300={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession,recordOutcomeWithReflection};init_zod();init_config();init_memory();init_create_tool();var MEMORY_KINDS=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],ProposalArgsSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:exports_external.enum(MEMORY_KINDS).optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}),swarm_memory_propose=createSwarmTool({description:"Create a pending Swarm memory proposal. This never writes durable memory directly; curator review is required.",args:{operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]).describe("Proposal operation"),kind:exports_external.enum(MEMORY_KINDS).optional().describe("Memory kind for add/update/supersede proposals"),text:exports_external.string().min(1).max(2000).optional().describe("Canonical fact text for add/update/supersede proposals"),targetMemoryId:exports_external.string().optional().describe("Target memory ID for update/delete/supersede proposals"),relatedMemoryIds:exports_external.array(exports_external.string()).optional().describe("For merge, 2-8 distinct memory IDs in one scope; also accepted as provenance for supersede proposals"),rationale:exports_external.string().min(1).max(2000).describe("Why this proposal matters"),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals301.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=ProposalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent3(ctx),gateway=_internals301.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID},{config:config3.memory});try{let proposal=await gateway.propose(parsed.data);return JSON.stringify({success:proposal.status!=="rejected",proposal_id:proposal.id,status:proposal.status,operation:proposal.operation,memory_id:proposal.proposedRecord?.id,rejection_reason:proposal.rejectionReason,message:proposal.status==="pending"?"Memory proposal created. Durable memory was not written.":"Memory proposal was captured with policy rejection metadata."},null,2)}finally{await gateway.dispose()}}}),_internals301={loadPluginConfigWithMeta,createMemoryGateway};function getContextAgent3(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_zod();init_config();init_memory();init_state2();init_create_tool();var MEMORY_KINDS2=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],swarm_memory_recall=createSwarmTool({description:"Recall scoped Swarm memory for the current repository. Read-only; retrieved memory is untrusted background.",args:{query:exports_external.string().min(3).describe("Natural language recall query"),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional().describe("Optional memory kinds to include"),maxItems:exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")},execute:async(args2,directory,ctx)=>computeSwarmMemoryRecall(args2,directory,ctx)});async function computeSwarmMemoryRecall(args2,directory,ctx,options){let{config:config3}=_internals302.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=RecallArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent4(ctx),unitId=ctx?.sessionID?_internals302.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals302.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId},{config:config3.memory});try{let bundle=await gateway.recall(parsed.data,{recordUsage:options?.recordUsage!==!1});return JSON.stringify({success:!0,bundle_id:bundle.id,memory_ids:bundle.items.map((item)=>item.record.id),total:bundle.items.length,token_estimate:bundle.tokenEstimate,signals:bundle.items.map((item)=>({memory_id:item.record.id,relation:item.relation,...item.signals})),prompt_block:bundle.promptBlock},null,2)}finally{await gateway.dispose()}}var RecallArgsSchema=exports_external.object({query:exports_external.string().min(3),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),maxItems:exports_external.number().int().min(1).max(20).optional()}),_internals302={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession};function getContextAgent4(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_symbols();init_p_limit();init_zod();init_config();init_manager2();init_detector();init_registry();init_create_tool();import*as fs222 from"node:fs";import*as path365 from"node:path";var _internals303={loadGateOverrides},MAX_FILE_SIZE2=2097152,BINARY_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD3=0.1,SYNTAX_CHECK_CONCURRENCY=8;function isBinaryContent2(content){let sample=content.slice(0,BINARY_CHECK_BYTES),nullCount=0;for(let i=0;i<sample.length;i++)if(sample.charCodeAt(i)===0)nullCount++;return nullCount/sample.length>BINARY_NULL_THRESHOLD3}function extractSyntaxErrors(parser,content){let tree=parser.parse(content);if(!tree)return[];let errors5=[],stack=[tree.rootNode];while(stack.length>0){let node=stack.pop();if(node.type==="ERROR")errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:"Syntax error"});else if(node.isMissing)errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:`Missing '${node.type}'`});let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}if(errors5.length===0&&tree.rootNode.hasError)errors5.push({line:1,column:0,message:"Syntax error detected (tree has errors)"});return tree.delete(),errors5}async function syntaxCheck(input,directory,gates){return computeSyntaxCheck(input,directory,gates,{persistEvidence:!0})}async function computeSyntaxCheck(input,directory,gates,options){if(gates?.syntax_check?.enabled===!1)return{verdict:"pass",files:[],summary:"syntax_check disabled by configuration"};let{changed_files,mode="changed",languages}=input,filesToCheck=changed_files;if(mode==="changed")filesToCheck=filesToCheck.filter((f)=>f.additions>0);if(languages?.length){let lowerLangs=languages.map((l)=>l.toLowerCase());filesToCheck=filesToCheck.filter((file3)=>{let ext=path365.extname(file3.path).toLowerCase(),langDef=getLanguageForExtension(ext),langId=getProfileForFile(file3.path)?.id||langDef?.id;return langId?lowerLangs.includes(langId.toLowerCase()):!1})}let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));async function checkOneFile(fileInfo){let{path:filePath}=fileInfo,fullPath=path365.isAbsolute(filePath)?filePath:path365.join(directory,filePath),result={path:filePath,language:"",ok:!1,errors:[]};try{let profile=getProfileForFile(filePath),grammarId=profile?.treeSitter?.grammarId,parser=null;if(grammarId)try{parser=await loadGrammar2(grammarId)}catch{parser=null}if(!parser)parser=await getParserForFile(filePath);if(!parser)return result.skipped_reason="unsupported_language",{result,counted:!1,failed:!1,skipped:!0};try{if(fs222.statSync(fullPath).size>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0}}catch{}let content;try{content=fs222.readFileSync(fullPath,"utf8")}catch{return result.skipped_reason="file_read_error",{result,counted:!1,failed:!1,skipped:!0}}if(content.length>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0};if(isBinaryContent2(content))return result.skipped_reason="binary_file",{result,counted:!1,failed:!1,skipped:!0};let ext=path365.extname(filePath).toLowerCase(),langDef=getLanguageForExtension(ext);result.language=profile?.id||langDef?.id||"unknown";let errors5=extractSyntaxErrors(parser,content);if(errors5.length>0)return result.ok=!1,result.errors=errors5,{result,counted:!0,failed:!0,skipped:!1};return result.ok=!0,{result,counted:!0,failed:!1,skipped:!1}}catch(error93){return result.skipped_reason=error93 instanceof Error?error93.message:"unknown_error",{result,counted:!0,failed:!1,skipped:!0}}}let limit=pLimit(SYNTAX_CHECK_CONCURRENCY),outcomes=await Promise.all(filesToCheck.map((fileInfo)=>limit(()=>checkOneFile(fileInfo)))),results=[],filesChecked=0,filesFailed=0,skippedCount=0;for(let outcome of outcomes){if(results.push(outcome.result),outcome.counted)filesChecked++;if(outcome.failed)filesFailed++;if(outcome.skipped)skippedCount++}let emptyCheckReasons=[];if(changed_files.length===0)emptyCheckReasons.push("no files were supplied in changed_files");else{if(mode==="changed")emptyCheckReasons.push("mode='changed' dropped files with additions === 0 (deletion-only or pure-rename entries); pass mode='all' to include them");if(languages?.length)emptyCheckReasons.push(`the languages filter [${languages.join(", ")}] matched no supplied file`);if(emptyCheckReasons.length===0)emptyCheckReasons.push("every supplied file was skipped as unsupported, unreadable, too large, or binary")}let verdict=filesFailed>0?"fail":filesChecked===0?"skip":"pass",summary=filesFailed>0?`Syntax errors found in ${filesFailed} of ${filesChecked} files`:filesChecked===0?`No files were checked — ${emptyCheckReasons.join("; ")}. This is NOT a passing syntax check.`:`All ${filesChecked} files passed syntax check`;if(options?.persistEvidence===!0)await _internals61.saveEvidence(directory,"syntax_check",{task_id:"syntax_check",type:"syntax",timestamp:new Date().toISOString(),agent:"syntax_check",verdict,summary,files_checked:filesChecked,files_failed:filesFailed,skipped_count:skippedCount,files:results});return{verdict,files:results,summary}}var syntax_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Check syntax of source files using tree-sitter parsers. Supports JS/TS, Python, Go, Rust, Java, C/C++, C#, PHP, Ruby. Returns JSON with syntax errors found per file.",args:{changed_files:exports_external.array(exports_external.object({path:exports_external.string(),additions:exports_external.number()})).describe("Files to check (from diff gate)"),mode:exports_external.enum(["changed","all"]).optional().describe("Check mode over the supplied changed_files. 'changed' (default) checks only entries with additions > 0, so deletion-only and pure-rename entries are excluded; 'all' checks every supplied entry. Neither mode enumerates the repository — this tool only ever inspects the files you pass in changed_files. If the filters leave nothing to check the verdict is 'skip', never 'pass'."),languages:exports_external.array(exports_external.string()).optional().describe("Optional: restrict to specific languages")},async execute(args2,directory){let gates=_internals303.loadGateOverrides(directory),result=await syntaxCheck(args2,directory,gates);return JSON.stringify(result)}});init_zod();init_analyzer();init_create_tool();init_resolve_working_directory();var test_impact=createSwarmTool({description:"Analyze which test files are impacted by changes to the given source files. Returns TestImpactResult with impactedTests, untestedFiles, and the full impact map.",args:{changedFiles:exports_external.array(exports_external.string()).describe("Array of source file paths to analyze for test impact"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.changedFiles||!Array.isArray(typedArgs.changedFiles)||typedArgs.changedFiles.length===0)return JSON.stringify({error:"changedFiles must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({error:resolved.message,success:!1},null,2);let cwd=resolved.directory,result=await analyzeImpact(typedArgs.changedFiles,cwd);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`test_impact failed: ${e.message}`:"test_impact failed: unknown error",success:!1},null,2)}}});init_test_runner();init_zod();init_config();init_gate_evidence();init_utils();init_logger();init_task_id();init_create_tool();init_path_security();import*as fs223 from"node:fs";import*as path366 from"node:path";var MAX_TEXT_LENGTH=200,MAX_FILE_SIZE_BYTES10=1048576,MAX_RECORDED_DETAILS=50,SUPPORTED_EXTENSIONS3=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".ps1",".go",".java",".c",".cpp",".h",".cs",".rb",".php",".blade.php",".swift",".kt"]),SKIP_DIRECTORIES5=new Set(["node_modules","dist","build",".git",".swarm","coverage"]),PRIORITY_MAP={FIXME:"high",HACK:"high",XXX:"high",TODO:"medium",WARN:"medium",NOTE:"low"},SHELL_METACHAR_REGEX3=/[;&|%$`\\]/;function validateTagsInput(tags){if(!tags||tags.length===0)return"tags cannot be empty";if(containsControlChars(tags))return"tags contains control characters";if(SHELL_METACHAR_REGEX3.test(tags))return"tags contains shell metacharacters (;|&$`\\)";if(!/^[a-zA-Z0-9,\s]+$/.test(tags))return"tags contains invalid characters (only alphanumeric, commas, spaces allowed)";return null}function validatePathsInput(paths,cwd){if(!paths||paths.length===0)return{error:null,resolvedPath:cwd};if(containsControlChars(paths))return{error:"paths contains control characters",resolvedPath:null};if(containsPathTraversal(paths))return{error:"paths contains path traversal",resolvedPath:null};try{let resolvedPath=path366.resolve(paths),normalizedCwd=path366.resolve(cwd);if(!path366.resolve(resolvedPath).startsWith(normalizedCwd))return{error:"paths must be within the current working directory",resolvedPath:null};return{error:null,resolvedPath}}catch(e){return{error:e instanceof Error?e.message:"invalid paths",resolvedPath:null}}}function isSupportedExtension(filePath){let ext=path366.extname(filePath).toLowerCase();return SUPPORTED_EXTENSIONS3.has(ext)}function findSourceFiles3(dir,files=[]){let entries2;try{entries2=fs223.readdirSync(dir)}catch{return files}entries2.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries2){if(SKIP_DIRECTORIES5.has(entry))continue;let fullPath=path366.join(dir,entry),stat25;try{stat25=fs223.statSync(fullPath)}catch{continue}if(stat25.isDirectory())findSourceFiles3(fullPath,files);else if(stat25.isFile()){if(isSupportedExtension(fullPath))files.push(fullPath)}}return files}function parseTodoComments(content,filePath,tagsSet){let entries2=[],lines=content.split(`
|
|
7831
|
+
`)};return{valid:!0}}var suggestPatch=createSwarmTool({description:'Suggest a structured patch for specified files without modifying them. Returns context-based patch proposals with anchors for reviewer use. When format="unified", also produces a unified diff string consumable by apply_patch. '+"This is a read-only tool — it does not modify any files.",args:{targetFiles:exports_external.array(exports_external.string()).describe("Array of file paths to patch").min(1),changes:exports_external.array(exports_external.object({file:exports_external.string().describe("Path to the file this change applies to"),contextBefore:exports_external.array(exports_external.string()).optional().describe("Lines before the change region (anchor)"),contextAfter:exports_external.array(exports_external.string()).optional().describe("Lines after the change region (anchor)"),oldContent:exports_external.string().optional().describe("Current content to be replaced"),newContent:exports_external.string().describe("New content to replace with")})).describe("Array of change descriptions with context anchors").min(1),format:exports_external.enum(["json","unified"]).optional().default("json").describe('Output format: "json" (default, existing structured output) or "unified" (unified diff string for apply_patch)')},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"Could not parse suggest-patch arguments"},null,2);let obj=args2,targetFiles=obj.targetFiles??[],changes=obj.changes??[],format=obj.format??"json";if(!targetFiles||targetFiles.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"targetFiles cannot be empty"},null,2);if(!changes||changes.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"changes cannot be empty"},null,2);if(!fs221.existsSync(directory))return JSON.stringify({success:!1,error:!0,type:"file-not-found",message:"Workspace directory does not exist"},null,2);let patches=[],filesModifiedSet=new Set,errors5=[],unifiedDiffEntries=[],targetFileSet=new Set(targetFiles),skippedBinaryFiles=new Set;if(format==="unified"){for(let change of changes)if(isBinaryFile4(change.file))errors5.push({success:!1,error:!0,type:"parse-error",message:`Binary files are not supported in unified diff mode: ${change.file}`,details:{location:change.file}}),skippedBinaryFiles.add(change.file)}for(let changeIndex=0;changeIndex<changes.length;changeIndex++){let change=changes[changeIndex];if(format==="unified"&&skippedBinaryFiles.has(change.file))continue;if(!targetFileSet.has(change.file)){errors5.push({success:!1,error:!0,type:"parse-error",message:`File "${change.file}" is not in targetFiles`,details:{location:change.file}});continue}if(!validateFilePath2(change.file,directory)){errors5.push({success:!1,error:!0,type:"parse-error",message:`Invalid file path: ${change.file}`,details:{location:change.file}});continue}let fullPath=path364.resolve(directory,change.file);if(!fs221.existsSync(fullPath)){errors5.push({success:!1,error:!0,type:"file-not-found",message:`File not found: ${change.file}`,details:{location:change.file}});continue}let content;try{content=fs221.readFileSync(fullPath,"utf-8")}catch(err2){errors5.push({success:!1,error:!0,type:"unknown",message:`Could not read file: ${err2 instanceof Error?err2.message:String(err2)}`,details:{location:`${change.file}:0`}});continue}let contextMatch=findContextMatch(content,change.contextBefore,change.contextAfter,change.oldContent);if(!contextMatch){errors5.push({success:!1,error:!0,type:"context-mismatch",message:`Could not find context anchor in ${change.file}. Provide contextBefore/contextAfter lines to locate the change region.`,details:{location:change.file}});continue}let lines=splitDiffLines(content),oldContentValidation=validateOldContent(lines,contextMatch,change.oldContent);if(!oldContentValidation.valid){errors5.push({success:!1,error:!0,type:"context-mismatch",message:"Content at the specified location does not match oldContent",details:{expected:oldContentValidation.expected,actual:oldContentValidation.actual,location:`${change.file}:${contextMatch.startLineIndex+1}-${contextMatch.endLineIndex+1}`}});continue}let originalContext=[...contextMatch.matchedBefore,...contextMatch.matchedAfter.length>0?["..."]:[],...contextMatch.matchedAfter];if(patches.push({file:change.file,originalContext,newContent:change.newContent,hunkIndex:changeIndex}),filesModifiedSet.add(change.file),format==="unified")unifiedDiffEntries.push({file:change.file,contextMatch,oldContent:change.oldContent,newContent:change.newContent})}if(patches.length>0){let baseResult={success:!0,patches,filesModified:Array.from(filesModifiedSet),...errors5.length>0&&{errors:errors5}};if(format==="unified"){let fileGroups=new Map;for(let entry of unifiedDiffEntries){let group=fileGroups.get(entry.file)??[];group.push(entry),fileGroups.set(entry.file,group)}let unifiedParts=[];for(let[file3,entries2]of fileGroups){entries2.sort((a,b)=>a.contextMatch.startLineIndex-b.contextMatch.startLineIndex);let entryFullPath=path364.resolve(directory,file3),entryContent;try{entryContent=fs221.readFileSync(entryFullPath,"utf-8")}catch{continue}unifiedParts.push(generateFileHeader(file3));for(let entry of entries2)unifiedParts.push(generateHunk(entryContent,entry.contextMatch,entry.oldContent,entry.newContent))}let unifiedPatch=unifiedParts.join("");return JSON.stringify({...baseResult,unifiedPatch},null,2)}return JSON.stringify(baseResult,null,2)}if(errors5.length===1)return JSON.stringify(errors5[0],null,2);return JSON.stringify({success:!1,error:!0,type:"context-mismatch",message:`All ${errors5.length} patch suggestions failed`,errors:errors5},null,2)}});init_zod();init_loader();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();function getContextAgent2(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}var ArgsSchema5=exports_external.object({phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),parent_agent:exports_external.string().min(1).optional(),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()}),summarize_work=createSwarmTool({description:`Emit a short structured summary of the work you just completed (key decisions, assumptions, risks, constraints observed/violated). Call this once at task completion. Keep the summary under ${MAX_AGENT_SUMMARY_WORDS} words and each list to ${MAX_LIST_ITEMS} items — longer content is truncated, not rejected. These `+"summaries roll up per phase and are reviewed by the architecture supervisor to catch cross-task contradictions, drift, and repeated failure loops. Advisory only.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number this work belongs to."),summary:exports_external.string().min(1).describe(`One-paragraph summary of what you did (<= ${MAX_AGENT_SUMMARY_WORDS} words).`),task_id:exports_external.string().min(1).optional().describe('Task ID this summary covers (e.g. "1.2").'),parent_agent:exports_external.string().min(1).optional().describe("The agent that delegated this task, if any."),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()},execute:async(rawArgs,directory,ctx)=>{let parsed=ArgsSchema5.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,sessionId=ctx?.sessionID??"unknown-session",agent=getContextAgent2(ctx)??"unknown-agent",maxWords=MAX_AGENT_SUMMARY_WORDS;try{maxWords=loadPluginConfig(workingDir).architectural_supervision?.max_agent_summary_words??maxWords}catch{}let summary=normalizeAgentWorkSummary({phase:args2.phase,task_id:args2.task_id,session_id:sessionId,agent,parent_agent:args2.parent_agent,summary:args2.summary,key_decisions:args2.key_decisions,constraints_observed:args2.constraints_observed,constraints_violated:args2.constraints_violated,assumptions:args2.assumptions,risks:args2.risks,files_touched:args2.files_touched,evidence_refs:args2.evidence_refs},maxWords),storedTaskId=await writeAgentSummary(workingDir,summary);return JSON.stringify({success:!0,stored_task_id:storedTaskId,phase:summary.phase,agent:summary.agent,truncated:summary.truncated??!1},null,2)}});init_zod();init_command_dispatch();init_tool_policy();init_create_tool();function createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Run supported /swarm commands through the canonical opencode-swarm command registry. Return the tool output verbatim to the user.",args:{command:exports_external.enum(SWARM_COMMAND_TOOL_COMMANDS).describe("The /swarm subcommand to run, without the /swarm prefix."),args:exports_external.array(exports_external.string()).default([]).describe("Additional command arguments as separate tokens.")},async execute(rawArgs,directory,ctx){let args2=rawArgs;return(await executeSwarmCommand({directory,agents,sessionID:ctx?.sessionID??"",tokens:[args2.command,...args2.args??[]],policy:classifySwarmCommandToolUse,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,activeAgentName:getActiveAgentName?.(ctx?.sessionID??"")})).text}})}var swarm_command=createSwarmCommandTool({});init_zod();init_config();init_memory();init_state2();init_create_tool();import{createHash as createHash115}from"node:crypto";var OutcomeArgsSchema=exports_external.object({memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional(),question:exports_external.string().trim().min(1).max(2000).optional(),outcome:exports_external.enum(["useful","dead_end","corrected"]),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional(),correction:exports_external.string().trim().min(1).max(4000).optional()}).strict().superRefine((value,context)=>{if(Boolean(value.memory_id)===Boolean(value.question))context.addIssue({code:"custom",message:"exactly one of memory_id or question is required"});if(value.outcome==="corrected"&&!value.correction)context.addIssue({code:"custom",message:"corrected outcomes require correction text"})}),swarm_memory_outcome=createSwarmTool({description:"Record whether recalled memory or a graph answer was useful, a dead end, or corrected; when reflection is enabled, synchronously refresh deterministic reflection artifacts.",args:{memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional().describe("Existing memory id to update"),question:exports_external.string().trim().min(1).max(2000).optional().describe("Question for a lightweight result memory when no id is known"),outcome:exports_external.enum(["useful","dead_end","corrected"]).describe("Observed result"),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional().describe("Repository-relative file and optional symbol anchors"),correction:exports_external.string().trim().min(1).max(4000).optional().describe("Required corrected claim text for corrected outcomes")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals300.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=OutcomeArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=typeof ctx?.agent==="string"?ctx.agent:void 0,taskId=ctx?.sessionID?_internals300.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals300.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId:taskId},{config:config3.memory}),eventId=ctx?.sessionID&&ctx.messageID?`tool-${createHash115("sha256").update(JSON.stringify({sessionID:ctx.sessionID,messageID:ctx.messageID,args:parsed.data})).digest("hex").slice(0,32)}`:void 0;try{let result=await _internals300.recordOutcomeWithReflection(directory,config3.memory,gateway,{memoryId:parsed.data.memory_id,question:parsed.data.question,outcome:parsed.data.outcome,anchors:parsed.data.anchors,correction:parsed.data.correction,eventId}),reflectionUpdated=result.reflectionUpdated,reflectionAttempted=result.reflectionAttempted,partial3=result.reflectionEnabled===!0&&reflectionAttempted&&!reflectionUpdated,reflectionError="error"in result?result.error:void 0;return JSON.stringify({success:!0,status:partial3?"partial":"complete",partial:partial3,outcome_recorded:result.outcomeRecorded,event_id:result.eventId,memory_id:result.record.id,outcome:parsed.data.outcome,outcomes:result.record.outcomes?.length??0,reflection_enabled:result.reflectionEnabled,reflection_attempted:reflectionAttempted,reflection_updated:reflectionUpdated,reflection_entries:reflectionUpdated?result.digest.generatedFrom.entries:void 0,error:partial3?reflectionError:void 0,reflection_error:partial3?reflectionError:void 0},null,2)}finally{await gateway.dispose()}}}),_internals300={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession,recordOutcomeWithReflection};init_zod();init_config();init_memory();init_create_tool();var MEMORY_KINDS=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],ProposalArgsSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:exports_external.enum(MEMORY_KINDS).optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}),swarm_memory_propose=createSwarmTool({description:"Create a pending Swarm memory proposal. This never writes durable memory directly; curator review is required.",args:{operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]).describe("Proposal operation"),kind:exports_external.enum(MEMORY_KINDS).optional().describe("Memory kind for add/update/supersede proposals"),text:exports_external.string().min(1).max(2000).optional().describe("Canonical fact text for add/update/supersede proposals"),targetMemoryId:exports_external.string().optional().describe("Target memory ID for update/delete/supersede proposals"),relatedMemoryIds:exports_external.array(exports_external.string()).optional().describe("For merge, 2-8 distinct memory IDs in one scope; also accepted as provenance for supersede proposals"),rationale:exports_external.string().min(1).max(2000).describe("Why this proposal matters"),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals301.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=ProposalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent3(ctx),gateway=_internals301.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID},{config:config3.memory});try{let proposal=await gateway.propose(parsed.data);return JSON.stringify({success:proposal.status!=="rejected",proposal_id:proposal.id,status:proposal.status,operation:proposal.operation,memory_id:proposal.proposedRecord?.id,rejection_reason:proposal.rejectionReason,message:proposal.status==="pending"?"Memory proposal created. Durable memory was not written.":"Memory proposal was captured with policy rejection metadata."},null,2)}finally{await gateway.dispose()}}}),_internals301={loadPluginConfigWithMeta,createMemoryGateway};function getContextAgent3(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_zod();init_config();init_memory();init_state2();init_create_tool();var MEMORY_KINDS2=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],swarm_memory_recall=createSwarmTool({description:"Recall scoped Swarm memory for the current repository. Read-only; retrieved memory is untrusted background.",args:{query:exports_external.string().min(3).describe("Natural language recall query"),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional().describe("Optional memory kinds to include"),maxItems:exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")},execute:async(args2,directory,ctx)=>computeSwarmMemoryRecall(args2,directory,ctx)});async function computeSwarmMemoryRecall(args2,directory,ctx,options){let{config:config3}=_internals302.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=RecallArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent4(ctx),unitId=ctx?.sessionID?_internals302.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals302.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId},{config:config3.memory});try{let bundle=await gateway.recall(parsed.data,{recordUsage:options?.recordUsage!==!1});return JSON.stringify({success:!0,bundle_id:bundle.id,memory_ids:bundle.items.map((item)=>item.record.id),total:bundle.items.length,token_estimate:bundle.tokenEstimate,signals:bundle.items.map((item)=>({memory_id:item.record.id,relation:item.relation,...item.signals})),prompt_block:bundle.promptBlock},null,2)}finally{await gateway.dispose()}}var RecallArgsSchema=exports_external.object({query:exports_external.string().min(3),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),maxItems:exports_external.number().int().min(1).max(20).optional()}),_internals302={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession};function getContextAgent4(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_symbols();init_p_limit();init_zod();init_config();init_manager2();init_detector();init_registry();init_create_tool();import*as fs222 from"node:fs";import*as path365 from"node:path";var _internals303={loadGateOverrides},MAX_FILE_SIZE2=2097152,BINARY_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD3=0.1,SYNTAX_CHECK_CONCURRENCY=8;function resolveGrammarIdForFile(filePath){let profileGrammarId=getProfileForFile(filePath)?.treeSitter?.grammarId,registryId=getLanguageForExtension(path365.extname(filePath).toLowerCase())?.id;if(profileGrammarId&®istryId&®istryId!==profileGrammarId)return registryId;return profileGrammarId}function isBinaryContent2(content){let sample=content.slice(0,BINARY_CHECK_BYTES),nullCount=0;for(let i=0;i<sample.length;i++)if(sample.charCodeAt(i)===0)nullCount++;return nullCount/sample.length>BINARY_NULL_THRESHOLD3}function extractSyntaxErrors(parser,content){let tree=parser.parse(content);if(!tree)return[];let errors5=[],stack=[tree.rootNode];while(stack.length>0){let node=stack.pop();if(node.type==="ERROR")errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:"Syntax error"});else if(node.isMissing)errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:`Missing '${node.type}'`});let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}if(errors5.length===0&&tree.rootNode.hasError)errors5.push({line:1,column:0,message:"Syntax error detected (tree has errors)"});return tree.delete(),errors5}async function syntaxCheck(input,directory,gates){return computeSyntaxCheck(input,directory,gates,{persistEvidence:!0})}async function computeSyntaxCheck(input,directory,gates,options){if(gates?.syntax_check?.enabled===!1)return{verdict:"pass",files:[],summary:"syntax_check disabled by configuration"};let{changed_files,mode="changed",languages}=input,filesToCheck=changed_files;if(mode==="changed")filesToCheck=filesToCheck.filter((f)=>f.additions>0);if(languages?.length){let lowerLangs=languages.map((l)=>l.toLowerCase());filesToCheck=filesToCheck.filter((file3)=>{let ext=path365.extname(file3.path).toLowerCase(),langDef=getLanguageForExtension(ext),langId=getProfileForFile(file3.path)?.id||langDef?.id;return langId?lowerLangs.includes(langId.toLowerCase()):!1})}let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));async function checkOneFile(fileInfo){let{path:filePath}=fileInfo,fullPath=path365.isAbsolute(filePath)?filePath:path365.join(directory,filePath),result={path:filePath,language:"",ok:!1,errors:[]};try{let profile=getProfileForFile(filePath),grammarId=resolveGrammarIdForFile(filePath),parser=null;if(grammarId)try{parser=await loadGrammar2(grammarId)}catch{parser=null}if(!parser)parser=await getParserForFile(filePath);if(!parser)return result.skipped_reason="unsupported_language",{result,counted:!1,failed:!1,skipped:!0};try{if(fs222.statSync(fullPath).size>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0}}catch{}let content;try{content=fs222.readFileSync(fullPath,"utf8")}catch{return result.skipped_reason="file_read_error",{result,counted:!1,failed:!1,skipped:!0}}if(content.length>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0};if(isBinaryContent2(content))return result.skipped_reason="binary_file",{result,counted:!1,failed:!1,skipped:!0};let ext=path365.extname(filePath).toLowerCase(),langDef=getLanguageForExtension(ext);result.language=profile?.id||langDef?.id||"unknown";let errors5=extractSyntaxErrors(parser,content);if(errors5.length>0)return result.ok=!1,result.errors=errors5,{result,counted:!0,failed:!0,skipped:!1};return result.ok=!0,{result,counted:!0,failed:!1,skipped:!1}}catch(error93){return result.skipped_reason=error93 instanceof Error?error93.message:"unknown_error",{result,counted:!0,failed:!1,skipped:!0}}}let limit=pLimit(SYNTAX_CHECK_CONCURRENCY),outcomes=await Promise.all(filesToCheck.map((fileInfo)=>limit(()=>checkOneFile(fileInfo)))),results=[],filesChecked=0,filesFailed=0,skippedCount=0;for(let outcome of outcomes){if(results.push(outcome.result),outcome.counted)filesChecked++;if(outcome.failed)filesFailed++;if(outcome.skipped)skippedCount++}let emptyCheckReasons=[];if(changed_files.length===0)emptyCheckReasons.push("no files were supplied in changed_files");else{if(mode==="changed")emptyCheckReasons.push("mode='changed' dropped files with additions === 0 (deletion-only or pure-rename entries); pass mode='all' to include them");if(languages?.length)emptyCheckReasons.push(`the languages filter [${languages.join(", ")}] matched no supplied file`);if(emptyCheckReasons.length===0)emptyCheckReasons.push("every supplied file was skipped as unsupported, unreadable, too large, or binary")}let verdict=filesFailed>0?"fail":filesChecked===0?"skip":"pass",summary=filesFailed>0?`Syntax errors found in ${filesFailed} of ${filesChecked} files`:filesChecked===0?`No files were checked — ${emptyCheckReasons.join("; ")}. This is NOT a passing syntax check.`:`All ${filesChecked} files passed syntax check`;if(options?.persistEvidence===!0)await _internals61.saveEvidence(directory,"syntax_check",{task_id:"syntax_check",type:"syntax",timestamp:new Date().toISOString(),agent:"syntax_check",verdict,summary,files_checked:filesChecked,files_failed:filesFailed,skipped_count:skippedCount,files:results});return{verdict,files:results,summary}}var syntax_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Check syntax of source files using tree-sitter parsers. Supports JS/TS, Python, Go, Rust, Java, C/C++, C#, PHP, Ruby. Returns JSON with syntax errors found per file.",args:{changed_files:exports_external.array(exports_external.object({path:exports_external.string(),additions:exports_external.number()})).describe("Files to check (from diff gate)"),mode:exports_external.enum(["changed","all"]).optional().describe("Check mode over the supplied changed_files. 'changed' (default) checks only entries with additions > 0, so deletion-only and pure-rename entries are excluded; 'all' checks every supplied entry. Neither mode enumerates the repository — this tool only ever inspects the files you pass in changed_files. If the filters leave nothing to check the verdict is 'skip', never 'pass'."),languages:exports_external.array(exports_external.string()).optional().describe("Optional: restrict to specific languages")},async execute(args2,directory){let gates=_internals303.loadGateOverrides(directory),result=await syntaxCheck(args2,directory,gates);return JSON.stringify(result)}});init_zod();init_analyzer();init_create_tool();init_resolve_working_directory();var test_impact=createSwarmTool({description:"Analyze which test files are impacted by changes to the given source files. Returns TestImpactResult with impactedTests, untestedFiles, and the full impact map.",args:{changedFiles:exports_external.array(exports_external.string()).describe("Array of source file paths to analyze for test impact"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.changedFiles||!Array.isArray(typedArgs.changedFiles)||typedArgs.changedFiles.length===0)return JSON.stringify({error:"changedFiles must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({error:resolved.message,success:!1},null,2);let cwd=resolved.directory,result=await analyzeImpact(typedArgs.changedFiles,cwd);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`test_impact failed: ${e.message}`:"test_impact failed: unknown error",success:!1},null,2)}}});init_test_runner();init_zod();init_config();init_gate_evidence();init_utils();init_logger();init_task_id();init_create_tool();init_path_security();import*as fs223 from"node:fs";import*as path366 from"node:path";var MAX_TEXT_LENGTH=200,MAX_FILE_SIZE_BYTES10=1048576,MAX_RECORDED_DETAILS=50,SUPPORTED_EXTENSIONS3=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".ps1",".go",".java",".c",".cpp",".h",".cs",".rb",".php",".blade.php",".swift",".kt"]),SKIP_DIRECTORIES5=new Set(["node_modules","dist","build",".git",".swarm","coverage"]),PRIORITY_MAP={FIXME:"high",HACK:"high",XXX:"high",TODO:"medium",WARN:"medium",NOTE:"low"},SHELL_METACHAR_REGEX3=/[;&|%$`\\]/;function validateTagsInput(tags){if(!tags||tags.length===0)return"tags cannot be empty";if(containsControlChars(tags))return"tags contains control characters";if(SHELL_METACHAR_REGEX3.test(tags))return"tags contains shell metacharacters (;|&$`\\)";if(!/^[a-zA-Z0-9,\s]+$/.test(tags))return"tags contains invalid characters (only alphanumeric, commas, spaces allowed)";return null}function validatePathsInput(paths,cwd){if(!paths||paths.length===0)return{error:null,resolvedPath:cwd};if(containsControlChars(paths))return{error:"paths contains control characters",resolvedPath:null};if(containsPathTraversal(paths))return{error:"paths contains path traversal",resolvedPath:null};try{let resolvedPath=path366.resolve(paths),normalizedCwd=path366.resolve(cwd);if(!path366.resolve(resolvedPath).startsWith(normalizedCwd))return{error:"paths must be within the current working directory",resolvedPath:null};return{error:null,resolvedPath}}catch(e){return{error:e instanceof Error?e.message:"invalid paths",resolvedPath:null}}}function isSupportedExtension(filePath){let ext=path366.extname(filePath).toLowerCase();return SUPPORTED_EXTENSIONS3.has(ext)}function findSourceFiles3(dir,files=[]){let entries2;try{entries2=fs223.readdirSync(dir)}catch{return files}entries2.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries2){if(SKIP_DIRECTORIES5.has(entry))continue;let fullPath=path366.join(dir,entry),stat25;try{stat25=fs223.statSync(fullPath)}catch{continue}if(stat25.isDirectory())findSourceFiles3(fullPath,files);else if(stat25.isFile()){if(isSupportedExtension(fullPath))files.push(fullPath)}}return files}function parseTodoComments(content,filePath,tagsSet){let entries2=[],lines=content.split(`
|
|
7831
7832
|
`),tagPattern=Array.from(tagsSet).map(escapeRegex2).join("|"),regex=new RegExp(`\\b(${tagPattern})\\b[:\\s]?`,"i");for(let i=0;i<lines.length;i++){let line=lines[i],match=regex.exec(line);if(match){let tag=match[1].toUpperCase(),priority=PRIORITY_MAP[tag]||"medium",text=line.substring(match.index+match[0].length).trim();if(text=text.replace(/^[/*\-\s]+/,""),text.length>MAX_TEXT_LENGTH)text=`${text.substring(0,MAX_TEXT_LENGTH-3)}...`;entries2.push({file:filePath,line:i+1,tag,text,priority})}}return entries2}var todo_extract=createSwarmTool({description:"Scan the codebase for TODO/FIXME/HACK/XXX/WARN/NOTE comments. Returns JSON with count by priority and sorted entries. Useful for identifying pending tasks and code issues. When task_id is provided and the todo_gate config is enabled (default), the high-priority scan is also recorded as todo_scan gate evidence for that task, consumed by check_gate_status and the phase-complete todo_gate gate.",args:{paths:exports_external.string().optional().describe("Directory or file to scan (default: entire project/cwd)"),tags:exports_external.string().optional().describe("Comma-separated tags to search for (default: TODO,FIXME,HACK,XXX,WARN,NOTE)"),task_id:exports_external.string().regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "2.3.1")').optional().describe("Optional task ID (N.M format). When provided and todo_gate is enabled, the high-priority (FIXME/HACK/XXX) count is recorded as todo_scan gate evidence in .swarm/evidence/{task_id}.json")},async execute(args2,directory){let paths,tags,taskId;try{if(args2&&typeof args2==="object"){let obj=args2;paths=typeof obj.paths==="string"?obj.paths:void 0,tags=typeof obj.tags==="string"?obj.tags:void 0,taskId=typeof obj.task_id==="string"?obj.task_id:void 0}}catch{}let cwd=directory,tagsInput=tags||"TODO,FIXME,HACK,XXX,WARN,NOTE",tagsValidationError=validateTagsInput(tagsInput);if(tagsValidationError){let errorResult={error:`invalid tags: ${tagsValidationError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let tagsList=tagsInput.split(",").map((t)=>t.trim().toUpperCase()).filter((t)=>t.length>0),tagsSet=new Set(tagsList);if(tagsSet.size===0)return JSON.stringify({error:"invalid tags: no valid tags provided",total:0,byPriority:{high:0,medium:0,low:0},entries:[]},null,2);let pathsInput=paths||cwd,{error:pathsError,resolvedPath}=validatePathsInput(pathsInput,cwd);if(pathsError){let errorResult={error:`invalid paths: ${pathsError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let scanPath=resolvedPath;if(!fs223.existsSync(scanPath)){let errorResult={error:`path not found: ${pathsInput}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let filesToScan=[];if(fs223.statSync(scanPath).isFile())if(isSupportedExtension(scanPath))filesToScan.push(scanPath);else{let errorResult={error:`unsupported file extension: ${path366.extname(scanPath)}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}else findSourceFiles3(scanPath,filesToScan);let allEntries=[];for(let filePath of filesToScan)try{if(fs223.statSync(filePath).size>MAX_FILE_SIZE_BYTES10)continue;let content=fs223.readFileSync(filePath,"utf-8"),entries2=parseTodoComments(content,filePath,tagsSet);allEntries.push(...entries2)}catch{}allEntries.sort((a,b)=>{let priorityOrder={high:0,medium:1,low:2},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.file.toLowerCase().localeCompare(b.file.toLowerCase())});let byPriority={high:allEntries.filter((e)=>e.priority==="high").length,medium:allEntries.filter((e)=>e.priority==="medium").length,low:allEntries.filter((e)=>e.priority==="low").length},result={total:allEntries.length,byPriority,entries:allEntries},coversHighPriorityClass=["FIXME","HACK","XXX"].every((tag)=>tagsSet.has(tag));if(taskId&&isStrictTaskId(taskId))if(!coversHighPriorityClass)log("todo_extract: todo_scan evidence recording skipped — custom tags omit the FIXME/HACK/XXX high-priority class");else try{let{config:config3}=loadPluginConfigWithMeta(directory);if(config3.todo_gate?.enabled!==!1){let detailLines=allEntries.filter((entry)=>entry.priority==="high").slice(0,MAX_RECORDED_DETAILS).map((entry)=>{return`${path366.relative(directory,entry.file)}:${entry.line} ${entry.tag} ${entry.text}`});await recordTodoScanEvidence(directory,taskId,{priority:"high",count:byPriority.high,details:detailLines,recorded_at:new Date().toISOString()})}}catch(recordError){log("todo_extract: todo_scan evidence recording skipped",recordError)}return JSON.stringify(result,null,2)}});init_zod();init_loader();init_schema();init_qa_gate_profile();init_task_gate_requirements();init_gate_evidence();import*as fs227 from"node:fs";import*as path370 from"node:path";init_bun_compat();init_git_executable();import*as fs225 from"node:fs";import*as path368 from"node:path";init_warning_buffer();init_bun_compat();init_git_executable();import*as fs224 from"node:fs";import*as path367 from"node:path";var _internals304={bunSpawn,resolveGitExecutableAsync};var _swarmGitExcludedChecked=!1;function fileCoversIgnorePatterns(content,patterns){for(let rawLine of content.split(`
|
|
7832
7833
|
`)){let line=rawLine.trim();if(line.startsWith("#")||line.length===0)continue;if(patterns.includes(line))return!0}return!1}function fileCoversSwarm(content){return fileCoversIgnorePatterns(content,[".swarm",".swarm/"])}function fileCoversSwarmWorktrees(content){return fileCoversIgnorePatterns(content,[".swarm-worktrees",".swarm-worktrees/"])}var ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS=3000,ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS=1500,GIT_SPAWN_OPTIONS={timeout:ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS,stdin:"ignore",stdout:"pipe",stderr:"pipe"};async function ensureSwarmGitExcluded(directory,options={}){if(_swarmGitExcludedChecked)return;_swarmGitExcludedChecked=!0;let{quiet:_quiet=!1}=options;try{let gitExecutable=await _internals304.resolveGitExecutableAsync(),[[gitRootExitCode,gitRootOutput],[excludePathExitCode,excludePathRaw],checkIgnoreExitCode,checkIgnoreWorktreesExitCode]=await Promise.all([(async()=>{let proc=_internals304.bunSpawn([gitExecutable,"-C",directory,"rev-parse","--show-toplevel"],GIT_SPAWN_OPTIONS);try{return await Promise.all([proc.exited,proc.stdout.text()])}finally{try{proc.kill()}catch{}}})(),(async()=>{let proc=_internals304.bunSpawn([gitExecutable,"-C",directory,"rev-parse","--git-path","info/exclude"],GIT_SPAWN_OPTIONS);try{return await Promise.all([proc.exited,proc.stdout.text()])}finally{try{proc.kill()}catch{}}})(),(async()=>{let proc=_internals304.bunSpawn([gitExecutable,"-C",directory,"check-ignore","-q",".swarm/.gitkeep"],GIT_SPAWN_OPTIONS);try{return await proc.exited}finally{try{proc.kill()}catch{}}})(),(async()=>{let proc=_internals304.bunSpawn([gitExecutable,"-C",directory,"check-ignore","-q",".swarm-worktrees/.gitkeep"],GIT_SPAWN_OPTIONS);try{return await proc.exited}finally{try{proc.kill()}catch{}}})()]);if(gitRootExitCode!==0)return;if(!gitRootOutput.trim())return;if(excludePathExitCode!==0)return;let excludeRelPath=excludePathRaw.trim();if(!excludeRelPath)return;let excludePath=path367.isAbsolute(excludeRelPath)?excludeRelPath:path367.join(directory,excludeRelPath),swarmIgnored=checkIgnoreExitCode===0,worktreesIgnored=checkIgnoreWorktreesExitCode===0;if(!swarmIgnored||!worktreesIgnored)try{fs224.mkdirSync(path367.dirname(excludePath),{recursive:!0});let existing="";try{existing=fs224.readFileSync(excludePath,"utf8")}catch{}let needSwarm=!swarmIgnored&&!fileCoversSwarm(existing),needWorktrees=!worktreesIgnored&&!fileCoversSwarmWorktrees(existing),added=[];if(needSwarm)added.push(".swarm/");if(needWorktrees)added.push(".swarm-worktrees/");if(added.length>0)fs224.appendFileSync(excludePath,`
|
|
7833
7834
|
# opencode-swarm local runtime state (incl. worktree lanes, #2527)
|
|
@@ -7872,6 +7873,6 @@ ${footerLines.join(`
|
|
|
7872
7873
|
`);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(`
|
|
7873
7874
|
`)}${output.length>0&&trailingNewline?`
|
|
7874
7875
|
`:""}`}function gitBlobObjectId(content,algorithm){let header=Buffer.from(`blob ${content.byteLength}\x00`,"utf8");return createHash118(algorithm).update(header).update(content).digest("hex")}function matchesDeclaredObjectId(actual,declared){return/^0+$/.test(declared)?!1:actual.startsWith(declared)}function decodeTextFile(relativePath2,buffer){if(buffer.includes(0))throw Error(`binary file rejected: ${relativePath2}`);return TEXT_DECODER.decode(buffer)}function parseBaseTreeEntry(output){let trimmed=output.split("\x00").find(Boolean)?.trim();if(!trimmed)return null;let match=/^(\d{6}) blob ([a-f0-9]{40,64})\t(.+)$/.exec(trimmed);if(!match)return null;return{mode:match[1],objectId:match[2],relativePath:normalizeRelativePath2(match[3])}}function fail3(code,reason){return{ok:!1,code,reason}}function snapshotPathIdentity(absolutePath2){if(!existsSync202(absolutePath2))return{exists:!1};let stat25=_internals319.lstatSync(absolutePath2),isSymbolicLink=typeof stat25.isSymbolicLink==="function"?stat25.isSymbolicLink():!1,isFile=typeof stat25.isFile==="function"?stat25.isFile():!1;return{exists:!0,isSymbolicLink,isFile,nlink:stat25.nlink,size:stat25.size,mtimeMs:stat25.mtimeMs,ctimeMs:stat25.ctimeMs,dev:stat25.dev,ino:stat25.ino,mode:stat25.mode}}function samePathIdentity(left,right){if(left.exists!==right.exists)return!1;if(!left.exists)return!0;return left.isSymbolicLink===right.isSymbolicLink&&left.isFile===right.isFile&&left.nlink===right.nlink&&left.size===right.size&&left.mtimeMs===right.mtimeMs&&left.ctimeMs===right.ctimeMs&&left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode}async function validateSourceCandidate(args2){if(assertProjectRoot(args2.directory),args2.config.source_allowlist.length===0)return fail3("ALLOWLIST_EMPTY","harness source allowlist is empty");if(!SHA_RE.test(args2.baseSha))return fail3("INVALID_BASE_SHA","baseSha must be a 40-64 hex digest");if(Buffer.byteLength(args2.patch,"utf8")>args2.config.max_patch_bytes)return fail3("PATCH_TOO_LARGE",`patch exceeds max_patch_bytes (${args2.config.max_patch_bytes})`);let base=await _internals319.runGitCommand(args2.directory,["rev-parse","HEAD"]);if(!base.ok)return fail3("GIT_FAILED",`git rev-parse failed: ${base.stderr||base.stdout}`);let currentBase=base.stdout.trim().toLowerCase();if(currentBase!==args2.baseSha.toLowerCase())return fail3("STALE_BASE",`source candidate base ${args2.baseSha} does not match current HEAD ${currentBase}`);let parsed=parsePatch(args2.patch);if(!parsed)return fail3("UNSUPPORTED_PATCH","patch grammar is not an admitted two-way unified diff");if(parsed.files.length>args2.config.max_files)return fail3("FILE_COUNT_EXCEEDED",`patch touches ${parsed.files.length} files, exceeding max_files ${args2.config.max_files}`);let approvedPaths=[],files=[],admittedPathSnapshots=new Map,totalBytes=0,totalChangedLines=0;for(let filePatch of parsed.files){let relativePath2=normalizeRelativePath2(filePatch.relativePath),oldRelativePath=filePatch.oldRelativePath?normalizeRelativePath2(filePatch.oldRelativePath):null;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let rejection=validateTargetWithinRoot(admittedPath,args2.directory);if(rejection)return fail3("PATH_REJECTED",`${admittedPath}: ${rejection}`);if(!isAllowlisted(admittedPath,args2.config.source_allowlist))return fail3("PATH_NOT_ALLOWLISTED",`${admittedPath} is outside the harness source allowlist`);if(isProtectedPath4(admittedPath,args2.config.extra_protected_paths))return fail3("PROTECTED_PATH",`${admittedPath} is protected from harness source candidates`)}let sourcePath=oldRelativePath??relativePath2;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let absolutePath2=path381.resolve(args2.directory,admittedPath),identity=snapshotPathIdentity(absolutePath2);if(admittedPathSnapshots.set(admittedPath,identity),!identity.exists)continue;if(identity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} is a symlink or junction`);if(identity.isFile&&(identity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} is a hardlinked file and is not trusted for harness source candidates`)}let tracked=await _internals319.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",sourcePath]);if(!tracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${sourcePath}`);let trackedEntry=parseBaseTreeEntry(tracked.stdout);if(!trackedEntry&&filePatch.operation!=="add")return fail3("UNTRACKED_PATH",`${sourcePath} is not tracked`);if(trackedEntry&&filePatch.operation==="add")return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`);if(filePatch.oldObjectId){if(filePatch.operation==="add"){if(!/^0+$/.test(filePatch.oldObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} add has a non-zero old object id`)}else if(!trackedEntry||!matchesDeclaredObjectId(trackedEntry.objectId,filePatch.oldObjectId))return fail3("STALE_BASE",`${sourcePath} object id does not match the declared patch base`)}if(filePatch.operation!=="add"&&(!trackedEntry||trackedEntry.relativePath!==sourcePath))return fail3("UNTRACKED_PATH",`${sourcePath} is not an admitted tracked file`);if(relativePath2!==sourcePath){let targetTracked=await _internals319.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",relativePath2]);if(!targetTracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${relativePath2}`);if(parseBaseTreeEntry(targetTracked.stdout))return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`)}let trackedMode=trackedEntry?.mode??filePatch.newMode??"100644";if(!["100644","100755"].includes(trackedMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} uses unsupported tracked mode ${trackedMode}`);let beforeBuffer=Buffer.alloc(0);if(trackedEntry){let baseBlob=await _internals319.runGitBinaryCommand(args2.directory,["show","--no-textconv",`${args2.baseSha}:${sourcePath}`],args2.config.max_file_bytes+1);if(!baseBlob.ok)return fail3("GIT_FAILED",`git show failed for ${sourcePath}: ${baseBlob.stderr}`);beforeBuffer=baseBlob.stdout}let beforeText;try{beforeText=decodeTextFile(relativePath2,beforeBuffer)}catch(error93){return fail3("BINARY_FILE",error93 instanceof Error?error93.message:String(error93))}let patchedText=filePatch.hunks.length===0?beforeText:applyFilePatch(beforeText,filePatch);if(patchedText===null)return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} did not apply cleanly`);let afterText=filePatch.operation==="delete"?"":patchedText;if(filePatch.newObjectId)if(filePatch.operation==="delete"){if(!/^0+$/.test(filePatch.newObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} delete has a non-zero new object id`)}else{let objectAlgorithm=args2.baseSha.length===64?"sha256":"sha1",actualObjectId=gitBlobObjectId(Buffer.from(afterText,"utf8"),objectAlgorithm);if(!matchesDeclaredObjectId(actualObjectId,filePatch.newObjectId))return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} object id does not match reconstructed output`)}if(filePatch.newMode&&!["100644","100755"].includes(filePatch.newMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} requests unsupported mode ${filePatch.newMode}`);if(filePatch.oldMode&&trackedEntry&&filePatch.oldMode!==trackedMode)return fail3("UNSUPPORTED_TRACKED_MODE",`${sourcePath} mode does not match the tracked base`);if(afterText.includes("\x00"))return fail3("BINARY_FILE",`${relativePath2} patch produces binary output`);let bytesBefore=Buffer.byteLength(beforeText,"utf8"),bytesAfter=Buffer.byteLength(afterText,"utf8");if(Math.max(bytesBefore,bytesAfter)>args2.config.max_file_bytes)return fail3("FILE_TOO_LARGE",`${relativePath2} exceeds max_file_bytes ${args2.config.max_file_bytes}`);if(totalBytes+=bytesAfter,totalBytes>args2.config.max_total_bytes)return fail3("TOTAL_TOO_LARGE",`patched output exceeds max_total_bytes ${args2.config.max_total_bytes}`);let addedLines=0,removedLines=0;for(let line of filePatch.hunks.flatMap((hunk)=>hunk.lines)){if(line.startsWith("+")&&!line.startsWith("+++"))addedLines++;if(line.startsWith("-")&&!line.startsWith("---"))removedLines++}let changedLines=addedLines+removedLines;if(totalChangedLines+=changedLines,totalChangedLines>args2.config.max_changed_lines)return fail3("LINE_COUNT_EXCEEDED",`patch exceeds max_changed_lines ${args2.config.max_changed_lines}`);approvedPaths.push(relativePath2),files.push({relativePath:relativePath2,...oldRelativePath&&oldRelativePath!==relativePath2?{oldRelativePath}:{},operation:filePatch.operation,trackedMode,...filePatch.newMode?{afterMode:filePatch.newMode}:{},beforeSha256:sha2569(beforeText),afterSha256:sha2569(afterText),bytesBefore,bytesAfter,addedLines,removedLines,changedLines})}for(let[admittedPath,initialIdentity]of admittedPathSnapshots){let absolutePath2=path381.resolve(args2.directory,admittedPath),finalIdentity=snapshotPathIdentity(absolutePath2);if(!samePathIdentity(initialIdentity,finalIdentity))return fail3("PATH_CHANGED_DURING_VALIDATION",`${admittedPath} changed on disk while the harness source candidate was being validated`);if(finalIdentity.exists&&finalIdentity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} became a symlink or junction during validation`);if(finalIdentity.exists&&finalIdentity.isFile&&(finalIdentity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} became a hardlinked file during validation`)}let manifestBase={v:RECORD_VERSION2,candidateId:args2.candidateId,baseSha:args2.baseSha.toLowerCase(),origin:args2.origin,patchSha256:sha2569(args2.patch),promptArtifactHashes:[],approvedPaths:[...approvedPaths].sort(),files},riskTier=deriveHarnessCandidateRiskTier(manifestBase),manifestHash2=computeHarnessCandidateManifestHash(manifestBase);return{ok:!0,candidate:{...parseHarnessCandidateManifest({...manifestBase,riskTier,manifestHash:manifestHash2}),patch:args2.patch}}}async function runGitCommand(directory,args2){return new Promise((resolve153)=>{let stdout="",stderr="",stdoutBytes=0,stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve153(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stdoutBytes);stdout+=slice.toString("utf8"),stdoutBytes+=slice.byteLength}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout,stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout,stderr})})})}async function runGitBinaryCommand(directory,args2,maxOutputBytes=MAX_GIT_OUTPUT_BYTES3){return new Promise((resolve153)=>{let stdoutChunks=[],stdoutBytes=0,stderr="",stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve153(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=maxOutputBytes)return;let slice=chunk.subarray(0,maxOutputBytes-stdoutBytes);if(stdoutChunks.push(slice),stdoutBytes+=slice.byteLength,slice.byteLength<chunk.byteLength||stdoutBytes>=maxOutputBytes)finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:`git output exceeds bound ${maxOutputBytes}`})}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout:Buffer.concat(stdoutChunks),stderr})})})}var _internals319={runGitCommand,runGitBinaryCommand,lstatSync:lstatSync44};init_store3();function projectStaticBlueprint2(agents){let runtimeDefinitions=Object.entries(agents).sort(([leftKey,left],[rightKey,right])=>left.name.localeCompare(right.name)||leftKey.localeCompare(rightKey)).map(([,agent])=>{let config3=agent.config,tools=config3.tools?Object.fromEntries(Object.entries(config3.tools).sort(([a],[b])=>a.localeCompare(b))):config3.tools;return{name:agent.name,description:agent.description,config:{...config3,tools,mode:config3.mode==="primary"?"primary":"subagent",temperature:config3.temperature??0.1,prompt:config3.prompt??`Static runtime definition for ${agent.name}`}}}),registeredToolIds=[...new Set(runtimeDefinitions.flatMap((definition)=>Object.keys(definition.config.tools??{})))].sort();return createAgentFactory({runtimeDefinitions,registeredToolIds}).projectBlueprint({blueprintId:"static-runtime-shadow"})}function diffHarnessBlueprints(left,right){let changes={};for(let key2 of[...new Set([...Object.keys(left),...Object.keys(right)])].sort())if(canonicalJson6(left[key2])!==canonicalJson6(right[key2]))changes[key2]={before:left[key2],after:right[key2]};return{changes,summary:{changeCount:Object.keys(changes).length,changedKeys:Object.keys(changes).sort()}}}var harnessMutationV1=Object.freeze(Object.assign(function(){return harnessMutationV1},{validateBlueprint:parseHarnessBlueprint,projectStaticBlueprint:projectStaticBlueprint2,applyPatchSet:applyBlueprintPatch,validateSourceCandidate,saveCandidate:recordHarnessCandidate,saveVersion:saveHarnessVersion,activate:activateHarnessCandidate,rollback:rollbackHarnessVersion,current:loadHarnessCurrent,history:listHarnessHistory,diff:diffHarnessBlueprints,auditLedger:auditHarnessLedger,recoverCorruptTail:recoverHarnessCorruptTail}));markStartupImportComplete();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500,_architectCompactionPending=new Map,MAX_TRACKED_ARCHITECT_COMPACTIONS=500,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS=250;function capSessionMap(map3,max,justInserted){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0||oldest===justInserted)break;map3.delete(oldest)}}function resolveSoundingBoardCallerCategory(args2){if(!args2||typeof args2!=="object"||Array.isArray(args2))return{supplied:!1};let record3=args2;if(Object.hasOwn(record3,"category"))return{supplied:!0,value:record3.category};return{supplied:!1}}function applySoundingBoardResponsePolicy(rawResponse,args2){let callerCategory=resolveSoundingBoardCallerCategory(args2),parsed=parseSoundingBoardResponse(rawResponse,callerCategory.supplied?{category:callerCategory.value}:void 0);if(!parsed)return null;let guarded=applyAlwaysSurfacePolicy(parsed);if(guarded.protocolError&&guarded.verdict==="UNNECESSARY")return{...guarded,verdict:"APPROVED",warning:guarded.warning??"Invalid or missing Category metadata; verdict was surfaced as APPROVED."};return guarded}var instanceExitCleanups=new Map,instanceExitCleanupCounter=0,processExitCleanupRegistered=!1,processSignalCleanupHandlers=[],signalExitCleanupInFlight=!1;function runInstanceExitCleanups(){for(let cleanup of instanceExitCleanups.values())try{cleanup()}catch{}}function makeSignalExitCleanupHandler(signal2){let handler=()=>{if(signalExitCleanupInFlight)return;signalExitCleanupInFlight=!0;try{runInstanceExitCleanups()}catch{}finally{process.off(signal2,handler),process.kill(process.pid,signal2)}};return handler}function registerProcessExitCleanupDispatcher(){if(processExitCleanupRegistered)return;processExitCleanupRegistered=!0,process.on("exit",runInstanceExitCleanups),processSignalCleanupHandlers=[{signal:"SIGINT",handler:makeSignalExitCleanupHandler("SIGINT")},{signal:"SIGTERM",handler:makeSignalExitCleanupHandler("SIGTERM")}];for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.on(signal2,handler)}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear(),pendingCostCorrectionByChildSession.clear(),scheduledCostCorrectionRecoveryBySession.clear(),latestAssistantUsageBySession.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path383.resolve(path383.dirname(fileURLToPath8(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS=1e4,TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS=1e4,RETENTION_SWEEP_INIT_TIMEOUT_MS=5000,LOAD_PLUGIN_CONFIG_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents,options={}){let surface=options.surface??"system";return async(input,output)=>{let{sessionID,agent,expectedGeneration}=input,activeAgentName=sessionID?surface==="messages"?agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName:swarmState.activeAgent.get(sessionID)??agent??swarmState.agentSessions.get(sessionID)?.agentName:agent;if(surface==="system"&&isSessionBoundArchitect(sessionID,activeAgentName))return;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG)))return;let banner=[SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
|
|
7875
|
-
`);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(`
|
|
7876
|
+
`);if(system.push(banner),sessionID)if(surface==="messages"&&output.deliveryBudgetReceipts){let receipt=recordProducerEmissionWithReceipt(sessionID,"swarm-command-banner",estimateTokens(banner),surface,{expectedGeneration});if(receipt)output.deliveryBudgetReceipts.push(receipt)}else recordProducerEmission(sessionID,"swarm-command-banner",estimateTokens(banner),0,surface,{expectedGeneration})}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;noteQueueScheduled();let timer=setTimeout(()=>{for(let task2 of tasks){let wrapped=wrapPostResolutionTask(task2);try{Promise.resolve(wrapped()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig,regenerateMemoryReflectionForInit=async(directory,config3)=>{let{regenerateMemoryReflection:regenerateMemoryReflection2}=await Promise.resolve().then(() => (init_reflection_service(),exports_reflection_service));return regenerateMemoryReflection2(directory,config3)};function overrideIndexInternalsForTest(overrides2){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit,previousRegenerateMemoryReflection=regenerateMemoryReflectionForInit;if(overrides2.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides2.createRepoGraphBuilderHook;if(overrides2.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides2.schedulePostResolutionTasks;if(overrides2.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides2.loadPluginConfigWithMetaAsync;if(overrides2.loadSnapshot)loadSnapshotForInit=overrides2.loadSnapshot;if(overrides2.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides2.ensureSwarmGitExcluded;if(overrides2.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides2.resolveAutoReviewConfig;if(overrides2.regenerateMemoryReflection)regenerateMemoryReflectionForInit=overrides2.regenerateMemoryReflection;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig,regenerateMemoryReflectionForInit=previousRegenerateMemoryReflection}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}async function recoverPendingCostCorrectionForTest(directory,parentSessionId,childSessionId,pricing){return recoverPendingCostCorrection(directory,parentSessionId,childSessionId,pricing)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var serverInitInvocations=0,runServerInit=async(ctx)=>{if(serverInitInvocations+=1,serverInitInvocations>1)log("[opencode-swarm] WARNING: plugin initialization invoked more than once in this process; module-level swarm state is shared between invocations (dual host load?)");beginStartupServerInterval();let postResolutionTasks=[];try{let hooks2=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),endStartupServerInterval(),hooks2}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},OpenCodeSwarm=async(ctx)=>runServerInit(ctx),MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map,pendingCostCorrectionByChildSession=new Map,scheduledCostCorrectionRecoveryBySession=new Set;function trackPendingCostCorrection(childSessionId,pending){pendingCostCorrectionByChildSession.delete(childSessionId),pendingCostCorrectionByChildSession.set(childSessionId,pending);while(pendingCostCorrectionByChildSession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=pendingCostCorrectionByChildSession.keys().next().value;if(oldest===void 0)break;pendingCostCorrectionByChildSession.delete(oldest)}}function emitPendingCostCorrection(sessionId,raw){let pending=pendingCostCorrectionByChildSession.get(sessionId);if(!pending)return!1;let fields=buildDelegationCostFields({raw,model:pending.model,gate:pending.gate,retry_index:pending.retryIndex,pricing:pending.pricing});if(fields.evidence_status!=="complete")return!0;if(!isCostUpgrade(pending.currentFields.cost_evidence??[],fields.cost_evidence??[]))return!0;let nextVersion=pending.version+1;return emit("delegation_cost_correction",{sessionId:pending.parentSessionId,agentName:pending.agentName,taskId:pending.taskId,record_id:pending.recordId,identity_fingerprint:pending.identityFingerprint,parent_session_digest:pending.parentSessionDigest,version:nextVersion,...fields}),pending.version=nextVersion,pending.currentFields=fields,!0}async function recoverPendingCostCorrection(directory,parentSessionId,childSessionId,pricing){let events=await readTelemetryEventsAsync(directory),folded=foldTelemetryEvents(events),parentSessionDigest=createHash119("sha256").update(`delegation-cost-parent-v1\x00${parentSessionId}`).digest("hex").slice(0,32),childSessionDigest=createHash119("sha256").update(`delegation-cost-child-v1\x00${childSessionId}`).digest("hex").slice(0,32),candidates=folded.events.filter((event2)=>event2.event==="delegation_end"&&event2.parent_session_digest===parentSessionDigest&&event2.cost_source!=="reported"&&typeof event2.record_id==="string"&&typeof event2.identity_fingerprint==="string"),exactCandidates=candidates.filter((event2)=>event2.child_session_digest===childSessionDigest),selectedCandidates=exactCandidates.length>0?exactCandidates:candidates;if(selectedCandidates.length===0)return null;if(selectedCandidates.length!==1)return;let event=selectedCandidates[0],effective=event;if(effective.cost_source==="reported")return null;let currentFields={tokens_input:typeof effective.tokens_input==="number"?effective.tokens_input:null,tokens_output:typeof effective.tokens_output==="number"?effective.tokens_output:null,tokens_reasoning:typeof effective.tokens_reasoning==="number"?effective.tokens_reasoning:null,tokens_cache:typeof effective.tokens_cache==="number"?effective.tokens_cache:null,cost_usd:typeof effective.cost_usd==="number"?effective.cost_usd:null,cost_source:effective.cost_source==="reported"||effective.cost_source==="estimated"?effective.cost_source:"unavailable",cost_evidence:Array.isArray(effective.cost_evidence)?effective.cost_evidence:void 0};return{recordId:event.record_id,identityFingerprint:event.identity_fingerprint,parentSessionId,parentSessionDigest,agentName:typeof event.agentName==="string"?event.agentName:"unknown",taskId:typeof event.taskId==="string"?event.taskId:"",model:typeof event.model==="string"?event.model:"unknown",gate:typeof event.gate==="string"?event.gate:void 0,retryIndex:typeof event.retry_index==="number"?event.retry_index:void 0,pricing,version:folded.versions[event.record_id]??1,currentFields}}function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")return rememberAssistantUsage(info.sessionID,info),typeof info.sessionID==="string"?{sessionId:info.sessionID,raw:info}:void 0;return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")return rememberAssistantUsage(part.sessionID,part),typeof part.sessionID==="string"?{sessionId:part.sessionID,raw:part}:void 0}return}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(_parentSessionID,taskOutput){let sessionIDs=collectSessionIDs(taskOutput);for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key2 of["sessionID","sessionId","session_id"]){let candidate2=value[key2];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key2 of["metadata","data","info","message","response","output"])visit(value[key2],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function writeBootstrapRootRedirectRecord(bootstrapRoot,openedDirectory){try{let advisoriesDir=path383.join(bootstrapRoot,".swarm","advisories");mkdirSync101(advisoriesDir,{recursive:!0}),writeFileSync66(path383.join(advisoriesDir,"bootstrap-root-redirect.json"),JSON.stringify({kind:"bootstrap-root-redirect",opened_directory:openedDirectory,project_root:bootstrapRoot,note:"Runtime state, project config, and telemetry for the opened workspace are owned by the project root."}))}catch{}}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){console.warn(`[opencode-swarm] running v${package_default.version}`),clearDeferredWarnings(),resetConfigAdvisoryDedup(),resetArchitectPromptBudgetAdvisories();let rootDecision=resolveProjectRootDecision(ctx.directory),bootstrapRoot=rootDecision.kind==="redirect"?rootDecision.owningRoot:ctx.directory,bootstrapStateWritesEnabled=rootDecision.kind!=="fail-closed",__initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(bootstrapRoot),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=bootstrapStateWritesEnabled&&hasSwarmState(bootstrapRoot)?withTimeout(loadSnapshotForInit(bootstrapRoot),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}):Promise.resolve(),gitExcludeP=bootstrapStateWritesEnabled&&hasGitMarkerAncestor(bootstrapRoot)?withTimeout(ensureSwarmGitExcludedForInit(bootstrapRoot),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})}):Promise.resolve(),projectContextP=hasManifestAncestor(ctx.directory)?(()=>{let timeoutError2=Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels");return withTimeoutSignal(async(signal2)=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory,signal2)},300,timeoutError2).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null})})():Promise.resolve(null);await Promise.all([configLoadP,snapshotP,gitExcludeP,projectContextP]);let{config:config3,loadedFromFile}=await configLoadP;if(rootDecision.kind==="redirect"){let redirectHint=`[opencode-swarm] project-root ownership: "${ctx.directory}" is an ordinary subdirectory — runtime state, project config, and telemetry for this workspace are owned by the project root "${bootstrapRoot}". Open the project root (or add a .git/.opencode marker in "${ctx.directory}") to make this directory independent.`;console.warn(redirectHint),addDeferredWarning(redirectHint),advisoryWarn(redirectHint),writeBootstrapRootRedirectRecord(bootstrapRoot,ctx.directory)}else if(rootDecision.kind==="fail-closed"){let failClosedHint=`[opencode-swarm] project-root ownership: cannot verify "${ctx.directory}" (${rootDecision.reason}) — runtime state is disabled for this session. Reopen the project from its verified root.`;console.warn(failClosedHint),addDeferredWarning(failClosedHint),advisoryWarn(failClosedHint)}if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),setGitBinaryOverride(config3.git?.binary),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}if(swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:bootstrapRoot,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),bootstrapStateWritesEnabled)registerObservabilityEventSink(bootstrapRoot),initTelemetry(bootstrapRoot);startHeartbeatTracking();let otlpExportConfig=config3.observability?.export;if(otlpExportConfig!==void 0&&bootstrapStateWritesEnabled){if(registerOtlpExporter(bootstrapRoot,otlpExportConfig),isOtlpExporterActive())postResolutionTasks.push(()=>{flushOtlpExporterForTesting(bootstrapRoot).catch(()=>{})})}let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled&&bootstrapStateWritesEnabled?repoGraphHookFactory(bootstrapRoot,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null,repoGraphInitPromise;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphInitPromise=repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();return startSnapshotCoordinationInitialization(bootstrapRoot)}),postResolutionTasks.push(()=>{runModelPreflight(config3,swarmState.opencodeClient,{generatedAgentNames:swarmState.generatedAgentNames}).then((result)=>{let msg=formatModelPreflightWarning(result);if(!msg)return;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of result.resolutions)if(resolution.status==="unresolved"||resolution.status==="missing-selection")telemetry.modelUnresolved(resolution.agent,resolution.model||"(no final selection)",resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{if(bootstrapStateWritesEnabled)runInitOrphanRecovery(bootstrapRoot).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),postResolutionTasks.push(function(){return withTimeout(bootstrapStateWritesEnabled?cleanupOldTrajectoryFiles(bootstrapRoot):Promise.resolve(),TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS,Error(`trajectory cleanup exceeded ${TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (lazy per-session cleanup remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init trajectory cleanup timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})}),postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();let retentionConfig=config3?.retention,retentionDaysValue=config3?.summaries?.retention_days,sweepCancelled=!1;return withTimeout(runRetentionSweep(bootstrapRoot,{enabled:retentionConfig?.enabled!==!1,dryRun:retentionConfig?.dry_run===!0,summariesRetentionDays:typeof retentionDaysValue==="number"&&retentionDaysValue>=1?retentionDaysValue:void 0,shouldContinue:()=>!sweepCancelled}),RETENTION_SWEEP_INIT_TIMEOUT_MS,Error(`retention sweep exceeded ${RETENTION_SWEEP_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (close-time sweeps remain a backstop)`)).catch((err2)=>{sweepCancelled=!0;let msg=err2 instanceof Error?err2.message:String(err2);log("post-init retention sweep timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})}),config3.hooks?.background_subagents===!0)postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();return withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(bootstrapRoot,{lockTimeoutMs:5000,reason:"post-init",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})),BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS,Error(`background maintenance exceeded ${BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (other maintenance points remain)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init background maintenance timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})});if(bootstrapStateWritesEnabled)writeSwarmConfigExampleIfNew(bootstrapRoot);if(postResolutionTasks.push(()=>{if(!bootstrapStateWritesEnabled)return;withTimeout(syncBundledProjectSkillsIfMissingAsync(bootstrapRoot,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await projectContextP,autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{},{preset:config3.preset})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,bootstrapRoot,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,bootstrapRoot),systemEnhancerHook=createSystemEnhancerHook(config3,bootstrapRoot),architectMessagesEnhancerHook=createSystemEnhancerHook(config3,bootstrapRoot,{surface:"messages",deferRealtimeLearningNudgeState:!0,reservedEnvelopeTokens:guidanceCarrierEnvelopeTokens("architect-session")}),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,bootstrapRoot),compactionHook=createCompactionCustomizerHook(config3,bootstrapRoot),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmID=extractSwarmIdFromAgentName(trimmedAgentName)||void 0,swarmAgents=getSwarmAgents(swarmID);return{exactAgentName:trimmedAgentName,role,swarmID,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key2 of["message","reason","code","status","statusCode","error","cause","detail","details","data","name"])parts.push(...extractBoundedErrorSignal(record3[key2],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:bootstrapRoot}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}},schedulePendingCostCorrectionRecovery=(rememberedUsage)=>{if(scheduledCostCorrectionRecoveryBySession.has(rememberedUsage.sessionId))return;scheduledCostCorrectionRecoveryBySession.add(rememberedUsage.sessionId);while(scheduledCostCorrectionRecoveryBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=scheduledCostCorrectionRecoveryBySession.values().next().value;if(oldest===void 0)break;scheduledCostCorrectionRecoveryBySession.delete(oldest)}(async()=>{let parentSessionId=await withTimeout(lookupParentSessionIDForTaskRoute(rememberedUsage.sessionId),1000,Error("late cost parent lookup exceeded 1000ms")).catch(()=>{return});if(!parentSessionId)return;let recovered=await recoverPendingCostCorrection(bootstrapRoot,parentSessionId,rememberedUsage.sessionId,config3.pricing),corrected=!1;if(recovered)trackPendingCostCorrection(rememberedUsage.sessionId,recovered),emit("delegation_cost_binding",{sessionId:parentSessionId,parent_session_digest:recovered.parentSessionDigest,record_id:recovered.recordId,identity_fingerprint:recovered.identityFingerprint,child_session_digest:createHash119("sha256").update(`delegation-cost-child-v1\x00${rememberedUsage.sessionId}`).digest("hex").slice(0,32)}),corrected=emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw);if(recovered===null)corrected=!0;if(!corrected)emit("delegation_cost_join",{sessionId:parentSessionId,reason:"join_miss"})})().catch(()=>{return}).finally(()=>{scheduledCostCorrectionRecoveryBySession.delete(rememberedUsage.sessionId)})};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel,bootstrapRoot),finalContextAccountingStep=createFinalContextAccountingStep({config:config3,directory:bootstrapRoot,resolveAgentModelFn:resolveIncomingAgentModel}),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client,config3.pricing),reviewModelDispatcher=createReviewModelDispatcher(ctx.client,config3.pricing),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),systemRenderBoundaryHook=createSystemRenderBoundaryHook(),commandHandler=createSwarmCommandHandler(bootstrapRoot,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,config:config3,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),architectMessagesCommandRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents,{surface:"messages"}),activityHooks=createAgentActivityHooks(config3,bootstrapRoot),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmConfig=config3.prm??PrmConfigSchema.parse({}),prmHook=createPrmHook(prmConfig,bootstrapRoot,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:prmConfig.max_trajectory_lines},bootstrapRoot),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,bootstrapRoot,agents),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:bootstrapRoot,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,pendingDelegationsModulePromise=null,maintainBackgroundDelegationsOnSessionEvent=async()=>{let modulePromise=pendingDelegationsModulePromise;if(modulePromise===null)modulePromise=Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).catch((err2)=>{throw pendingDelegationsModulePromise=null,err2}),pendingDelegationsModulePromise=modulePromise;await(await modulePromise).maintainBackgroundDelegations(bootstrapRoot,{lockTimeoutMs:2000,reason:"session-close",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})},delegationSanitizerHook=createDelegationSanitizerHook(bootstrapRoot),trainingCaptureObserver=createTrainingCaptureObserver(bootstrapRoot),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:bootstrapRoot,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(bootstrapStateWritesEnabled?regenerateMemoryReflectionForInit(bootstrapRoot,reflectionConfig):Promise.resolve(),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback),dispatchProtectionConfig=DispatchProtectionConfigSchema.parse(config3.dispatch_protection??{});if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled,bootstrapRoot),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,guardrailsHooks=createGuardrailsHooks(bootstrapRoot,void 0,guardrailsConfig,authorityConfig,worktreeDirOverride?[worktreeDirOverride]:[],resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,bootstrapRoot),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:bootstrapRoot}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:bootstrapRoot}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:bootstrapRoot}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,bootstrapRoot),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard},bootstrapRoot,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:bootstrapRoot,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:bootstrapRoot,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},bootstrapRoot,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(bootstrapRoot),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:bootstrapRoot,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,bootstrapRoot),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:bootstrapRoot,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(bootstrapRoot,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(bootstrapRoot,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(bootstrapRoot,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(bootstrapRoot,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(bootstrapRoot),coChangeSuggesterHook=createCoChangeSuggesterHook(bootstrapRoot),darkMatterDetectorHook=createDarkMatterDetectorHook(bootstrapRoot),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=bootstrapStateWritesEnabled?createSnapshotWriterHook(bootstrapRoot):async()=>{},automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){if(automationManager=createAutomationManager(automationConfig),bootstrapStateWritesEnabled)automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{getSharedAutomationStatusArtifact:getSharedAutomationStatusArtifact2}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path383.resolve(bootstrapRoot,".swarm"),automationStatusArtifactPostInitTask=async()=>{try{getSharedAutomationStatusArtifact2(swarmDir).updateConfig(automationConfig.mode,automationConfig.capabilities)}catch(err2){log("automation status artifact init failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}};if(bootstrapStateWritesEnabled)postResolutionTasks.push(automationStatusArtifactPostInitTask);if(automationConfig.capabilities?.evidence_auto_summaries===!0&&bootstrapStateWritesEnabled){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:bootstrapRoot,projectDir:bootstrapRoot,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:bootstrapRoot})}if(automationConfig.capabilities?.phase_preflight===!0&&bootstrapStateWritesEnabled){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:bootstrapRoot,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:bootstrapRoot})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0&&bootstrapStateWritesEnabled)try{planSyncWorker=new PlanSyncWorker({directory:bootstrapRoot}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:bootstrapRoot})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}ensurePrSubscriptionDispatcherInstalled(),registerPrMonitorWorkerHandler(bootstrapRoot,ensurePrMonitorWorkerRunning);let prEventCleanup=null,prFeedbackLoopRuntimeCleanup=null;if(isPrFeedbackLoopEnabled(config3))try{let registration=registerPrFeedbackLoopRuntime({client:ctx.client,directory:ctx.directory,config:config3,agentNames:instanceGeneratedAgentNames,resolveSessionAgent:(sessionID)=>swarmState.activeAgent.get(sessionID)??getAgentSession(sessionID)?.agentName});prFeedbackLoopRuntimeCleanup=registration,postResolutionTasks.push(()=>registration.promote())}catch(err2){log("[pr-feedback-loop] Runtime registration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}let prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:bootstrapRoot,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery)),registration=deliveryModule.registerPrEventDelivery({client:ctx.client,directory:bootstrapRoot,config:prMonitorConfig});postResolutionTasks.push(()=>registration.promote()),prEventDelivery={noteSessionIdle:(sessionID,directory)=>deliveryModule.noteSessionIdle(sessionID,directory),unregister:registration}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(bootstrapRoot,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(bootstrapRoot).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(bootstrapRoot)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let automationCleaned=!1,cleanupAutomation=()=>{if(automationCleaned)return;automationCleaned=!0,automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),dashboardDisposed=!0;try{closeDashboardServerForRootIfOwner(bootstrapRoot,dashboardHandleRef.current)}catch{}removePrMonitorWorkerHandler(bootstrapRoot,ensurePrMonitorWorkerRunning),prEventCleanup?.(),prEventDelivery?.unregister(),prFeedbackLoopRuntimeCleanup?.(),markSnapshotCoordinationClosing(bootstrapRoot);try{if(closeGroupCommitWriter(bootstrapRoot),getSnapshotCoordinationStatus(bootstrapRoot).settled)closeProjectDb(bootstrapRoot)}catch{}},instanceExitCleanupToken=`${bootstrapRoot}#${++instanceExitCleanupCounter}`;if(registerProcessExitCleanupDispatcher(),instanceExitCleanups.set(instanceExitCleanupToken,cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(bootstrapRoot,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}let dashboardPort=config3.dashboard?.port??0,dashboardHandleRef={current:null},dashboardDisposed=!1;if(dashboardPort>0)postResolutionTasks.push(async function(){try{let{startDashboardServer:startDashboardServer2}=await Promise.resolve().then(() => (init_dashboard(),exports_dashboard)),handle=await startDashboardServer2({port:dashboardPort,host:"127.0.0.1",directory:bootstrapRoot});if(!handle.listening){advisoryWarn(`Swarm dashboard disabled: port ${dashboardPort} is unavailable (in use or bind failed). Free the port or change dashboard.port in opencode-swarm.json.`);return}if(dashboardDisposed){handle.close();return}dashboardHandleRef.current=handle,log("swarm dashboard listening (loopback, token-protected)",{port:handle.port})}catch(err2){log("dashboard startup failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}});log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}});let messagesTransformTrainingCaptureStep=(_input,output)=>{return trainingCaptureObserver.observeMessages(output)},messagesTransformDelegationLedgerStep=(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},stagedArchitectGuidanceByMessages=new WeakMap,settleDeliveryBudgetReceipts=(receipts,action2)=>{for(let receipt of receipts)if(action2==="commit")commitInjectionBudgetReceipt(receipt);else refundInjectionBudgetReceipt(receipt)},messagesTransformArchitectEnhancerStage=async(_input,output)=>{let messages=output?.messages;if(!Array.isArray(messages))return;let mctx=resolveMessageTransformContext(output),sessionID=mctx.sessionID;if(!sessionID)return;let compactionPending=_architectCompactionPending.delete(sessionID);if(!isSessionBoundArchitect(sessionID,mctx.agent)||compactionPending)return;let identity=getLiveContextModelIdentity(sessionID),context=identity?getLiveContextWindow(sessionID,identity):void 0,model=identity?{id:identity.modelID,providerID:identity.providerID,limit:context===void 0?void 0:{context}}:void 0,stagedOutput={system:[],deliveryBudgetReceipts:[],deferredRealtimeLearningNudges:[]},enhancer=architectMessagesEnhancerHook["experimental.chat.system.transform"];try{if(typeof enhancer==="function")await enhancer({sessionID,model},stagedOutput);let stagedAgent=mctx.agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName??"architect";stagedArchitectGuidanceByMessages.set(messages,{sessionID,agent:stagedAgent,system:stagedOutput.system,deferredRealtimeLearningNudges:stagedOutput.deferredRealtimeLearningNudges??[],turnLedgerGeneration:stagedOutput.turnLedgerGeneration,systemEnhancerBudgetReceipt:stagedOutput.systemEnhancerBudgetReceipt,fenceBudgetReceipt:stagedOutput.fenceBudgetReceipt,deliveryBudgetReceipts:stagedOutput.deliveryBudgetReceipts})}catch{if(settleDeliveryBudgetReceipts(stagedOutput.deliveryBudgetReceipts,"refund"),stagedOutput.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(stagedOutput.systemEnhancerBudgetReceipt);if(stagedOutput.fenceBudgetReceipt)refundInjectionBudgetReceipt(stagedOutput.fenceBudgetReceipt)}},messagesTransformArchitectEnhancerDeliveryStep=async(_input,output)=>{let messages=output?.messages;if(!Array.isArray(messages))return;let staged=stagedArchitectGuidanceByMessages.get(messages);if(!staged)return;stagedArchitectGuidanceByMessages.delete(messages);let deliveryConfirmed=!1;try{let stagedOutput={system:staged.system,deliveryBudgetReceipts:staged.deliveryBudgetReceipts};await roleFilterSystemHook["experimental.chat.system.transform"]({sessionID:staged.sessionID,agent:staged.agent,expectedGeneration:staged.turnLedgerGeneration},stagedOutput),await architectMessagesCommandRuleHook({sessionID:staged.sessionID,agent:staged.agent,expectedGeneration:staged.turnLedgerGeneration},stagedOutput);let text=stagedOutput.system.filter((entry)=>entry.trim()).join(`
|
|
7876
7877
|
|
|
7877
|
-
`),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};
|
|
7878
|
+
`),carrier=appendGuidanceCarrier(messages,"architect-session",text,{sessionID:staged.sessionID});if(!deliveredGuidanceDelta(carrier,text)){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt);return}if(staged.systemEnhancerBudgetReceipt)commitInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)commitInjectionBudgetReceipt(staged.fenceBudgetReceipt);settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"commit"),deliveryConfirmed=!0;for(let sessionID of staged.deferredRealtimeLearningNudges)recordRealtimeLearningNudge(sessionID);let carrierTokens=estimateTokens(messageTextOf(carrier)),stagedTokens=estimateTokens(text),fenceOverheadTokens=Math.max(0,carrierTokens-stagedTokens);if(fenceOverheadTokens>0){if(staged.sessionID&&staged.turnLedgerGeneration!==void 0)recordProducerEmission(staged.sessionID,"guidance-carrier-fence",fenceOverheadTokens,0,"messages",{expectedGeneration:staged.turnLedgerGeneration})}}catch{if(!deliveryConfirmed){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt)}}},messagesTransformKnowledgeApplicationScanStep=(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(bootstrapRoot,output,mctx.sessionID)}catch{return Promise.resolve()}},messagesTransformSkillPropagationScanStep=(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(bootstrapRoot,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},messagesTransformSystemGuidanceMaterializeStep=(_input,output)=>{if(Array.isArray(output.messages))materializeSystemGuidanceInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()},messagesTransformGuidanceCarrierOrderStep=(_input,output)=>{if(Array.isArray(output?.messages))moveGuidanceCarriersToEnd(output.messages);return Promise.resolve()},systemTransformStartDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemTransformEnhancerDoneDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},systemTransformHeartbeatStep=(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS,sessionID),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()};return{name:"opencode-swarm",dispose:async()=>{try{cancelDeferredMaintenanceScans(bootstrapRoot)}catch(err2){log("dispose deferred-scan cancellation failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(cleanupAutomation(),instanceExitCleanups.delete(instanceExitCleanupToken),instanceExitCleanups.size===0&&processExitCleanupRegistered){process.off("exit",runInstanceExitCleanups);for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.off(signal2,handler);processSignalCleanupHandlers=[],processExitCleanupRegistered=!1}evictAndClose(bootstrapRoot);try{await closeSnapshotCoordinationInitialization(bootstrapRoot),closeGroupCommitWriter(bootstrapRoot),closeProjectDb(bootstrapRoot)}catch(err2){log("dispose durable-state close failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{let rememberedUsage=rememberAssistantUsageEvent(input);if(rememberedUsage){if(!emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw))schedulePendingCostCorrectionRecovery(rememberedUsage)}let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&typeof part?.tool==="string"&&isTaskToolId(part.tool)&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(bootstrapRoot,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:resolveSessionChatAgent(childSessionID)??swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels});else if(!route&&routeModel&&routeModel.fallbackModels.length>0&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal))){let advanced=advanceSessionFallbackSelection({sessionID:childSessionID,role:routeModel.role,swarmID:routeModel.swarmID,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels}),reason=isQuotaError(errorSignal)?"quota":"transient";telemetry.modelFallback(childSessionID,routeModel.role,routeModel.primaryModel??"unknown",advanced.modelString??"exhausted",reason);let session=swarmState.agentSessions.get(childSessionID);if(session){if(advanced.exhausted)pushAdvisory(session,`MODEL FALLBACK: [primary-model-fallback-exhausted:${routeModel.role}] all configured fallback models for ${routeModel.role} failed after a provider ${reason} error; staying on the session's selected model.`,{dedupeKey:`[primary-model-fallback-exhausted:${routeModel.role}]`});else if(advanced.accepted&&advanced.modelString)pushAdvisory(session,`MODEL FALLBACK: [primary-model-fallback:${routeModel.role}] switching ${routeModel.role} from configured primary ${routeModel.primaryModel??"unknown"} to ${advanced.modelString} after a provider ${reason} error; the next message uses the fallback.`,{dedupeKey:`[primary-model-fallback:${routeModel.role}]`})}}}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"){_architectCompactionPending.delete(sessionID);try{await terminalizePrWorkflowGateForSession2(bootstrapRoot,sessionID)}catch{warn("PR workflow gate terminalization on session deletion failed (non-fatal)")}try{let reconciliation=reconcilePrWorkflowCheckoutReceipts(bootstrapRoot,sessionID),summary=await withTimeout(reconciliation,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS,Error("PR workflow checkout receipt reconciliation exceeded the session-deletion event budget"));log("PR workflow checkout receipts reconciled on session deletion",{inspected:summary.inspectedReceiptCount,collected:summary.collectedStashOids.length,retiredMissing:summary.retiredMissingStashOids.length,preserved:summary.preservedStashOids.length,failures:summary.failures.length})}catch{warn("PR workflow checkout receipt reconciliation on session deletion failed or exceeded its event budget (non-fatal)")}if(bootstrapStateWritesEnabled)deleteSnapshotSessionRows(bootstrapRoot,sessionID);clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID)}if(backgroundSubagentsEnabled&&bootstrapStateWritesEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}try{let{recoverTerminalLaneReceipts:recoverTerminalLaneReceipts2}=await Promise.resolve().then(() => (init_delegation_lifecycle(),exports_delegation_lifecycle));await recoverTerminalLaneReceipts2(bootstrapRoot)}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID,ctx.directory)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan (runs the canonical command)"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-harness-opt":{template:"/swarm harness-opt $ARGUMENTS",description:"Use /swarm harness-opt to govern harness optimization rounds (plan|run|status|stop|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-report":{template:"/swarm report $ARGUMENTS",description:"Use /swarm report to query swarm observability events (--task/--session/--trace/--run/--since/--json)"},"swarm-dashboard":{template:"/swarm dashboard",description:"Use /swarm dashboard to show the opt-in local mission-control dashboard URL and status"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-dataset-consent":{template:"/swarm dataset consent $ARGUMENTS",description:"Use /swarm dataset consent to grant or revoke the training-content consent (human-only, confirm token)"},"swarm-dataset-export":{template:"/swarm dataset export $ARGUMENTS",description:"Use /swarm dataset export to preview/write the deterministic governed dataset export (human-only, confirm token)"},"swarm-dataset-withdraw":{template:"/swarm dataset withdraw $ARGUMENTS",description:"Use /swarm dataset withdraw to purge vault content, tombstone, and revoke exports (human-only, confirm token)"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop; cancel an armed PR_FEEDBACK without publication with PR_FEEDBACK --cancel-publication <reason...> (human-only escape hatch)"},"swarm-pr-feedback-loop":{template:"/swarm pr-feedback-loop $ARGUMENTS",description:"Use /swarm pr-feedback-loop stop <reason...> to stop the autonomous PR babysitting settling loop for this session (human-only)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-approve-write":{template:"/swarm approve-write $ARGUMENTS",description:"Use /swarm approve-write to issue one exact, session-bound, one-shot write approval (human-only)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-ci":{template:"/swarm ci $ARGUMENTS",description:shortcutDescription("ci")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-blueprint-validate":{template:"/swarm blueprint validate $ARGUMENTS",description:shortcutDescription("blueprint validate")},"swarm-blueprint-current":{template:"/swarm blueprint current",description:shortcutDescription("blueprint current")},"swarm-blueprint-history":{template:"/swarm blueprint history",description:shortcutDescription("blueprint history")},"swarm-blueprint-diff":{template:"/swarm blueprint diff $ARGUMENTS",description:shortcutDescription("blueprint diff")},"swarm-blueprint-export":{template:"/swarm blueprint export $ARGUMENTS",description:shortcutDescription("blueprint export")},"swarm-harness-candidate-validate":{template:"/swarm harness candidate validate $ARGUMENTS",description:shortcutDescription("harness candidate validate")},"swarm-harness-candidate-show":{template:"/swarm harness candidate show $ARGUMENTS",description:shortcutDescription("harness candidate show")},"swarm-harness-candidate-diff":{template:"/swarm harness candidate diff $ARGUMENTS",description:shortcutDescription("harness candidate diff")},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":withStartupFirstUseTracking("first_turn",void 0,composeHandlers(...[messagesTransformArchitectEnhancerStage,messagesTransformTrainingCaptureStep,messagesTransformDelegationLedgerStep,pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,messagesTransformKnowledgeApplicationScanStep,messagesTransformSkillPropagationScanStep,messagesTransformArchitectEnhancerDeliveryStep,messagesTransformSystemGuidanceMaterializeStep,messagesTransformGuidanceCarrierOrderStep,finalContextAccountingStep].filter((fn2)=>Boolean(fn2)))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[systemTransformStartDiagnostic,systemEnhancerHook["experimental.chat.system.transform"],systemTransformEnhancerDoneDiagnostic,contextCapsuleInjectHook["experimental.chat.system.transform"],systemTransformHeartbeatStep,automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(bootstrapRoot,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(bootstrapRoot,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"],systemRenderBoundaryHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":async(input,output)=>{let{sessionID}=input??{};if(sessionID)_architectCompactionPending.delete(sessionID),_architectCompactionPending.set(sessionID,!0),capSessionMap(_architectCompactionPending,MAX_TRACKED_ARCHITECT_COMPACTIONS,sessionID),advanceTurnGeneration(sessionID);let delegate=compactionHook["experimental.session.compacting"];if(typeof delegate==="function")await delegate(input,output)},"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME,bootstrapRoot)}}let failClosedRegionCompleted=!1;try{if(dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool)){let armed=armDispatchIdentity(input.callID,input.tool,output.args),invocationID=invocationIdForSession(input.sessionID);assertDispatchSpawnCircuitAdmits({sessionID:input.sessionID,invocationID,actionDigest:armed.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms}),await acquireDispatchToken({directory:bootstrapRoot,ratePerSecond:dispatchProtectionConfig.rate_per_second,burstCapacity:dispatchProtectionConfig.burst_capacity})}await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(bootstrapRoot,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames,input.callID),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{},skillAttributionPlanTaskOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(bootstrapRoot));if(injectSkillsIntoDelegation(bootstrapRoot,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet,...skillAttributionPlanTaskOptions}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(bootstrapRoot,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getFinalPromptPressure(input.sessionID)?.pct??getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE (estimated): ${pressurePct.toFixed(1)}% estimated prompt pressure of the model context window. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),isTaskToolId(input.tool)&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}if(resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs),isTaskToolId(input.tool)){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY,input.callID),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,bootstrapRoot,{maxLines:prmConfig.max_trajectory_lines})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(isTaskToolId(input.tool))try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID,input.sessionID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let isTaskTool8=isTaskToolId(input.tool),afterCtx=resolveToolAfterContext(input);if(await safeHook(()=>trainingCaptureObserver.observeToolExecution({tool:input.tool,sessionID:input.sessionID,input:afterCtx.args,output,error:output?.state==="error"?output:void 0}))(input,output),dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool))try{let identity=takeArmedDispatchIdentity(input.callID)??dispatchIdentityFor(input.tool,afterCtx.args),invocationID=invocationIdForSession(input.sessionID);if(output?.state==="error"){let{opened}=noteDispatchSpawnFailure({sessionID:input.sessionID,invocationID,actionDigest:identity.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms});if(opened)telemetry.loopDetected(input.sessionID,swarmState.activeAgent.get(input.sessionID)??"agent",`dispatch.spawn:${identity.pattern}`)}else if(output?.state==="completed")noteDispatchSpawnSuccess({sessionID:input.sessionID,invocationID,actionDigest:identity.digest})}catch{}try{let pushCommand=afterCtx.args?.command;if(typeof pushCommand==="string"&&/^\s*git\s+push/i.test(pushCommand)){let pushAttemptSessionID=await prWorkflowSessionResolver.resolve(input.sessionID);await recordPrFeedbackPushAttemptResult(bootstrapRoot,{sessionID:pushAttemptSessionID,callID:input.callID,tool:input.tool},pushCommand,output)}}catch{}if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(bootstrapRoot,input,output,createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(bootstrapRoot).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(_toolName,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(bootstrapRoot,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,bootstrapRoot),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",decisions:extractContextDecisionsFromContextMd(bootstrapRoot,{agent_role:resolveSessionChatAgent(input.sessionID)??swarmState.activeAgent.get(input.sessionID)??"unknown"}),directory:bootstrapRoot})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing}),childSessionID=collectSessionIDs(output)[0],recordMaterial=`${sessionId}\x00${input.callID}`;if(costFields.record_id=createHash119("sha256").update(`delegation-cost-id-v1\x00${recordMaterial}`).digest("hex").slice(0,32),costFields.identity_fingerprint=createHash119("sha256").update(`delegation-cost-identity-v1\x00${recordMaterial}\x00${agentName}\x00${configuredModel}`).digest("hex").slice(0,32),costFields.version=1,costFields.parent_session_digest=createHash119("sha256").update(`delegation-cost-parent-v1\x00${sessionId}`).digest("hex").slice(0,32),childSessionID)costFields.child_session_digest=createHash119("sha256").update(`delegation-cost-child-v1\x00${childSessionID}`).digest("hex").slice(0,32);swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME,bootstrapRoot);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){let costTaskId=beganDelegation?.taskId||taskSession.currentTaskId||"";if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,costTaskId,"completed",costFields),childSessionID&&costFields.evidence_status!=="complete"&&costFields.record_id&&costFields.identity_fingerprint)trackPendingCostCorrection(childSessionID,{recordId:costFields.record_id,identityFingerprint:costFields.identity_fingerprint,parentSessionId:sessionId,parentSessionDigest:costFields.parent_session_digest,agentName,taskId:costTaskId,model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retryIndex:activeWindow?.transientRetryCount,pricing:config3.pricing,version:1,currentFields:costFields});if(baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=applySoundingBoardResponsePolicy(rawResponse,afterCtx.args);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.category)verdictMsg+=` Category: ${parsed.category}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){recordSessionChatAgent(String(input.sessionID),input.agent);let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);try{if(input2?.sessionID&&typeof input2?.agent==="string"&&input2.agent.trim()!=="")maybeEmitNonArchitectAdvisory(String(input2.sessionID),String(input2.agent))}catch{}if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model;else if(resolution.status==="missing"){let sessionResolution=resolveSessionChatModelOverride({sessionID:String(input2.sessionID),role:routeModel.role,swarmID:routeModel.swarmID,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels});if(sessionResolution.status==="override"&&sessionResolution.model)output2.message.model=sessionResolution.model}}}if(input2?.sessionID){let messageModel=output2.message?.model;if(messageModel&&typeof messageModel==="object")setLiveContextWindow(String(input2.sessionID),void 0,{modelID:typeof messageModel.modelID==="string"?messageModel.modelID:typeof messageModel.id==="string"?messageModel.id:void 0,providerID:typeof messageModel.providerID==="string"?messageModel.providerID:void 0})}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(bootstrapRoot,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(bootstrapRoot,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm,setup:(ctx)=>openCodeSwarmV2Setup(ctx,{runInit:runServerInit})};export{schedulePostResolutionTasksForTest,recoverPendingCostCorrectionForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,applySoundingBoardResponsePolicy,_resetDelegationTelemetryPairingForTesting};
|