opencode-swarm 7.170.0 → 7.170.2
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/agents/reviewer-directive-compliance.d.ts +23 -7
- package/dist/cli/{coder-settlement-65zx1bet.js → coder-settlement-rrm3ngsa.js} +7 -7
- package/dist/cli/{config-doctor-c30rss1c.js → config-doctor-rnfyv55m.js} +2 -2
- package/dist/cli/{core-8wkbr1tr.js → core-b161yfjy.js} +1 -1
- package/dist/cli/{curation-policy-k74qz9ms.js → curation-policy-tg84dnnd.js} +4 -4
- package/dist/cli/{curator-pckzk1q4.js → curator-dfcpzqwr.js} +28 -28
- package/dist/cli/{curator-llm-factory-jkjqasfs.js → curator-llm-factory-cjrh0sa3.js} +28 -28
- package/dist/cli/{evidence-summary-service-4ydcapke.js → evidence-summary-service-7jfq6dax.js} +11 -11
- package/dist/cli/{gate-evidence-xwqfky3m.js → gate-evidence-0e70dqjg.js} +4 -4
- package/dist/cli/{guardrail-explain-fe2veh2s.js → guardrail-explain-a40pmzzc.js} +29 -29
- package/dist/cli/{guardrail-log-z38j69bx.js → guardrail-log-71wvwyd0.js} +6 -6
- package/dist/cli/{guardrail-reset-mmnzt4mz.js → guardrail-reset-znw5636e.js} +28 -28
- package/dist/cli/{hive-promoter-68hrw1y1.js → hive-promoter-pznn5yfn.js} +28 -28
- package/dist/cli/{index-ye43mdfm.js → index-19xctk9g.js} +1 -1
- package/dist/cli/{index-3eh2n3dx.js → index-1kt9xbrt.js} +2 -2
- package/dist/cli/{index-mjn6aqqk.js → index-24pamt0h.js} +2 -2
- package/dist/cli/{index-td6xrw55.js → index-29gnavqx.js} +1 -1
- package/dist/cli/{index-06rbdzqn.js → index-2q6qj0vw.js} +3 -3
- package/dist/cli/{index-3p3y55xg.js → index-3q7bb7qz.js} +7 -7
- package/dist/cli/{index-r1z8nrb6.js → index-45x6meqp.js} +5 -5
- package/dist/cli/{index-9xk97bcf.js → index-4m9hfbhe.js} +3 -3
- package/dist/cli/{index-xnpjwc4h.js → index-4say55ww.js} +1 -1
- package/dist/cli/{index-5qt9yf5w.js → index-5y7kqjyt.js} +1 -1
- package/dist/cli/{index-gfbggp8k.js → index-70avfxnw.js} +3 -3
- package/dist/cli/{index-xztkjj3c.js → index-7a180w76.js} +30 -30
- package/dist/cli/{index-j144fgk8.js → index-7htmxmjp.js} +71 -70
- package/dist/cli/{index-z5vas8c3.js → index-7pgzjj3z.js} +28 -28
- package/dist/cli/{index-nprdr0sm.js → index-7sz2rkx3.js} +2 -2
- package/dist/cli/{index-31sqcdsd.js → index-8v2k9xqv.js} +4 -4
- package/dist/cli/{index-4wc5gfgm.js → index-9g3c0w22.js} +1 -1
- package/dist/cli/{index-59fcfpkh.js → index-9vxaf499.js} +1 -1
- package/dist/cli/{index-7h01bkm6.js → index-a0vggadp.js} +1 -1
- package/dist/cli/{index-8w1mrvbd.js → index-d1sdve0x.js} +7 -7
- package/dist/cli/{index-pw00xcj0.js → index-dbg2g834.js} +4 -4
- package/dist/cli/{index-n0d5hrs4.js → index-efkxjmdb.js} +2 -2
- package/dist/cli/{index-9ttqbhvw.js → index-g0q47r3r.js} +1 -1
- package/dist/cli/{index-zw3hkzch.js → index-g2sc35qk.js} +12 -4
- package/dist/cli/{index-p6fj7qz7.js → index-gs4m1dxw.js} +3 -3
- package/dist/cli/{index-5bbem0ey.js → index-j1tjd6aq.js} +5 -5
- package/dist/cli/{index-fgp96k3r.js → index-p6zt0qm1.js} +2 -2
- package/dist/cli/{index-bx1wgn3a.js → index-sf32ny5w.js} +1 -1
- package/dist/cli/{index-0xprxg95.js → index-w79t20a6.js} +3 -3
- package/dist/cli/{index-3axdtaf0.js → index-we9jztxd.js} +4 -4
- package/dist/cli/{index-ssx8087p.js → index-x067zyvp.js} +6 -6
- package/dist/cli/{index-t73888m0.js → index-z4ewmn1h.js} +1 -1
- package/dist/cli/{index-bm5xrfnx.js → index-zr6ev5kt.js} +1 -1
- package/dist/cli/index.js +28 -28
- package/dist/cli/{knowledge-escalator-pz2faktx.js → knowledge-escalator-95gqgg8e.js} +10 -10
- package/dist/cli/{knowledge-events-s6s8qedx.js → knowledge-events-hcx770h3.js} +8 -8
- package/dist/cli/{knowledge-link-rkxfrmhm.js → knowledge-link-twmzh8cf.js} +3 -3
- package/dist/cli/{knowledge-store-dgv3xw3h.js → knowledge-store-ppmrqs41.js} +4 -4
- package/dist/cli/{knowledge-validator-22qppdyv.js → knowledge-validator-63rfvqmw.js} +6 -6
- package/dist/cli/{pending-delegations-4r21nf9d.js → pending-delegations-dqdetx92.js} +6 -6
- package/dist/cli/{pr-subscriptions-d52xy3zd.js → pr-subscriptions-z9t7f7m0.js} +6 -6
- package/dist/cli/{pr-workflow-gate-0de81kzw.js → pr-workflow-gate-wqrcb5m8.js} +28 -28
- package/dist/cli/{runner-1dwrgyyr.js → runner-2r5j33tm.js} +4 -4
- package/dist/cli/{scan-cursor-ahbbejab.js → scan-cursor-xzmmf7r4.js} +5 -5
- package/dist/cli/{schema-17h2hcw9.js → schema-6bn7mj29.js} +1 -1
- package/dist/cli/{scope-persistence-gcn3zm5e.js → scope-persistence-wyg0rb07.js} +10 -10
- package/dist/cli/{skill-generator-hkqr5qs7.js → skill-generator-kwnwapfn.js} +12 -12
- package/dist/cli/{snapshot-coordination-init-ms36zxv6.js → snapshot-coordination-init-ajvmd1z6.js} +28 -28
- package/dist/cli/{telemetry-fdtaemnv.js → telemetry-yst95z2f.js} +1 -1
- package/dist/cli/{worktree-collision-ownership-7v7gg511.js → worktree-collision-ownership-dm6nq9yw.js} +6 -6
- package/dist/cli/{worktree-isolation-nanamt25.js → worktree-isolation-b10h20sv.js} +28 -28
- package/dist/hooks/incremental-verify.d.ts +3 -1
- package/dist/hooks/normalize-tool-name.d.ts +16 -0
- package/dist/hooks/phase-complete-directive-gate.d.ts +13 -0
- package/dist/hooks/phase-directives.d.ts +31 -2
- package/dist/hooks/reviewer-verdict-parser.d.ts +6 -1
- package/dist/index.js +35 -27
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.170.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","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:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.170.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","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","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:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -465,7 +465,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
|
|
|
465
465
|
lease_expires_at = excluded.lease_expires_at, payload = excluded.payload,
|
|
466
466
|
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
|
|
467
467
|
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
|
|
468
|
-
(source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals13.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals13;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals13={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals14.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals14;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals14={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:431"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:428"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:415"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:255"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:639",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:643",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:647",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:685",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:733",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:915",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:923",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:948",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:651",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:661",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:785",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:1796",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:1816",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:766",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:780",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:694",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:711",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:698",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:721",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:737",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:756",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1305",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:794",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:803",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:807",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:903",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:911",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:933",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:821",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:842",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:856",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:873",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:890",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1286",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:963",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:977",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:990",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1004",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:348",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1783",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1587",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1041",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1063",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:1087",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:1124",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:1150",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:1174",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:1197",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:1226",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:1270",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),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}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals15,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals15.createObservation(event,data),line=JSON.stringify(_internals15.toLegacyTelemetryLine(canonical))+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)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals15.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals15;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals15.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals15.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals15.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals15.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals15.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals15.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals15.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals15.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals15.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals15.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals15.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals15.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals15.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals15.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals15.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals15.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals15.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals15.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals15.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals15.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals15.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals15.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals15.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals15.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals15.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals15.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals15.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals15.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals15.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals15.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals15.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals15.emit("close_archive_result",data)},residueHealth(data){_internals15.emit("residue_health",data)},contextTelemetryHealth(data){_internals15.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals15.emit("skill_usage_health",data)},coreEventsHealth(data){_internals15.emit("core_events_health",data)},shellAuditHealth(data){_internals15.emit("shell_audit_health",data)},trajectoryHealth(data){_internals15.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals15.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals15.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals15.emit("retrieval_routed",{sessionId,...data})}},_internals15={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals16.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path14.dirname(current);if(parent===current)break;if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals16;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals16={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
|
|
468
|
+
(source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals13.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals13;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals13={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals14.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals14;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals14={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:431"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:428"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:415"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:255"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:639",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:643",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:647",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:685",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:733",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:915",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:923",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:948",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:651",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:661",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:785",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:1802",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:1822",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:766",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:780",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:694",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:711",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:698",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:721",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:737",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:756",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1305",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:794",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:803",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:807",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:903",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:911",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:933",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:821",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:842",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:856",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:873",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:890",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1286",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:963",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:977",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:990",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1004",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:348",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1783",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1587",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1041",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1063",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:1087",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:1124",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:1150",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:1174",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:1197",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:1226",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:1270",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),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}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals15,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals15.createObservation(event,data),line=JSON.stringify(_internals15.toLegacyTelemetryLine(canonical))+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)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals15.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals15;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals15.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals15.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals15.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals15.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals15.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals15.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals15.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals15.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals15.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals15.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals15.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals15.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals15.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals15.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals15.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals15.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals15.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals15.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals15.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals15.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals15.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals15.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals15.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals15.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals15.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals15.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals15.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals15.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals15.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals15.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals15.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals15.emit("close_archive_result",data)},residueHealth(data){_internals15.emit("residue_health",data)},contextTelemetryHealth(data){_internals15.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals15.emit("skill_usage_health",data)},coreEventsHealth(data){_internals15.emit("core_events_health",data)},shellAuditHealth(data){_internals15.emit("shell_audit_health",data)},trajectoryHealth(data){_internals15.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals15.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals15.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals15.emit("retrieval_routed",{sessionId,...data})}},_internals15={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals16.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path14.dirname(current);if(parent===current)break;if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals16;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals16={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
|
|
469
469
|
`).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}
|
|
470
470
|
`,"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()}
|
|
471
471
|
`,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(`
|
|
@@ -696,8 +696,8 @@ try {
|
|
|
696
696
|
} catch {
|
|
697
697
|
[Console]::Error.WriteLine($_.Exception.Message);
|
|
698
698
|
exit 1;
|
|
699
|
-
}`,encodedScript=Buffer2.from(psScript,"utf16le").toString("base64");return`& '${psSingleQuoteEscape(powerShellExe)}' -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ${encodedScript}; exit $LASTEXITCODE`}getEnvOverrides(){return{PATH:getSafeWindowsPath(),TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null}}}var SANDBOX_UNAVAILABLE_CODES2,DEFAULT_SYSTEM_ROOT="C:\\Windows",UNSAFE_PATH_CHARACTERS,_internals41;var init_restricted_environment_executor=__esm(()=>{init_logger();init_executor();SANDBOX_UNAVAILABLE_CODES2=new Set(["ENOENT","EACCES","EPERM","ENOSPC"]),UNSAFE_PATH_CHARACTERS=new Set([":",'"',"'",";","&","|","<",">","^","%","!","?","*","`","$"]);_internals41={probeWindowsSandbox}});import*as crypto4 from"node:crypto";import*as fs26 from"node:fs";import*as os13 from"node:os";import*as path45 from"node:path";class NativeWindowsSandboxExecutor{mechanism;_probeResult;_fallbackExecutor;_strength;_disabled;_disabledReason;constructor(scopePaths=[],tempDir){if(this._disabled=!1,this._disabledReason=null,this._fallbackExecutor=new WindowsSandboxExecutor(scopePaths,tempDir),this._probeResult=probe(),this._probeResult.available)this._strength="strong",this.mechanism=`native-runner/${this._probeResult.mode}`;else if(this._fallbackExecutor.isAvailable())this._strength="weak",this.mechanism="powershell-wrapper",criticalWarn(`[sandbox] native Windows sandbox runner unavailable (${sanitizeDiagnosticText(this._probeResult.error??"unknown",200)}); falling back to PowerShell environment restrictions (weak sandbox). Run /swarm diagnose for details.`);else this._strength="none",this.mechanism="none"}get strength(){if(this._disabled)return"none";return this._strength}isAvailable(){return!this._disabled&&this._strength!=="none"}disable(reason){this._disabled=!0,this._disabledReason=reason,criticalWarn(`[sandbox] Sandbox disabled: ${sanitizeDiagnosticText(reason,200)}. Falling through to tool-layer enforcement. Run /swarm diagnose for details.`)}wrapCommand(command,scopePaths,tempDir,envOverrides,policy){if(!this.isAvailable())throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");if(this._strength==="strong"){if(/["&|<>^%]/.test(command))return this._fallbackExecutor.wrapCommand(command,scopePaths,tempDir,envOverrides);return this._wrapWithRunner(command,scopePaths,tempDir,envOverrides,policy)}return this._fallbackExecutor.wrapCommand(command,scopePaths,tempDir,envOverrides)}_wrapWithRunner(command,scopePaths,tempDir,_envOverrides,policyOverride){let binary=_internals39.findRunnerBinary();if(!binary)throw new SandboxError("Runner binary not found","RUNNER_NOT_FOUND");let workspaceRoot=scopePaths[0]??process.cwd(),runId=`swarm-${crypto4.randomUUID?.()??Date.now()}`,policy=buildDefaultPolicy(workspaceRoot,runId);if(tempDir)policy.temp_root=tempDir;if(policy.workspace_roots=scopePaths.length>0?scopePaths:[workspaceRoot],policy.writable_roots=policyOverride?.writable_roots&&policyOverride.writable_roots.length>0?[...policyOverride.writable_roots]:policy.workspace_roots,policy.network_mode=policyOverride?.network_mode??policy.network_mode,_envOverrides)for(let[key,value]of Object.entries(_envOverrides)){if(!isValidEnvKey(key))continue;if(typeof value==="string")policy.env_overrides[key]=value;else policy.env_unsets.push(key),policy.env_allowlist=policy.env_allowlist.filter((allowed)=>allowed.toUpperCase()!==key.toUpperCase())}let policyJson=JSON.stringify(policy),policyDir=path45.join(os13.tmpdir(),"swarm-sandbox-policies");try{fs26.mkdirSync(policyDir,{recursive:!0})}catch{}let policyFile=path45.join(policyDir,`${runId}.json`);fs26.writeFileSync(policyFile,policyJson,"utf-8");let mode=this._probeResult.mode==="none"?"auto":this._probeResult.mode,escapedBinary=binary.includes(" ")?`"${binary}"`:binary,escapedPolicyFile=policyFile.includes(" ")?`"${policyFile}"`:policyFile,escapedCommand=command.replace(/"/g,"\\\"");return`cmd /c "type ${escapedPolicyFile} | ${escapedBinary} --policy-stdin --mode ${mode} -- ${escapedCommand} & del ${escapedPolicyFile} 2>nul"`}getEnvOverrides(){if(this._strength==="strong")return{PATH:null,TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null};return this._fallbackExecutor.getEnvOverrides()}async executeNative(command,workspaceRoot,runId){if(this._strength!=="strong")throw new SandboxError("Native execution requires strong sandbox (runner binary)","NATIVE_UNAVAILABLE");let policy=buildDefaultPolicy(workspaceRoot,runId);return execute(command,policy)}get hasNativeRunner(){return this._strength==="strong"}get disabledReason(){return this._disabledReason}get probeResult(){return this._probeResult}}var init_native_sandbox_executor=__esm(()=>{init_path_identity();init_logger();init_executor();init_restricted_environment_executor();init_runner_client()});var exports_windows={};__export(exports_windows,{WindowsSandboxExecutor:()=>NativeWindowsSandboxExecutor,LegacyWindowsSandboxExecutor:()=>WindowsSandboxExecutor});var init_windows=__esm(()=>{init_native_sandbox_executor();init_restricted_environment_executor()});function normalizeSandboxMechanism(mechanism){return mechanism.toLowerCase().replace(/[^a-z0-9]+/g,"")}function isValidEnvKey(key){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)}function isUntrustedEnvKey(key){let upper=key.toUpperCase();for(let prefix of UNTRUSTED_ENV_KEY_PREFIXES)if(upper.startsWith(prefix))return!0;return!1}function detectSandboxCapability(){return new SandboxCapabilityProbe().detect()}function normalizeSandboxRequirements(requirements){return{mode:requirements?.mode??"advisory",require_filesystem:requirements?.require_filesystem??!1,require_network:requirements?.require_network??!1,require_process:requirements?.require_process??!1,network_mode:requirements?.network_mode??"off",network_allowlist:[...requirements?.network_allowlist??[]],writable_roots:[...requirements?.writable_roots??[]]}}function normalizeSandboxPolicy(requirements){return{network_mode:requirements.network_mode,network_allowlist:[...requirements.network_allowlist],writable_roots:[...requirements.writable_roots]}}function hashList(values){return values.map((value)=>value.trim()).filter((value)=>value.length>0).sort((a,b)=>a.localeCompare(b)).join("\x1F")}function buildSandboxAssessmentCacheKey(capability,requirements,policy){return[capability.identity,requirements.mode,`fs=${requirements.require_filesystem?1:0}`,`net=${requirements.require_network?1:0}`,`proc=${requirements.require_process?1:0}`,`netmode=${policy.network_mode}`,`allowlist=${hashList(policy.network_allowlist)}`,`roots=${hashList(policy.writable_roots)}`].join("|")}function evaluatePolicySupport(capability,policy){let unsupported=[];if(policy.network_allowlist.length>0)unsupported.push("network_allowlist");let mechanism=normalizeSandboxMechanism(capability.mechanism);if(policy.network_mode==="off"&&(capability.platform==="darwin"||mechanism==="powershellwrapper"))unsupported.push("network_mode");return{supported:unsupported.length===0,unsupported}}function pruneSandboxAssessmentCache(){while(_sandboxAssessmentCache.size>MAX_SANDBOX_ASSESSMENT_CACHE){let oldestKey=_sandboxAssessmentCache.keys().next().value;if(oldestKey===void 0)return;_sandboxAssessmentCache.delete(oldestKey)}}async function assessSandboxEnforcement(requirements){let capability=await _internals42.detectSandboxCapability(),normalized=normalizeSandboxRequirements(requirements),policy=normalizeSandboxPolicy(normalized),cacheKey=buildSandboxAssessmentCacheKey(capability,normalized,policy),cached2=_sandboxAssessmentCache.get(cacheKey);if(cached2)return cached2;let assessmentPromise=Promise.resolve().then(()=>{let support=evaluatePolicySupport(capability,policy),assessment=assessSandboxRequirements(capability,normalized);return{capability,requirements:normalized,policy,satisfied:support.supported&&assessment.satisfied,missing:assessment.missing,supported:support.supported,unsupported:support.unsupported,cacheKey}});return _sandboxAssessmentCache.set(cacheKey,assessmentPromise),pruneSandboxAssessmentCache(),assessmentPromise}async function getExecutor(){if(_cachedExecutorPromise!==void 0)return _cachedExecutorPromise;return _cachedExecutorPromise=_createExecutor(),_cachedExecutorPromise}async function _createExecutor(){let platform=process.platform;if(platform==="linux")return _createLinuxExecutor();if(platform==="darwin")return _createMacOSExecutor();if(platform==="win32")return _createWindowsExecutor();return null}async function _createLinuxExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isBubblewrapAvailable:isBubblewrapAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isBubblewrapAvailable2())return null;try{let{BubblewrapSandboxExecutor:BubblewrapSandboxExecutor2}=(init_bubblewrap(),__toCommonJS(exports_bubblewrap));return new BubblewrapSandboxExecutor2([])}catch{return null}}function setMacOSSandboxPolicy(enabled){_macosSandboxEnabled=enabled}async function _createMacOSExecutor(){if(!_macosSandboxEnabled){if(!_hasWarnedMacOSSandboxDisabledByConfig)_hasWarnedMacOSSandboxDisabledByConfig=!0,warn("[sandbox] macOS sandbox-exec is disabled by config (guardrails.sandbox_macos_enabled=false). "+"Enable it only after verifying the production SBPL profile on a real macOS host — see docs/configuration.md.");return null}let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isSandboxExecAvailable:isSandboxExecAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isSandboxExecAvailable2())return null;try{let{MacOSSandboxExecutor:MacOSSandboxExecutor2}=(init_macos(),__toCommonJS(exports_macos));return new MacOSSandboxExecutor2([])}catch{return null}}async function _createWindowsExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isWindowsSandboxAvailable:isWindowsSandboxAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isWindowsSandboxAvailable2())return null;try{let{WindowsSandboxExecutor:WindowsSandboxExecutor2}=(init_windows(),__toCommonJS(exports_windows));return new WindowsSandboxExecutor2([])}catch{return null}}var SandboxError,UNTRUSTED_ENV_KEY_PREFIXES,_cachedExecutorPromise,MAX_SANDBOX_ASSESSMENT_CACHE=8,_sandboxAssessmentCache,_internals42,_macosSandboxEnabled=!1,_hasWarnedMacOSSandboxDisabledByConfig=!1;var init_executor=__esm(()=>{init_logger();init_capability_probe();SandboxError=class SandboxError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="SandboxError"}};UNTRUSTED_ENV_KEY_PREFIXES=["GIT_","LD_","DYLD_"];_sandboxAssessmentCache=new Map;_internals42={detectSandboxCapability}});var COUNCIL_MEMBER_ROLES,COUNCIL_DEFAULTS;var init_types=__esm(()=>{COUNCIL_MEMBER_ROLES=["critic","reviewer","sme","test_engineer","explorer"],COUNCIL_DEFAULTS={enabled:!1,maxRounds:3,parallelTimeoutMs:30000,vetoPriority:!0,requireAllMembers:!1,minimumMembers:3,phaseConcernsAllowComplete:!0,finalCompletionPolicy:{mode:"all_required"},freshnessMaxAgeHours:24}});import{createHash as createHash21}from"node:crypto";function isIdentityDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function resolveCouncilMemberRole(agentName){let resolved=getCanonicalAgentRole(agentName);return COUNCIL_MEMBER_ROLES.includes(resolved)?resolved:null}function computeCouncilReviewHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,type:phase.type,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,fr_refs:task.fr_refs?[...task.fr_refs].sort():void 0}))}))};return createHash21("sha256").update(JSON.stringify(normalized),"utf8").digest("hex")}function computeCouncilPolicyDigest(level,config2){let base={maxRounds:config2?.maxRounds??3,vetoPriority:config2?.vetoPriority??!0,freshnessMaxAgeHours:config2?.freshnessMaxAgeHours??24},normalized;if(level==="final")normalized={...base,finalCompletionPolicy:resolveFinalCompletionPolicy(config2)};else if(level==="phase")normalized={...base,requireAllMembers:config2?.requireAllMembers??!1,minimumMembers:config2?.minimumMembers??3,phaseConcernsAllowComplete:config2?.phaseConcernsAllowComplete??!0};else normalized={...base,requireAllMembers:config2?.requireAllMembers??!1,minimumMembers:config2?.minimumMembers??3};return createHash21("sha256").update(JSON.stringify(normalized),"utf8").digest("hex")}function resolveFinalCompletionPolicy(config2){let policy=config2?.finalCompletionPolicy;if(!policy||policy.mode!=="quorum")return{mode:"all_required"};let minimum=policy.minimumMembers;if(typeof minimum==="number"&&Number.isInteger(minimum)&&minimum>=3&&minimum<=5)return{mode:"quorum",minimumMembers:minimum};return{mode:"all_required"}}function computeCouncilReviewIdentity(input){let identity={version:COUNCIL_REVIEW_IDENTITY_VERSION,level:input.level,scope:input.scope,planId:input.plan?derivePlanId(input.plan):null,planIdentityHash:input.plan?derivePlanIdentityHash(input.plan):null,reviewHash:input.plan?computeCouncilReviewHash(input.plan):null,policyDigest:computeCouncilPolicyDigest(input.level,input.config)};return{...identity,identityDigest:createHash21("sha256").update(JSON.stringify(identity),"utf8").digest("hex")}}function councilIdentityEvidenceFields(identity){return{identity_version:identity.version,review_hash:identity.reviewHash,policy_digest:identity.policyDigest,identity_digest:identity.identityDigest}}var COUNCIL_REVIEW_IDENTITY_VERSION=2,DIGEST_PATTERN;var init_council_review_identity=__esm(()=>{init_schema();init_planning_profile();init_utils3();init_types();DIGEST_PATTERN=/^[a-f0-9]{64}$/});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash22}from"node:crypto";function hashString(value){return createHash22("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired2(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired2(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired2(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired2(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import*as fsSync5 from"node:fs";import*as path46 from"node:path";function dcNormalizeCommand(cmd){let s=cmd.normalize("NFKC");return s=s.replace(/`(.)/g,"$1"),s=s.replace(/\^([a-zA-Z0-9 ])/g,"$1"),s=s.replace(/""/g,""),s=s.replace(/''/g,""),s}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=/^cmd(?:\.exe)?\s+\/[ckCK]\s+"?(.*?)"?\s*$/is.exec(t);if(cmdExeMatch)return cmdExeMatch[1].trim();let psCommandMatch=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-(?:Command|command|c)\s+)(.+)$/is.exec(t);if(psCommandMatch)return psCommandMatch[1].replace(/^["']|["']$/g,"").trim();let psEncMatch=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-(?:EncodedCommand|encodedcommand|enc|e)\s+)([A-Za-z0-9+/=]+)\s*$/.exec(t);if(psEncMatch)try{return Buffer.from(psEncMatch[1],"base64").toString("utf16le").trim()}catch{return t}let shellMatch=/^(?:bash|sh|zsh|dash|fish)(?:\.exe)?\s+-c\s+"?(.*?)"?\s*$/is.exec(t);if(shellMatch)return shellMatch[1].trim();let evalMatch=/^eval\s+(.+)$/is.exec(t);if(evalMatch)return evalMatch[1].replace(/^["']|["']$/g,"").trim();let prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??/^env(?:\s+[A-Za-z_][A-Za-z0-9_]*=[^\s]*)*\s+(.+)$/is.exec(t)??/^nice\s+(?:-n\s+\d+\s+)?(.+)$/is.exec(t);if(prefixMatch)return prefixMatch[1].trim();let wslMatch=/^wsl(?:\.exe)?\s+(?:-e|--)\s+(.+)$/is.exec(t);if(wslMatch)return wslMatch[1].trim();let scriptBlockMatch=/^&\s*\{(.+)\}$/s.exec(t);if(scriptBlockMatch)return scriptBlockMatch[1].trim();let iexMatch=/^(?:Invoke-Expression|iex)\s+(.+)$/is.exec(t);if(iexMatch)return iexMatch[1].replace(/^["'`]|["'`]$/g,"").trim();let invokeCommandMatch=/^Invoke-Command\s+.*-ScriptBlock\s*\{(.+)\}$/is.exec(t);if(invokeCommandMatch)return invokeCommandMatch[1].trim();let callMatch=/^call\s+(.+)$/is.exec(t);if(callMatch)return callMatch[1].trim();return null}function dcUnwrapWrappers(cmd){let current=cmd.trim();for(let depth=0;depth<DC_MAX_UNWRAP_DEPTH;depth++){let inner=dcStripOneWrapper(current);if(inner===null||inner===current)break;current=inner.trim()}return current}function dcSplitSegments(cmd){let segments=[],current="",inDoubleQuote=!1,inSingleQuote=!1;for(let i=0;i<cmd.length;i++){let ch=cmd[i],next=cmd[i+1];if(ch==='"'&&!inSingleQuote){inDoubleQuote=!inDoubleQuote,current+=ch;continue}if(ch==="'"&&!inDoubleQuote){inSingleQuote=!inSingleQuote,current+=ch;continue}if(!inDoubleQuote&&!inSingleQuote){if(ch==="&"&&next==="&"||ch==="|"&&next==="|"){segments.push(current.trim()),current="",i++;continue}if(ch==="|"||ch===";"||ch===`
|
|
700
|
-
`||ch==="\r"){segments.push(current.trim()),current="";continue}if(ch==="&"&&next!=="&"){if(!(cmd[i-1]===">"||next===">")){segments.push(current.trim()),current="";continue}}}current+=ch}if(current.trim())segments.push(current.trim());return segments.filter((s)=>s.length>0)}function dcExtractRecursiveRmTargets(segment){let tokens=segment.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/g)??[];if(tokens.length<2||tokens[0]!=="rm")return null;let destructive=!1,index=1;for(;index<tokens.length;index++){let token=tokens[index];if(token==="--"){index++;break}if(!token.startsWith("-")||token==="-")break;if(token==="--recursive"||token==="--force")destructive=!0;if(!token.startsWith("--")&&/[rRfF]/.test(token.slice(1)))destructive=!0}if(!destructive)return null;return tokens.slice(index).map((target)=>target.replace(/^(["'])|(["'])$/g,""))}function dcHasUnresolvableVars(p){return/(%[A-Za-z_][A-Za-z0-9_]*%|\$\{?[A-Za-z_]|\$env:)/i.test(p)}function dcIsRemotePath(p){return DC_REMOTE_PREFIXES.some((pfx)=>p.startsWith(pfx))}function dcLstatAncestorWalk(targetPath,cwd){let normalizedTarget=path46.resolve(cwd,targetPath),normalizedCwd=path46.resolve(cwd),ancestors=[],current=normalizedTarget;while(!0){let rel=path46.relative(normalizedCwd,current);if(rel===".."||rel.startsWith(`..${path46.sep}`)||path46.isAbsolute(rel))break;if(ancestors.push(current),rel==="")break;let parent=path46.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat7=null;try{stat7=fsSync5.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`lstat failed on "${ancestor}": ${String(err)} — refusing to allow destructive operation on unverifiable path`}if(stat7.isSymbolicLink())return`BLOCKED: "${ancestor}" is a symlink/junction — deleting recursively through it would destroy the link target. Use platform-specific junction deletion (fsutil reparsepoint delete, Remove-Item without -Recurse) instead.`}return null}function dcValidateTargets(targets,cwd){for(let raw of targets){let t=raw.trim().replace(/^["']|["']$/g,"");if(!t||t===".")continue;if(dcHasUnresolvableVars(t))return`BLOCKED: Destructive command targets path with unexpanded variable "${t}" — cannot verify safety. Resolve variables before using destructive operations.`;if(dcIsRemotePath(t))return`BLOCKED: Destructive command targets remote/network filesystem path "${t}" — refusing to execute remote destructive operations.`;if(/^\\\\/.test(t))return`BLOCKED: Destructive command targets UNC path "${t}" — UNC paths in destructive operations are not allowed.`;let filesystemTarget=t.replace(/[\\/]+/g,path46.sep),lstatBlock=dcLstatAncestorWalk(filesystemTarget,cwd);if(lstatBlock)return lstatBlock;let basename10=path46.basename(filesystemTarget);if(dcPathComponents(t).length===1&&DC_SAFE_TARGETS.has(basename10))continue;if(DC_FS_ROOTS.has(t)||DC_FS_ROOTS.has(t.replace(/\//g,"\\")))return`BLOCKED: Destructive command targets filesystem root "${t}"`;if(path46.isAbsolute(t)||/^[A-Za-z]:/.test(t)){for(let blocked of DC_BLOCKED_ABSOLUTE_PREFIXES)if(t.startsWith(blocked))return`BLOCKED: Destructive command targets system path "${t}" which is under protected prefix "${blocked}"`}}return null}function dcIsUntrustedCodePoint(codePoint){return codePoint<=31||codePoint>=127&&codePoint<=159||codePoint>=8234&&codePoint<=8238||codePoint>=8294&&codePoint<=8297}function dcHasUntrustedText(value){return Array.from(value).some((character)=>dcIsUntrustedCodePoint(character.codePointAt(0)??0))}function dcSafeDiagnosticValue(value){return value.split("").map((character)=>dcIsUntrustedCodePoint(character.codePointAt(0)??0)?"?":character).join("").slice(0,512)}function dcPathComponents(value){return value.replace(/\\/g,"/").split("/").filter(Boolean)}function dcComponentEquals(left,right){return process.platform==="win32"?left.toLowerCase()===right.toLowerCase():left===right}function dcScopeContains(scopeEntry,target){let normalize7=(value)=>{let normalized=path46.posix.normalize(value.replace(/\\/g,"/")).replace(/^\.\//,"").replace(/\/$/,"");return process.platform==="win32"?normalized.toLowerCase():normalized},scope=normalize7(scopeEntry),candidate=normalize7(target);return candidate===scope||candidate.startsWith(`${scope}/`)}function dcEvaluateRecursiveDeleteTargets(input){if(input.targets.length===0)return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:"BLOCKED: Recursive delete has no statically verifiable target."};let commonBlock=dcValidateTargets(input.targets,input.cwd);if(commonBlock)return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:commonBlock};let normalizedTargets=[],hasNested=!1;for(let raw of input.targets){let target=raw.trim().replace(/^['"]|['"]$/g,""),safeTarget=dcSafeDiagnosticValue(target);if(!target||target==="."||dcHasUntrustedText(target)||dcPathComponents(target).includes(".."))return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:`BLOCKED: Recursive delete target "${safeTarget}" is empty, the workspace root, contains traversal, or contains control characters.`};let components=dcPathComponents(target);if(components.some((component)=>dcComponentEquals(component,".git")||dcComponentEquals(component,".swarm")))return{allowed:!1,code:"DESTRUCTIVE_TARGET_PROTECTED",reason:`BLOCKED: Recursive delete target "${safeTarget}" contains protected .git or .swarm state.`};let filesystemTarget=target.replace(/[\\/]+/g,path46.sep),resolved=path46.resolve(input.cwd,filesystemTarget),relative9=path46.relative(path46.resolve(input.cwd),resolved);if(relative9===""||relative9===".."||relative9.startsWith(`..${path46.sep}`)||path46.isAbsolute(relative9))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUTSIDE_WORKSPACE",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not strictly contained by the workspace.`};let basename10=path46.basename(resolved);if(!DC_SAFE_TARGETS.has(basename10))return{allowed:!1,code:"DESTRUCTIVE_TARGET_NOT_SAFE_ARTIFACT",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not an allowlisted build/cache artifact.`};let normalizedRelative=relative9.replace(/\\/g,"/");if(components.length!==1){if(hasNested=!0,!input.verifiedScope?.bindingId||!input.verifiedScope.generationId)return{allowed:!1,code:"DESTRUCTIVE_TARGET_SCOPE_REQUIRED",reason:`BLOCKED: Nested safe artifact "${safeTarget}" requires a verified active coder scope binding.`};if(!input.verifiedScope.files.some((entry)=>dcScopeContains(entry,normalizedRelative)))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUT_OF_SCOPE",reason:`BLOCKED: Nested safe artifact "${safeTarget}" is outside the verified active coder scope.`}}normalizedTargets.push(normalizedRelative)}return{allowed:!0,kind:hasNested?"scoped-nested-safe-artifact":"bare-safe-artifact",targets:normalizedTargets}}function dcCheckJunctionCreation(segment,cwd){let mklinkMatch=/^mklink(?:\.exe)?\s+\/[JjDd]\s+"?([^"\s]+)"?\s+"?([^"\s]+)"?/i.exec(segment);if(mklinkMatch){let target=mklinkMatch[2].trim();if(!dcHasUnresolvableVars(target)){let resolved=path46.resolve(cwd,target),rel=path46.relative(cwd,resolved);if(rel.startsWith("..")||path46.isAbsolute(rel))return`BLOCKED: Junction/symlink creation targeting path outside working directory: mklink target "${target}" resolves to "${resolved}" which is outside "${cwd}". Creating junctions to external paths and then deleting them recursively can destroy data.`}return null}let newItemTypeMatch=/New-Item\b.*-ItemType\s+(?:Junction|SymbolicLink|HardLink)\b/i.test(segment),newItemTargetMatch=/-Target\s+"?([^"\s;]+)"?/i.exec(segment),newItemMatch=newItemTypeMatch?newItemTargetMatch:null;if(newItemMatch){let target=newItemMatch[1].trim();if(!dcHasUnresolvableVars(target)){let resolved=path46.resolve(cwd,target),rel=path46.relative(cwd,resolved);if(rel.startsWith("..")||path46.isAbsolute(rel))return`BLOCKED: Junction/symlink creation targeting path outside working directory: New-Item target "${target}" resolves to "${resolved}" which is outside "${cwd}". This pattern caused the K2.6 data-loss incident.`}return null}let lnMatch=/^ln\s+(?:-[sfnv]*s[sfnv]*|-s)\s+"?([^"\s]+)"?(?:\s+"?[^"\s]+"?)?\s*$/.exec(segment);if(lnMatch){let target=lnMatch[1].trim();if(!dcHasUnresolvableVars(target)){let resolved=path46.resolve(cwd,target),rel=path46.relative(cwd,resolved);if(rel.startsWith("..")||path46.isAbsolute(rel))return`BLOCKED: Symlink creation targeting path outside working directory: ln -s target "${target}" resolves to "${resolved}" which is outside "${cwd}". Symlinks to external paths combined with recursive deletion can destroy data.`}return null}return null}function dcExtractWindowsCmdTargets(segment){let rmdirMatch=/^(?:rmdir|rd)(?:\.exe)?\s+(?:\/[sqSQ]\s+)*"?(.+?)"?\s*$/i.exec(segment);if(rmdirMatch)return[rmdirMatch[1].trim()];let delMatch=/^del(?:\.exe)?\s+(?:\/[sqfSQF]\s+)*"?(.+?)"?\s*$/i.exec(segment);if(delMatch)return[delMatch[1].trim()];return[]}function dcExtractPowerShellTargets(segment){let verbMatch=/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\s+/i.exec(segment);if(!verbMatch)return[];let tokens=segment.slice(verbMatch[0].length).match(/"[^"]*"|'[^']*'|[^\s]+/g)??[],targets=[],valueFlags=new Set(["-literalpath","-path","-filter","-include","-exclude","-lp"]),skipNext=!1;for(let tok of tokens){if(skipNext){skipNext=!1;continue}if(tok.startsWith("-")){if(valueFlags.has(tok.toLowerCase())){skipNext=!0;let idx=tokens.indexOf(tok);if(idx!==-1&&idx+1<tokens.length){let val=tokens[idx+1].replace(/^["']|["']$/g,"");if(val)targets.push(val);skipNext=!0}}}else{let cleaned=tok.replace(/^["']|["']$/g,"");if(cleaned)targets.push(cleaned)}}return targets}var DC_MAX_UNWRAP_DEPTH=5,DC_SAFE_TARGETS,DC_BLOCKED_ABSOLUTE_PREFIXES,DC_FS_ROOTS,DC_REMOTE_PREFIXES;var init_destructive_command=__esm(()=>{DC_SAFE_TARGETS=new Set(["node_modules","dist","build","coverage",".next",".turbo",".cache",".venv","venv","__pycache__","target","out",".parcel-cache",".svelte-kit",".nuxt",".output",".angular",".gradle","vendor"]),DC_BLOCKED_ABSOLUTE_PREFIXES=["/root","/home","/Users","/etc","/var","/usr","/opt","/bin","/sbin","/lib","/boot","/proc","/sys","/dev","/run","/System","/Library","/Applications","C:\\Windows","C:\\Users","C:\\Program Files","C:\\ProgramData","C:/Windows","C:/Users","C:/Program Files","C:/ProgramData"],DC_FS_ROOTS=new Set(["/","C:\\","C:/","D:\\","D:/","E:\\","E:/"]),DC_REMOTE_PREFIXES=["\\\\","/Volumes/","/net/","/nfs/","/smb/","/run/user/"]});import{createHash as createHash23}from"node:crypto";function digest2(value){return createHash23("sha256").update(value).digest("hex")}function hasAmbiguousSyntax(value){let single=!1,double=!1,escaped=!1;for(let character of value){if(escaped){escaped=!1;continue}if(character==="\\"){escaped=!0;continue}if(character==="'"&&!double)single=!single;if(character==='"'&&!single)double=!double}return single||double||escaped||/<<[-]?\s*\w+/.test(value)||/\$\(|`|\$\{?|\$IFS\b/i.test(value)}function matchRule(rules,segment){for(let rule of rules)if(rule.pattern.test(segment))return rule;return null}function classifySegment(segment,ambiguous){let bounded=segment.slice(0,MAX_EVIDENCE_CHARS),catastrophic=matchRule(CATASTROPHIC,segment);if(catastrophic)return{segment:bounded,category:"catastrophic",reason:catastrophic.reason??catastrophic.pattern.source,ruleId:catastrophic.id};let destructive=matchRule(DESTRUCTIVE,segment);if(destructive)return{segment:bounded,category:"destructive",reason:destructive.reason??destructive.pattern.source,ruleId:destructive.id};if(ambiguous||/[<>]|\|\s*(?:sh|bash|zsh|fish|pwsh|powershell|cmd)\b/i.test(segment))return{segment:bounded,category:"unknown",reason:"ambiguous shell syntax"};let escalate=matchRule(ESCALATE,segment);if(escalate)return{segment:bounded,category:"escalate",reason:escalate.reason??escalate.pattern.source,ruleId:escalate.id};let safe=matchRule(SAFE,segment);if(safe)return{segment:bounded,category:"safe",reason:safe.reason??safe.pattern.source,ruleId:safe.id};return{segment:bounded,category:"unknown",reason:"command is not in the bounded classifier corpus"}}function getSharedClassifierGuardrailBlock(classification){if(classification.aggregate!=="catastrophic"&&classification.aggregate!=="destructive")return null;for(let segment of classification.segments){if(segment.category!==classification.aggregate||typeof segment.ruleId!=="string")continue;let rule=BLOCK_RULES_BY_ID.get(segment.ruleId);if(!rule?.liveGuardrail||rule.liveGuardrail.mode!=="immediate-block")continue;return Object.freeze({ruleId:rule.id,category:classification.aggregate,destructiveCategory:rule.liveGuardrail.destructiveCategory,message:rule.liveGuardrail.message})}return null}function classifyCommand(original){let originalDigest=digest2(typeof original==="string"?original:String(original));if(typeof original!=="string"||original.length===0)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});if(Buffer.byteLength(original,"utf8")>MAX_COMMAND_BYTES)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});let normalized=dcNormalizeCommand(original),unwrapped=dcUnwrapWrappers(normalized),candidates=[...new Set([normalized,unwrapped,...dcSplitSegments(normalized),...dcSplitSegments(unwrapped),...dcSplitSegments(normalized).map(dcUnwrapWrappers)])];if(candidates.length===0||candidates.length>MAX_SEGMENTS)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});let ambiguous=hasAmbiguousSyntax(normalized),segments=candidates.map((segment)=>classifySegment(segment.trim(),ambiguous)),aggregate=segments.reduce((highest,current)=>SEVERITY[current.category]>SEVERITY[highest]?current.category:highest,"safe"),frozenSegments=Object.freeze(segments.map((segment)=>Object.freeze(segment)));return Object.freeze({v:1,originalDigest,aggregate,ambiguous,segments:frozenSegments})}var MAX_COMMAND_BYTES=65536,MAX_SEGMENTS=128,MAX_EVIDENCE_CHARS=512,SEVERITY,CATASTROPHIC,DESTRUCTIVE,ESCALATE,SAFE,BLOCK_RULES_BY_ID;var init_command_classifier=__esm(()=>{init_destructive_command();SEVERITY={safe:0,escalate:1,unknown:2,destructive:3,catastrophic:4},CATASTROPHIC=[{id:"fork-bomb",pattern:/:\s*\(\s*\)\s*\{[^}]*\|[^}]*:/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"fork bomb",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"power-control",pattern:/\b(?:shutdown|reboot|halt|poweroff)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"system shutdown",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"mkfs-suffixed",pattern:/\bmkfs[./]/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"diskpart",pattern:/^diskpart(?:\.exe)?$/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"format-drive",pattern:/^format\s+[A-Za-z]:/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"vssadmin-delete",pattern:/^vssadmin(?:\.exe)?\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"wbadmin-delete",pattern:/^wbadmin(?:\.exe)?\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"bcdedit-delete",pattern:/^bcdedit(?:\.exe)?\s+\/delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"boot configuration delete",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"dd-data-wipe",pattern:/\bdd\b[^\n]*(?:of=\s*(?:\/dev\/|[A-Za-z]:)|if=\s*\/dev\/(?:zero|random|urandom))/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "dd" with destructive data-wipe parameters detected by the shared command classifier; critic approval cannot waive this policy'}},{id:"git-push-force",pattern:/\bgit\s+push\b[^\n]*(?:--force(?!-with-lease)|\s-f\b)/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"force push",message:"BLOCKED: Force push detected — git push --force is not allowed (use --force-with-lease instead)"}},{id:"curl-pipe-shell",pattern:/\b(?:curl|wget)\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"script pipe execution",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}}],DESTRUCTIVE=[{id:"git-reset-hard",pattern:/\bgit\s+(?:-C\s+\S+\s+)?reset\s+--hard\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git reset",message:'BLOCKED: "git reset --hard" detected — use --soft or --mixed with caution'}},{id:"git-reset-mixed-target",pattern:/\bgit\s+(?:-C\s+\S+\s+)?reset\s+--mixed\s+\S+/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git reset",message:'BLOCKED: "git reset --mixed" with a target branch/commit is not allowed'}},{id:"git-clean-force",pattern:/\bgit\s+(?:-C\s+\S+\s+)?clean\s+-[^\s]*[fdx]/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git clean",message:'BLOCKED: "git clean -fd" detected — permanently deletes untracked files and directories'}},{id:"rm-recursive",pattern:/\brm\b[^\n]*(?:-[^\s]*[rf]|--recursive|--force)/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive delete",message:"target-aware recursive delete"}},{id:"windows-recursive-delete",pattern:/\b(?:rmdir|rd|del)(?:\.exe)?\b[^\n]*\/[sqf]/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive delete",message:"target-aware Windows recursive delete"}},{id:"powershell-recursive-delete",pattern:/\bRemove-Item\b[^\n]*(?:-Recurse|-Force)/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive remove",message:"target-aware PowerShell recursive delete"}},{id:"find-delete",pattern:/\bfind\b[^\n]*\s-delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"find delete",message:'BLOCKED: "find -delete" detected — dynamic delete expansion is not allowed from shell commands'}},{id:"rsync-delete",pattern:/\brsync\b[^\n]*--delete(?:-after|-before|-during|-delay)?\b/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"rsync delete",message:"target-aware rsync delete"}},{id:"docker-system-prune",pattern:/\bdocker\s+system\s+prune\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"docker prune",message:'BLOCKED: "docker system prune" detected — destructive container operation'}},{id:"kubectl-delete",pattern:/\bkubectl\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"kubectl delete",message:'BLOCKED: "kubectl delete" detected — destructive cluster operation'}},{id:"sql-drop",pattern:/\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"sql drop",message:"BLOCKED: SQL DROP command detected — destructive database operation"}},{id:"sql-truncate",pattern:/\bTRUNCATE\s+TABLE\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"sql truncate",message:"BLOCKED: SQL TRUNCATE command detected — destructive database operation"}},{id:"sed-config-rewrite",pattern:/\bsed\s+-i\b[^\n]*(?:biome\.json|oxlintrc|eslint)/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"config rewrite",message:"BLOCKED: in-place configuration rewrite detected — protected lint or policy config edit matched the shared command classifier"}},{id:"sdelete",pattern:/^sdelete(?:\.exe)?\s+/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"secure delete",message:'BLOCKED: "sdelete" detected — secure file deletion (Sysinternals)'}},{id:"fsutil-destructive",pattern:/^fsutil(?:\.exe)?\s+(?:reparsepoint\s+delete|file\s+setzerodata)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "fsutil" destructive subcommand detected'}},{id:"takeown-recursive",pattern:/^takeown(?:\.exe)?\s+.*\/[rR]\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"ownership takeover",message:'BLOCKED: "takeown /R" (recursive ownership takeover) detected — often precedes destructive operations'}},{id:"cipher-wipe",pattern:/^cipher(?:\.exe)?\s+\/[wW]\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "cipher /w" detected — overwrites free disk space (data wipe operation)'}},{id:"robocopy-mirror",pattern:/^robocopy(?:\.exe)?\s+.*\/(?:MIR|mir)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"mirror sync",message:'BLOCKED: "robocopy /MIR" (mirror) detected — can delete files in the destination that do not exist in the source'}},{id:"chmod-permission-wipe",pattern:/^chmod\s+.*-[rR]\b.*000\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"permission wipe",message:'BLOCKED: "chmod -R 000" detected — removes all permissions recursively'}},{id:"chattr-immutable",pattern:/^chattr\s+.*\+i\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"immutable flag",message:'BLOCKED: "chattr +i" detected — makes files immutable'}},{id:"icacls-deny",pattern:/^icacls(?:\.exe)?\s+.*\/deny\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"permission deny",message:'BLOCKED: "icacls /deny" detected — denies filesystem permissions'}}],ESCALATE=[{id:"sudo-network-permissions",pattern:/\b(?:sudo|chmod|chown|curl|wget|ssh|scp|sftp|nc|netcat)\b/i},{id:"dynamic-eval",pattern:/\b(?:eval|Invoke-Expression|iex)\b/i}],SAFE=[{id:"safe-readonly-shell",pattern:/^(?:cat|head|tail|file|stat|wc|sort|uniq|cut|grep|rg|ag|ls|pwd|whoami|hostname|uname|date|which|type|tree)\b/i},{id:"safe-readonly-git",pattern:/^git\s+(?:-C\s+\S+\s+)?(?:status|log|show|diff|branch|describe|rev-parse|rev-list|ls-files|remote\s+-v)\b/i},{id:"safe-shell-builtin",pattern:/^(?:true|false|test|echo|printf)\b/i},{id:"safe-package-scripts",pattern:/^(?:bun|npm|yarn|pnpm)\s+(?:run\s+(?:typecheck|lint|test|build)|test|typecheck|lint)\b/i}],BLOCK_RULES_BY_ID=new Map([...CATASTROPHIC,...DESTRUCTIVE].map((rule)=>[rule.id,rule]))});import*as path47 from"node:path";function normalizeProtectedPath(value){return value.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function equalsOrDescendant(candidate,protectedPath){let left=process.platform==="win32"?candidate.toLowerCase():candidate,right=process.platform==="win32"?protectedPath.toLowerCase():protectedPath;return left===right||left.startsWith(`${right}/`)}function isPolicyProtectedPath(filePath,options={}){if(!filePath)return!1;let normalized=normalizeProtectedPath(filePath),segments=normalized.split("/").filter(Boolean);if(options.includeDefaults!==!1){if(segments.some((segment)=>DEFAULT_SEGMENTS.has(process.platform==="win32"?segment.toLowerCase():segment)))return!0;if(DEFAULT_PREFIXES.some((prefix)=>equalsOrDescendant(normalized,prefix)))return!0}return(options.additional??[]).some((entry)=>{let protectedPath=normalizeProtectedPath(entry);if(!protectedPath)return!1;if(equalsOrDescendant(normalized,protectedPath))return!0;if(protectedPath.includes("/"))return!1;return segments.some((segment)=>(process.platform==="win32"?segment.toLowerCase():segment)===(process.platform==="win32"?protectedPath.toLowerCase():protectedPath))})}function protectedRoots(projectRoot,additional=[]){return[...DEFAULT_PREFIXES,...DEFAULT_SEGMENTS,...additional].map((entry)=>path47.resolve(projectRoot,entry))}var DEFAULT_SEGMENTS,DEFAULT_PREFIXES,DEFAULT_PROTECTED_PATH_PREFIXES;var init_protected_path_policy=__esm(()=>{DEFAULT_SEGMENTS=new Set([".git",".swarm",".env","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","CODEOWNERS"]),DEFAULT_PREFIXES=[".github/workflows",".github/CODEOWNERS","src/sandbox","src/hooks/guardrails","src/security","src/evaluation","docs/releases","tests/fixtures/evaluation"],DEFAULT_PROTECTED_PATH_PREFIXES=DEFAULT_PREFIXES});function normalizePath(p){if(!p)return"";let result=p.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\.\//,"").replace(/(?:^|\/)\.\//g,"/");if(result=result.replace(/\/$/,""),result=result.replace(/\/\.$/,""),process.platform==="win32")result=result.toLowerCase();if(!result){let norm=p.replace(/\\/g,"/");if(norm==="."||norm==="./")return".";return""}return result}import*as fs27 from"node:fs";import*as path48 from"node:path";function isReadOnlyTool(toolName){if(!toolName)return!1;return READ_ONLY_TOOLS.has(toolName.toLowerCase())}function isWriteLikeTool(toolName){if(!toolName)return!1;return WRITE_LIKE_TOOLS.has(toolName.toLowerCase())}function isSubagentDelegation(toolName,args2){let lower=toolName?.toLowerCase()??"";if(SUBAGENT_TOOLS.has(lower))return!0;if(lower==="task"&&args2&&typeof args2==="object")return!0;return!1}function isWithinDirectory(target,root){if(!target||!root)return!1;let resolvedTarget=path48.resolve(target),resolvedRoot=path48.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path48.sep)?resolvedRoot:resolvedRoot+path48.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}function isProtectedPath(filePath,config2){if(!filePath)return!1;let normalized=normalizePath(filePath);for(let prefix of ALWAYS_PROTECTED_PREFIXES){let np=normalizePath(prefix);if(normalized===np||normalized.startsWith(`${np}/`))return!0}let allowDefaults=config2?.permission_policy?.allow_defaults!==!1;return isPolicyProtectedPath(normalized,{includeDefaults:allowDefaults,additional:[...allowDefaults?PROTECTED_PATH_DEFAULTS:[],...config2?.permission_policy?.protected_paths??[]]})}function classifyPathRisk(filePath,context){if(!filePath)return{withinProjectRoot:!1,withinDeclaredScope:null,protected:!1,highRiskBuild:!1};let absolute=path48.isAbsolute(filePath)?filePath:path48.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs27.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs27.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path48.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative10=normalizePath(path48.relative(context.directory,absolute)),withinDeclaredScope=null;if(Array.isArray(context.declaredScope))withinDeclaredScope=context.declaredScope.length===0?!1:context.declaredScope.some((scope)=>{let s=normalizePath(scope);if(!s)return!1;return relative10===s||relative10.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative10.startsWith(e);return relative10===e||relative10.startsWith(`${e}/`)});return{withinProjectRoot,withinDeclaredScope,protected:!1,highRiskBuild}}function classifyCommandRisk(command,_cwd,_context){if(FULL_AUTO_SECRET_READ_PATTERN.test(command)||FULL_AUTO_SECRET_ENV_PATTERN.test(command)||FULL_AUTO_PRIMARY_PUSH_PATTERN.test(command))return{decision:"deny",reason:"full-auto consumer policy: command reads secrets or targets a primary branch push"};let classification=classifyCommand(command);if(classification.aggregate==="catastrophic"||classification.aggregate==="destructive")return{decision:"deny",reason:`shared classifier: ${classification.aggregate}`};if(classification.aggregate==="safe")return{decision:"allow",reason:"shared classifier: safe"};return{decision:"escalate_critic",reason:`shared classifier: ${classification.aggregate}`}}function extractPathArgs(toolName,args2){if(!args2||typeof args2!=="object")return[];let found=[];for(let key of PATH_ARG_KEYS){let v=args2[key];if(typeof v==="string"&&v.trim())found.push(v)}let filesArg=args2.files;if(Array.isArray(filesArg)){for(let f of filesArg)if(typeof f==="string"&&f.trim())found.push(f);else if(f&&typeof f==="object"&&typeof f.path==="string")found.push(f.path)}let editsArg=args2.edits;if(Array.isArray(editsArg)){for(let e of editsArg)if(e&&typeof e==="object"&&typeof e.file_path==="string")found.push(e.file_path)}if(toolName==="declare_scope"&&Array.isArray(args2.files));return found}function extractCommandArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.command==="string"&&args2.command||typeof args2.cmd==="string"&&args2.cmd||typeof args2.script==="string"&&args2.script||void 0}function extractURLArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.url==="string"&&args2.url||typeof args2.uri==="string"&&args2.uri||typeof args2.endpoint==="string"&&args2.endpoint||void 0}function isTrustedDomain(url2,config2){let domains=config2?.permission_policy?.trusted_domains??[];if(domains.length===0)return!1;let host="";try{host=new URL(url2).hostname.toLowerCase()}catch{return!1}return domains.some((d)=>{let dl=d.toLowerCase();return host===dl||host.endsWith(`.${dl}`)})}function resolveAgentCapabilityTools(roleName,pluginConfig){let tools=pluginConfig?.tool_filter?.overrides?.[roleName]??AGENT_TOOL_MAP[roleName]??[];if(pluginConfig?.memory?.enabled===!0)tools=Array.from(new Set([...tools,...MEMORY_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.external_skills?.curation_enabled===!0)tools=Array.from(new Set([...tools,...EXTERNAL_SKILL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.enabled===!0)tools=Array.from(new Set([...tools,...COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.general?.enabled===!0)tools=Array.from(new Set([...tools,...GENERAL_COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.turbo!==void 0)tools=Array.from(new Set([...tools,...TURBO_AGENT_TOOL_MAP[roleName]??[]]));let skillTools=SKILL_AGENT_TOOL_MAP[roleName]??[];if(skillTools.length>0)if(pluginConfig?.skills?.enabled===!0)tools=Array.from(new Set([...tools,...skillTools]));else{let skillSet=new Set(skillTools);tools=tools.filter((tool)=>!skillSet.has(tool))}if(pluginConfig?.skills?.enabled!==!0&&roleName!=="skill_improver"){let allSkillTools=new Set(SKILL_TOOL_NAMES);tools=tools.filter((tool)=>!allSkillTools.has(tool))}return tools}function resolveDelegationRisk(input,subagentName){let role=input.generatedAgentNames&&input.generatedAgentNames.length>0?resolveGeneratedAgentRole(subagentName,input.generatedAgentNames):getCanonicalAgentRole(subagentName);if(!isKnownCanonicalRole(role))return{risk:"high",reason:"subagent role is unknown or not registry-backed",role,tools:[],safeReadOnly:!1};let tools=resolveAgentCapabilityTools(role,input.pluginConfig);if(tools.length===0)return{risk:"high",reason:"subagent has no registered capability map",role,tools,safeReadOnly:!1};let dangerous=tools.some((tool)=>isWriteLikeTool(tool)||SHELL_TOOLS.has(tool)||NETWORK_TOOLS.has(tool)||tool==="swarm_command"||tool==="Task"||tool==="task"),unknown2=tools.some((tool)=>!isReadOnlyTool(tool)&&!isWriteLikeTool(tool)&&!SHELL_TOOLS.has(tool)&&!NETWORK_TOOLS.has(tool)&&tool!=="swarm_command");if(dangerous||unknown2)return{risk:"high",reason:dangerous?"delegated role can write, execute, publish, or recurse":"delegated role exposes non-read-only unknown capabilities",role,tools,safeReadOnly:!1};return{risk:"medium",reason:"delegated role is limited to registered read-only capabilities",role,tools,safeReadOnly:!0}}function classifyFullAutoToolAction(input){let tool=input.toolName?.toLowerCase()??"",config2=input.fullAutoConfig,mode=config2?.mode??"supervised";if(!(mode==="strict"||config2?.permission_policy?.enabled!==!1))return{action:"allow",reason:"permission policy disabled by config",tier:"local"};if(isReadOnlyTool(tool))return{action:"allow",reason:"read-only tool",tier:"safe"};if(isSubagentDelegation(tool,input.args)){let subagentName=typeof input.args?.subagent_type==="string"&&input.args.subagent_type||typeof input.args?.agent==="string"&&input.args.agent||"unknown",delegationRisk=resolveDelegationRisk(input,subagentName);if(mode!=="strict"&&delegationRisk.safeReadOnly)return{action:"allow",reason:`read-only subagent delegation allowed (${delegationRisk.role})`,tier:"local"};return{action:"escalate_critic",reason:`subagent delegation requires plan/scope verification (${delegationRisk.reason})`,risk:mode==="strict"?"high":delegationRisk.risk,context:{tool,subagent:subagentName,canonicalRole:delegationRisk.role,registeredTools:delegationRisk.tools,currentTaskID:input.currentTaskID,currentPhase:input.currentPhase}}}if(tool==="phase_complete")return{action:"escalate_critic",reason:"phase_complete requires Full-Auto approval evidence",risk:"high",context:{tool,currentPhase:input.currentPhase}};if(tool==="update_task_status"){let status=typeof input.args?.status==="string"&&input.args.status||"";if(status==="completed"){if(mode==="strict"||config2?.oversight?.on_task_completion===!0)return{action:"escalate_critic",reason:"task completion requires Full-Auto critic verification",risk:"medium",context:{tool,status}}}else{if(mode==="strict")return{action:"escalate_critic",reason:`strict mode: update_task_status with status=${status} requires critic verification`,risk:"medium",context:{tool,status}};return{action:"allow",reason:`update_task_status with status=${status} is a routine state change`,tier:"local"}}}if(tool==="save_plan")return{action:"escalate_critic",reason:"plan mutation requires Full-Auto critic verification",risk:"high",context:{tool}};if(NETWORK_TOOLS.has(tool)){let url2=extractURLArg(input.args);if(url2&&isTrustedDomain(url2,config2))return{action:"allow",reason:"network tool with trusted domain",tier:"local"};return{action:"escalate_critic",reason:"network/web tool — verify intent and target",risk:"medium",context:{tool,url:url2}}}if(SHELL_TOOLS.has(tool)){let command=extractCommandArg(input.args);if(!command)return{action:"deny",reason:"shell tool invoked without a command argument",code:"shell_no_command",recoverable:!0};let cmdRisk=classifyCommandRisk(command,input.workingDirectory??"",{directory:input.directory});if(cmdRisk.decision==="deny")return{action:"deny",reason:cmdRisk.reason,code:"shell_deny",recoverable:!0};if(cmdRisk.decision==="allow")return{action:"allow",reason:cmdRisk.reason,tier:"local"};return{action:"escalate_critic",reason:cmdRisk.reason,risk:"medium",context:{tool,command}}}if(isWriteLikeTool(tool)||tool==="patch"||tool==="edit"){let paths=extractPathArgs(tool,input.args);if(paths.length===0){if(new Set(["declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine"]).has(tool))return{action:"allow",reason:`pathless plan/evidence tool '${tool}' allowed under Full-Auto`,tier:"local"};return{action:"escalate_critic",reason:"write-like tool without explicit path — verify side effects",risk:"medium",context:{tool,args:input.args}}}for(let p of paths){let risk=classifyPathRisk(p,{directory:input.directory,declaredScope:input.declaredScope??null});if(!risk.withinProjectRoot)return{action:"deny",reason:`write target outside project root: ${p}`,code:"path_out_of_root",recoverable:!0};if(isProtectedPath(path48.relative(input.directory,path48.resolve(input.directory,p)),config2))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool}}}function buildStructuredDenial(decision,tool){return{full_auto_denial:!0,tool,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}var READ_ONLY_TOOLS,WRITE_LIKE_TOOLS,SHELL_TOOLS,NETWORK_TOOLS,SUBAGENT_TOOLS,HIGH_RISK_BUILD_PATHS,ALWAYS_PROTECTED_PREFIXES,PROTECTED_PATH_DEFAULTS,FULL_AUTO_SECRET_READ_PATTERN,FULL_AUTO_SECRET_ENV_PATTERN,FULL_AUTO_PRIMARY_PUSH_PATTERN,PATH_ARG_KEYS;var init_policy=__esm(()=>{init_constants();init_schema();init_command_classifier();init_protected_path_policy();READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine","suggest_patch"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","gitingest"]),SUBAGENT_TOOLS=new Set(["task","agent","delegate"]),HIGH_RISK_BUILD_PATHS=["src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto/","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"];FULL_AUTO_SECRET_READ_PATTERN=/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)\b/i,FULL_AUTO_SECRET_ENV_PATTERN=/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,FULL_AUTO_PRIMARY_PUSH_PATTERN=/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i;PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"]});async function withTimeout(promise2,ms,timeoutError){let timer,timeoutPromise=new Promise((_,reject)=>{timer=setTimeout(()=>reject(timeoutError),ms)});try{return await Promise.race([promise2,timeoutPromise])}finally{if(timer!==void 0)clearTimeout(timer)}}async function withTimeoutSignal(operation,ms,timeoutError){if(!Number.isFinite(ms)||ms<0)throw RangeError("timeout must be a finite non-negative number");if(timeoutError.name==="Error")try{timeoutError.name="TimeoutError"}catch{}let controller=new AbortController,timer,timeoutPromise=new Promise((_,reject)=>{timer=_internals43.setTimeout(()=>{controller.abort(timeoutError),reject(timeoutError)},ms)});try{return await Promise.race([Promise.resolve().then(()=>operation(controller.signal)),timeoutPromise])}finally{if(timer!==void 0)_internals43.clearTimeout(timer)}}function yieldToEventLoop(){return new Promise((resolve26)=>{setTimeout(resolve26,0)})}var _internals43;var init_timeout=__esm(()=>{_internals43={setTimeout,clearTimeout}});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals44});import{existsSync as existsSync26,statSync as statSync15}from"node:fs";import*as path49 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{Language,Parser as TreeSitterParser}from"web-tree-sitter";async function initTreeSitter(){if(!treeSitterInitPromise)treeSitterInitPromise=(async()=>{if(_internals44.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals44.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path49.join(grammarsDir,"tree-sitter.wasm");if(!_internals44.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
|
|
699
|
+
}`,encodedScript=Buffer2.from(psScript,"utf16le").toString("base64");return`& '${psSingleQuoteEscape(powerShellExe)}' -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ${encodedScript}; exit $LASTEXITCODE`}getEnvOverrides(){return{PATH:getSafeWindowsPath(),TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null}}}var SANDBOX_UNAVAILABLE_CODES2,DEFAULT_SYSTEM_ROOT="C:\\Windows",UNSAFE_PATH_CHARACTERS,_internals41;var init_restricted_environment_executor=__esm(()=>{init_logger();init_executor();SANDBOX_UNAVAILABLE_CODES2=new Set(["ENOENT","EACCES","EPERM","ENOSPC"]),UNSAFE_PATH_CHARACTERS=new Set([":",'"',"'",";","&","|","<",">","^","%","!","?","*","`","$"]);_internals41={probeWindowsSandbox}});import*as crypto4 from"node:crypto";import*as fs26 from"node:fs";import*as os13 from"node:os";import*as path45 from"node:path";class NativeWindowsSandboxExecutor{mechanism;_probeResult;_fallbackExecutor;_strength;_disabled;_disabledReason;constructor(scopePaths=[],tempDir){if(this._disabled=!1,this._disabledReason=null,this._fallbackExecutor=new WindowsSandboxExecutor(scopePaths,tempDir),this._probeResult=probe(),this._probeResult.available)this._strength="strong",this.mechanism=`native-runner/${this._probeResult.mode}`;else if(this._fallbackExecutor.isAvailable())this._strength="weak",this.mechanism="powershell-wrapper",criticalWarn(`[sandbox] native Windows sandbox runner unavailable (${sanitizeDiagnosticText(this._probeResult.error??"unknown",200)}); falling back to PowerShell environment restrictions (weak sandbox). Run /swarm diagnose for details.`);else this._strength="none",this.mechanism="none"}get strength(){if(this._disabled)return"none";return this._strength}isAvailable(){return!this._disabled&&this._strength!=="none"}disable(reason){this._disabled=!0,this._disabledReason=reason,criticalWarn(`[sandbox] Sandbox disabled: ${sanitizeDiagnosticText(reason,200)}. Falling through to tool-layer enforcement. Run /swarm diagnose for details.`)}wrapCommand(command,scopePaths,tempDir,envOverrides,policy){if(!this.isAvailable())throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");if(this._strength==="strong"){if(/["&|<>^%]/.test(command))return this._fallbackExecutor.wrapCommand(command,scopePaths,tempDir,envOverrides);return this._wrapWithRunner(command,scopePaths,tempDir,envOverrides,policy)}return this._fallbackExecutor.wrapCommand(command,scopePaths,tempDir,envOverrides)}_wrapWithRunner(command,scopePaths,tempDir,_envOverrides,policyOverride){let binary=_internals39.findRunnerBinary();if(!binary)throw new SandboxError("Runner binary not found","RUNNER_NOT_FOUND");let workspaceRoot=scopePaths[0]??process.cwd(),runId=`swarm-${crypto4.randomUUID?.()??Date.now()}`,policy=buildDefaultPolicy(workspaceRoot,runId);if(tempDir)policy.temp_root=tempDir;if(policy.workspace_roots=scopePaths.length>0?scopePaths:[workspaceRoot],policy.writable_roots=policyOverride?.writable_roots&&policyOverride.writable_roots.length>0?[...policyOverride.writable_roots]:policy.workspace_roots,policy.network_mode=policyOverride?.network_mode??policy.network_mode,_envOverrides)for(let[key,value]of Object.entries(_envOverrides)){if(!isValidEnvKey(key))continue;if(typeof value==="string")policy.env_overrides[key]=value;else policy.env_unsets.push(key),policy.env_allowlist=policy.env_allowlist.filter((allowed)=>allowed.toUpperCase()!==key.toUpperCase())}let policyJson=JSON.stringify(policy),policyDir=path45.join(os13.tmpdir(),"swarm-sandbox-policies");try{fs26.mkdirSync(policyDir,{recursive:!0})}catch{}let policyFile=path45.join(policyDir,`${runId}.json`);fs26.writeFileSync(policyFile,policyJson,"utf-8");let mode=this._probeResult.mode==="none"?"auto":this._probeResult.mode,escapedBinary=binary.includes(" ")?`"${binary}"`:binary,escapedPolicyFile=policyFile.includes(" ")?`"${policyFile}"`:policyFile,escapedCommand=command.replace(/"/g,"\\\"");return`cmd /c "type ${escapedPolicyFile} | ${escapedBinary} --policy-stdin --mode ${mode} -- ${escapedCommand} & del ${escapedPolicyFile} 2>nul"`}getEnvOverrides(){if(this._strength==="strong")return{PATH:null,TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null};return this._fallbackExecutor.getEnvOverrides()}async executeNative(command,workspaceRoot,runId){if(this._strength!=="strong")throw new SandboxError("Native execution requires strong sandbox (runner binary)","NATIVE_UNAVAILABLE");let policy=buildDefaultPolicy(workspaceRoot,runId);return execute(command,policy)}get hasNativeRunner(){return this._strength==="strong"}get disabledReason(){return this._disabledReason}get probeResult(){return this._probeResult}}var init_native_sandbox_executor=__esm(()=>{init_path_identity();init_logger();init_executor();init_restricted_environment_executor();init_runner_client()});var exports_windows={};__export(exports_windows,{WindowsSandboxExecutor:()=>NativeWindowsSandboxExecutor,LegacyWindowsSandboxExecutor:()=>WindowsSandboxExecutor});var init_windows=__esm(()=>{init_native_sandbox_executor();init_restricted_environment_executor()});function normalizeSandboxMechanism(mechanism){return mechanism.toLowerCase().replace(/[^a-z0-9]+/g,"")}function isValidEnvKey(key){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)}function isUntrustedEnvKey(key){let upper=key.toUpperCase();for(let prefix of UNTRUSTED_ENV_KEY_PREFIXES)if(upper.startsWith(prefix))return!0;return!1}function detectSandboxCapability(){return new SandboxCapabilityProbe().detect()}function normalizeSandboxRequirements(requirements){return{mode:requirements?.mode??"advisory",require_filesystem:requirements?.require_filesystem??!1,require_network:requirements?.require_network??!1,require_process:requirements?.require_process??!1,network_mode:requirements?.network_mode??"off",network_allowlist:[...requirements?.network_allowlist??[]],writable_roots:[...requirements?.writable_roots??[]]}}function normalizeSandboxPolicy(requirements){return{network_mode:requirements.network_mode,network_allowlist:[...requirements.network_allowlist],writable_roots:[...requirements.writable_roots]}}function hashList(values){return values.map((value)=>value.trim()).filter((value)=>value.length>0).sort((a,b)=>a.localeCompare(b)).join("\x1F")}function buildSandboxAssessmentCacheKey(capability,requirements,policy){return[capability.identity,requirements.mode,`fs=${requirements.require_filesystem?1:0}`,`net=${requirements.require_network?1:0}`,`proc=${requirements.require_process?1:0}`,`netmode=${policy.network_mode}`,`allowlist=${hashList(policy.network_allowlist)}`,`roots=${hashList(policy.writable_roots)}`].join("|")}function evaluatePolicySupport(capability,policy){let unsupported=[];if(policy.network_allowlist.length>0)unsupported.push("network_allowlist");let mechanism=normalizeSandboxMechanism(capability.mechanism);if(policy.network_mode==="off"&&(capability.platform==="darwin"||mechanism==="powershellwrapper"))unsupported.push("network_mode");return{supported:unsupported.length===0,unsupported}}function pruneSandboxAssessmentCache(){while(_sandboxAssessmentCache.size>MAX_SANDBOX_ASSESSMENT_CACHE){let oldestKey=_sandboxAssessmentCache.keys().next().value;if(oldestKey===void 0)return;_sandboxAssessmentCache.delete(oldestKey)}}async function assessSandboxEnforcement(requirements){let capability=await _internals42.detectSandboxCapability(),normalized=normalizeSandboxRequirements(requirements),policy=normalizeSandboxPolicy(normalized),cacheKey=buildSandboxAssessmentCacheKey(capability,normalized,policy),cached2=_sandboxAssessmentCache.get(cacheKey);if(cached2)return cached2;let assessmentPromise=Promise.resolve().then(()=>{let support=evaluatePolicySupport(capability,policy),assessment=assessSandboxRequirements(capability,normalized);return{capability,requirements:normalized,policy,satisfied:support.supported&&assessment.satisfied,missing:assessment.missing,supported:support.supported,unsupported:support.unsupported,cacheKey}});return _sandboxAssessmentCache.set(cacheKey,assessmentPromise),pruneSandboxAssessmentCache(),assessmentPromise}async function getExecutor(){if(_cachedExecutorPromise!==void 0)return _cachedExecutorPromise;return _cachedExecutorPromise=_createExecutor(),_cachedExecutorPromise}async function _createExecutor(){let platform=process.platform;if(platform==="linux")return _createLinuxExecutor();if(platform==="darwin")return _createMacOSExecutor();if(platform==="win32")return _createWindowsExecutor();return null}async function _createLinuxExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isBubblewrapAvailable:isBubblewrapAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isBubblewrapAvailable2())return null;try{let{BubblewrapSandboxExecutor:BubblewrapSandboxExecutor2}=(init_bubblewrap(),__toCommonJS(exports_bubblewrap));return new BubblewrapSandboxExecutor2([])}catch{return null}}function setMacOSSandboxPolicy(enabled){_macosSandboxEnabled=enabled}async function _createMacOSExecutor(){if(!_macosSandboxEnabled){if(!_hasWarnedMacOSSandboxDisabledByConfig)_hasWarnedMacOSSandboxDisabledByConfig=!0,warn("[sandbox] macOS sandbox-exec is disabled by config (guardrails.sandbox_macos_enabled=false). "+"Enable it only after verifying the production SBPL profile on a real macOS host — see docs/configuration.md.");return null}let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isSandboxExecAvailable:isSandboxExecAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isSandboxExecAvailable2())return null;try{let{MacOSSandboxExecutor:MacOSSandboxExecutor2}=(init_macos(),__toCommonJS(exports_macos));return new MacOSSandboxExecutor2([])}catch{return null}}async function _createWindowsExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isWindowsSandboxAvailable:isWindowsSandboxAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isWindowsSandboxAvailable2())return null;try{let{WindowsSandboxExecutor:WindowsSandboxExecutor2}=(init_windows(),__toCommonJS(exports_windows));return new WindowsSandboxExecutor2([])}catch{return null}}var SandboxError,UNTRUSTED_ENV_KEY_PREFIXES,_cachedExecutorPromise,MAX_SANDBOX_ASSESSMENT_CACHE=8,_sandboxAssessmentCache,_internals42,_macosSandboxEnabled=!1,_hasWarnedMacOSSandboxDisabledByConfig=!1;var init_executor=__esm(()=>{init_logger();init_capability_probe();SandboxError=class SandboxError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="SandboxError"}};UNTRUSTED_ENV_KEY_PREFIXES=["GIT_","LD_","DYLD_"];_sandboxAssessmentCache=new Map;_internals42={detectSandboxCapability}});var COUNCIL_MEMBER_ROLES,COUNCIL_DEFAULTS;var init_types=__esm(()=>{COUNCIL_MEMBER_ROLES=["critic","reviewer","sme","test_engineer","explorer"],COUNCIL_DEFAULTS={enabled:!1,maxRounds:3,parallelTimeoutMs:30000,vetoPriority:!0,requireAllMembers:!1,minimumMembers:3,phaseConcernsAllowComplete:!0,finalCompletionPolicy:{mode:"all_required"},freshnessMaxAgeHours:24}});import{createHash as createHash21}from"node:crypto";function isIdentityDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function resolveCouncilMemberRole(agentName){let resolved=getCanonicalAgentRole(agentName);return COUNCIL_MEMBER_ROLES.includes(resolved)?resolved:null}function computeCouncilReviewHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,type:phase.type,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,fr_refs:task.fr_refs?[...task.fr_refs].sort():void 0}))}))};return createHash21("sha256").update(JSON.stringify(normalized),"utf8").digest("hex")}function computeCouncilPolicyDigest(level,config2){let base={maxRounds:config2?.maxRounds??3,vetoPriority:config2?.vetoPriority??!0,freshnessMaxAgeHours:config2?.freshnessMaxAgeHours??24},normalized;if(level==="final")normalized={...base,finalCompletionPolicy:resolveFinalCompletionPolicy(config2)};else if(level==="phase")normalized={...base,requireAllMembers:config2?.requireAllMembers??!1,minimumMembers:config2?.minimumMembers??3,phaseConcernsAllowComplete:config2?.phaseConcernsAllowComplete??!0};else normalized={...base,requireAllMembers:config2?.requireAllMembers??!1,minimumMembers:config2?.minimumMembers??3};return createHash21("sha256").update(JSON.stringify(normalized),"utf8").digest("hex")}function resolveFinalCompletionPolicy(config2){let policy=config2?.finalCompletionPolicy;if(!policy||policy.mode!=="quorum")return{mode:"all_required"};let minimum=policy.minimumMembers;if(typeof minimum==="number"&&Number.isInteger(minimum)&&minimum>=3&&minimum<=5)return{mode:"quorum",minimumMembers:minimum};return{mode:"all_required"}}function computeCouncilReviewIdentity(input){let identity={version:COUNCIL_REVIEW_IDENTITY_VERSION,level:input.level,scope:input.scope,planId:input.plan?derivePlanId(input.plan):null,planIdentityHash:input.plan?derivePlanIdentityHash(input.plan):null,reviewHash:input.plan?computeCouncilReviewHash(input.plan):null,policyDigest:computeCouncilPolicyDigest(input.level,input.config)};return{...identity,identityDigest:createHash21("sha256").update(JSON.stringify(identity),"utf8").digest("hex")}}function councilIdentityEvidenceFields(identity){return{identity_version:identity.version,review_hash:identity.reviewHash,policy_digest:identity.policyDigest,identity_digest:identity.identityDigest}}var COUNCIL_REVIEW_IDENTITY_VERSION=2,DIGEST_PATTERN;var init_council_review_identity=__esm(()=>{init_schema();init_planning_profile();init_utils3();init_types();DIGEST_PATTERN=/^[a-f0-9]{64}$/});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash22}from"node:crypto";function hashString(value){return createHash22("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired2(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired2(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired2(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired2(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});function normalizeToolName(toolName){if(!toolName)return;return toolName.replace(NAMESPACE_PREFIX_PATTERN,"")}function normalizeToolNameLowerCase(toolName){return toolName.replace(NAMESPACE_PREFIX_PATTERN,"").toLowerCase()}function isTaskToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.task$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="task"}var NAMESPACE_PREFIX_PATTERN;var init_normalize_tool_name=__esm(()=>{NAMESPACE_PREFIX_PATTERN=/^[^:]+[:.]/});import*as fsSync5 from"node:fs";import*as path46 from"node:path";function dcNormalizeCommand(cmd){let s=cmd.normalize("NFKC");return s=s.replace(/`(.)/g,"$1"),s=s.replace(/\^([a-zA-Z0-9 ])/g,"$1"),s=s.replace(/""/g,""),s=s.replace(/''/g,""),s}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=/^cmd(?:\.exe)?\s+\/[ckCK]\s+"?(.*?)"?\s*$/is.exec(t);if(cmdExeMatch)return cmdExeMatch[1].trim();let psCommandMatch=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-(?:Command|command|c)\s+)(.+)$/is.exec(t);if(psCommandMatch)return psCommandMatch[1].replace(/^["']|["']$/g,"").trim();let psEncMatch=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-(?:EncodedCommand|encodedcommand|enc|e)\s+)([A-Za-z0-9+/=]+)\s*$/.exec(t);if(psEncMatch)try{return Buffer.from(psEncMatch[1],"base64").toString("utf16le").trim()}catch{return t}let shellMatch=/^(?:bash|sh|zsh|dash|fish)(?:\.exe)?\s+-c\s+"?(.*?)"?\s*$/is.exec(t);if(shellMatch)return shellMatch[1].trim();let evalMatch=/^eval\s+(.+)$/is.exec(t);if(evalMatch)return evalMatch[1].replace(/^["']|["']$/g,"").trim();let prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??/^env(?:\s+[A-Za-z_][A-Za-z0-9_]*=[^\s]*)*\s+(.+)$/is.exec(t)??/^nice\s+(?:-n\s+\d+\s+)?(.+)$/is.exec(t);if(prefixMatch)return prefixMatch[1].trim();let wslMatch=/^wsl(?:\.exe)?\s+(?:-e|--)\s+(.+)$/is.exec(t);if(wslMatch)return wslMatch[1].trim();let scriptBlockMatch=/^&\s*\{(.+)\}$/s.exec(t);if(scriptBlockMatch)return scriptBlockMatch[1].trim();let iexMatch=/^(?:Invoke-Expression|iex)\s+(.+)$/is.exec(t);if(iexMatch)return iexMatch[1].replace(/^["'`]|["'`]$/g,"").trim();let invokeCommandMatch=/^Invoke-Command\s+.*-ScriptBlock\s*\{(.+)\}$/is.exec(t);if(invokeCommandMatch)return invokeCommandMatch[1].trim();let callMatch=/^call\s+(.+)$/is.exec(t);if(callMatch)return callMatch[1].trim();return null}function dcUnwrapWrappers(cmd){let current=cmd.trim();for(let depth=0;depth<DC_MAX_UNWRAP_DEPTH;depth++){let inner=dcStripOneWrapper(current);if(inner===null||inner===current)break;current=inner.trim()}return current}function dcSplitSegments(cmd){let segments=[],current="",inDoubleQuote=!1,inSingleQuote=!1;for(let i=0;i<cmd.length;i++){let ch=cmd[i],next=cmd[i+1];if(ch==='"'&&!inSingleQuote){inDoubleQuote=!inDoubleQuote,current+=ch;continue}if(ch==="'"&&!inDoubleQuote){inSingleQuote=!inSingleQuote,current+=ch;continue}if(!inDoubleQuote&&!inSingleQuote){if(ch==="&"&&next==="&"||ch==="|"&&next==="|"){segments.push(current.trim()),current="",i++;continue}if(ch==="|"||ch===";"||ch===`
|
|
700
|
+
`||ch==="\r"){segments.push(current.trim()),current="";continue}if(ch==="&"&&next!=="&"){if(!(cmd[i-1]===">"||next===">")){segments.push(current.trim()),current="";continue}}}current+=ch}if(current.trim())segments.push(current.trim());return segments.filter((s)=>s.length>0)}function dcExtractRecursiveRmTargets(segment){let tokens=segment.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/g)??[];if(tokens.length<2||tokens[0]!=="rm")return null;let destructive=!1,index=1;for(;index<tokens.length;index++){let token=tokens[index];if(token==="--"){index++;break}if(!token.startsWith("-")||token==="-")break;if(token==="--recursive"||token==="--force")destructive=!0;if(!token.startsWith("--")&&/[rRfF]/.test(token.slice(1)))destructive=!0}if(!destructive)return null;return tokens.slice(index).map((target)=>target.replace(/^(["'])|(["'])$/g,""))}function dcHasUnresolvableVars(p){return/(%[A-Za-z_][A-Za-z0-9_]*%|\$\{?[A-Za-z_]|\$env:)/i.test(p)}function dcIsRemotePath(p){return DC_REMOTE_PREFIXES.some((pfx)=>p.startsWith(pfx))}function dcLstatAncestorWalk(targetPath,cwd){let normalizedTarget=path46.resolve(cwd,targetPath),normalizedCwd=path46.resolve(cwd),ancestors=[],current=normalizedTarget;while(!0){let rel=path46.relative(normalizedCwd,current);if(rel===".."||rel.startsWith(`..${path46.sep}`)||path46.isAbsolute(rel))break;if(ancestors.push(current),rel==="")break;let parent=path46.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat7=null;try{stat7=fsSync5.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`lstat failed on "${ancestor}": ${String(err)} — refusing to allow destructive operation on unverifiable path`}if(stat7.isSymbolicLink())return`BLOCKED: "${ancestor}" is a symlink/junction — deleting recursively through it would destroy the link target. Use platform-specific junction deletion (fsutil reparsepoint delete, Remove-Item without -Recurse) instead.`}return null}function dcValidateTargets(targets,cwd){for(let raw of targets){let t=raw.trim().replace(/^["']|["']$/g,"");if(!t||t===".")continue;if(dcHasUnresolvableVars(t))return`BLOCKED: Destructive command targets path with unexpanded variable "${t}" — cannot verify safety. Resolve variables before using destructive operations.`;if(dcIsRemotePath(t))return`BLOCKED: Destructive command targets remote/network filesystem path "${t}" — refusing to execute remote destructive operations.`;if(/^\\\\/.test(t))return`BLOCKED: Destructive command targets UNC path "${t}" — UNC paths in destructive operations are not allowed.`;let filesystemTarget=t.replace(/[\\/]+/g,path46.sep),lstatBlock=dcLstatAncestorWalk(filesystemTarget,cwd);if(lstatBlock)return lstatBlock;let basename10=path46.basename(filesystemTarget);if(dcPathComponents(t).length===1&&DC_SAFE_TARGETS.has(basename10))continue;if(DC_FS_ROOTS.has(t)||DC_FS_ROOTS.has(t.replace(/\//g,"\\")))return`BLOCKED: Destructive command targets filesystem root "${t}"`;if(path46.isAbsolute(t)||/^[A-Za-z]:/.test(t)){for(let blocked of DC_BLOCKED_ABSOLUTE_PREFIXES)if(t.startsWith(blocked))return`BLOCKED: Destructive command targets system path "${t}" which is under protected prefix "${blocked}"`}}return null}function dcIsUntrustedCodePoint(codePoint){return codePoint<=31||codePoint>=127&&codePoint<=159||codePoint>=8234&&codePoint<=8238||codePoint>=8294&&codePoint<=8297}function dcHasUntrustedText(value){return Array.from(value).some((character)=>dcIsUntrustedCodePoint(character.codePointAt(0)??0))}function dcSafeDiagnosticValue(value){return value.split("").map((character)=>dcIsUntrustedCodePoint(character.codePointAt(0)??0)?"?":character).join("").slice(0,512)}function dcPathComponents(value){return value.replace(/\\/g,"/").split("/").filter(Boolean)}function dcComponentEquals(left,right){return process.platform==="win32"?left.toLowerCase()===right.toLowerCase():left===right}function dcScopeContains(scopeEntry,target){let normalize7=(value)=>{let normalized=path46.posix.normalize(value.replace(/\\/g,"/")).replace(/^\.\//,"").replace(/\/$/,"");return process.platform==="win32"?normalized.toLowerCase():normalized},scope=normalize7(scopeEntry),candidate=normalize7(target);return candidate===scope||candidate.startsWith(`${scope}/`)}function dcEvaluateRecursiveDeleteTargets(input){if(input.targets.length===0)return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:"BLOCKED: Recursive delete has no statically verifiable target."};let commonBlock=dcValidateTargets(input.targets,input.cwd);if(commonBlock)return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:commonBlock};let normalizedTargets=[],hasNested=!1;for(let raw of input.targets){let target=raw.trim().replace(/^['"]|['"]$/g,""),safeTarget=dcSafeDiagnosticValue(target);if(!target||target==="."||dcHasUntrustedText(target)||dcPathComponents(target).includes(".."))return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:`BLOCKED: Recursive delete target "${safeTarget}" is empty, the workspace root, contains traversal, or contains control characters.`};let components=dcPathComponents(target);if(components.some((component)=>dcComponentEquals(component,".git")||dcComponentEquals(component,".swarm")))return{allowed:!1,code:"DESTRUCTIVE_TARGET_PROTECTED",reason:`BLOCKED: Recursive delete target "${safeTarget}" contains protected .git or .swarm state.`};let filesystemTarget=target.replace(/[\\/]+/g,path46.sep),resolved=path46.resolve(input.cwd,filesystemTarget),relative9=path46.relative(path46.resolve(input.cwd),resolved);if(relative9===""||relative9===".."||relative9.startsWith(`..${path46.sep}`)||path46.isAbsolute(relative9))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUTSIDE_WORKSPACE",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not strictly contained by the workspace.`};let basename10=path46.basename(resolved);if(!DC_SAFE_TARGETS.has(basename10))return{allowed:!1,code:"DESTRUCTIVE_TARGET_NOT_SAFE_ARTIFACT",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not an allowlisted build/cache artifact.`};let normalizedRelative=relative9.replace(/\\/g,"/");if(components.length!==1){if(hasNested=!0,!input.verifiedScope?.bindingId||!input.verifiedScope.generationId)return{allowed:!1,code:"DESTRUCTIVE_TARGET_SCOPE_REQUIRED",reason:`BLOCKED: Nested safe artifact "${safeTarget}" requires a verified active coder scope binding.`};if(!input.verifiedScope.files.some((entry)=>dcScopeContains(entry,normalizedRelative)))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUT_OF_SCOPE",reason:`BLOCKED: Nested safe artifact "${safeTarget}" is outside the verified active coder scope.`}}normalizedTargets.push(normalizedRelative)}return{allowed:!0,kind:hasNested?"scoped-nested-safe-artifact":"bare-safe-artifact",targets:normalizedTargets}}function dcCheckJunctionCreation(segment,cwd){let mklinkMatch=/^mklink(?:\.exe)?\s+\/[JjDd]\s+"?([^"\s]+)"?\s+"?([^"\s]+)"?/i.exec(segment);if(mklinkMatch){let target=mklinkMatch[2].trim();if(!dcHasUnresolvableVars(target)){let resolved=path46.resolve(cwd,target),rel=path46.relative(cwd,resolved);if(rel.startsWith("..")||path46.isAbsolute(rel))return`BLOCKED: Junction/symlink creation targeting path outside working directory: mklink target "${target}" resolves to "${resolved}" which is outside "${cwd}". Creating junctions to external paths and then deleting them recursively can destroy data.`}return null}let newItemTypeMatch=/New-Item\b.*-ItemType\s+(?:Junction|SymbolicLink|HardLink)\b/i.test(segment),newItemTargetMatch=/-Target\s+"?([^"\s;]+)"?/i.exec(segment),newItemMatch=newItemTypeMatch?newItemTargetMatch:null;if(newItemMatch){let target=newItemMatch[1].trim();if(!dcHasUnresolvableVars(target)){let resolved=path46.resolve(cwd,target),rel=path46.relative(cwd,resolved);if(rel.startsWith("..")||path46.isAbsolute(rel))return`BLOCKED: Junction/symlink creation targeting path outside working directory: New-Item target "${target}" resolves to "${resolved}" which is outside "${cwd}". This pattern caused the K2.6 data-loss incident.`}return null}let lnMatch=/^ln\s+(?:-[sfnv]*s[sfnv]*|-s)\s+"?([^"\s]+)"?(?:\s+"?[^"\s]+"?)?\s*$/.exec(segment);if(lnMatch){let target=lnMatch[1].trim();if(!dcHasUnresolvableVars(target)){let resolved=path46.resolve(cwd,target),rel=path46.relative(cwd,resolved);if(rel.startsWith("..")||path46.isAbsolute(rel))return`BLOCKED: Symlink creation targeting path outside working directory: ln -s target "${target}" resolves to "${resolved}" which is outside "${cwd}". Symlinks to external paths combined with recursive deletion can destroy data.`}return null}return null}function dcExtractWindowsCmdTargets(segment){let rmdirMatch=/^(?:rmdir|rd)(?:\.exe)?\s+(?:\/[sqSQ]\s+)*"?(.+?)"?\s*$/i.exec(segment);if(rmdirMatch)return[rmdirMatch[1].trim()];let delMatch=/^del(?:\.exe)?\s+(?:\/[sqfSQF]\s+)*"?(.+?)"?\s*$/i.exec(segment);if(delMatch)return[delMatch[1].trim()];return[]}function dcExtractPowerShellTargets(segment){let verbMatch=/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\s+/i.exec(segment);if(!verbMatch)return[];let tokens=segment.slice(verbMatch[0].length).match(/"[^"]*"|'[^']*'|[^\s]+/g)??[],targets=[],valueFlags=new Set(["-literalpath","-path","-filter","-include","-exclude","-lp"]),skipNext=!1;for(let tok of tokens){if(skipNext){skipNext=!1;continue}if(tok.startsWith("-")){if(valueFlags.has(tok.toLowerCase())){skipNext=!0;let idx=tokens.indexOf(tok);if(idx!==-1&&idx+1<tokens.length){let val=tokens[idx+1].replace(/^["']|["']$/g,"");if(val)targets.push(val);skipNext=!0}}}else{let cleaned=tok.replace(/^["']|["']$/g,"");if(cleaned)targets.push(cleaned)}}return targets}var DC_MAX_UNWRAP_DEPTH=5,DC_SAFE_TARGETS,DC_BLOCKED_ABSOLUTE_PREFIXES,DC_FS_ROOTS,DC_REMOTE_PREFIXES;var init_destructive_command=__esm(()=>{DC_SAFE_TARGETS=new Set(["node_modules","dist","build","coverage",".next",".turbo",".cache",".venv","venv","__pycache__","target","out",".parcel-cache",".svelte-kit",".nuxt",".output",".angular",".gradle","vendor"]),DC_BLOCKED_ABSOLUTE_PREFIXES=["/root","/home","/Users","/etc","/var","/usr","/opt","/bin","/sbin","/lib","/boot","/proc","/sys","/dev","/run","/System","/Library","/Applications","C:\\Windows","C:\\Users","C:\\Program Files","C:\\ProgramData","C:/Windows","C:/Users","C:/Program Files","C:/ProgramData"],DC_FS_ROOTS=new Set(["/","C:\\","C:/","D:\\","D:/","E:\\","E:/"]),DC_REMOTE_PREFIXES=["\\\\","/Volumes/","/net/","/nfs/","/smb/","/run/user/"]});import{createHash as createHash23}from"node:crypto";function digest2(value){return createHash23("sha256").update(value).digest("hex")}function hasAmbiguousSyntax(value){let single=!1,double=!1,escaped=!1;for(let character of value){if(escaped){escaped=!1;continue}if(character==="\\"){escaped=!0;continue}if(character==="'"&&!double)single=!single;if(character==='"'&&!single)double=!double}return single||double||escaped||/<<[-]?\s*\w+/.test(value)||/\$\(|`|\$\{?|\$IFS\b/i.test(value)}function matchRule(rules,segment){for(let rule of rules)if(rule.pattern.test(segment))return rule;return null}function classifySegment(segment,ambiguous){let bounded=segment.slice(0,MAX_EVIDENCE_CHARS),catastrophic=matchRule(CATASTROPHIC,segment);if(catastrophic)return{segment:bounded,category:"catastrophic",reason:catastrophic.reason??catastrophic.pattern.source,ruleId:catastrophic.id};let destructive=matchRule(DESTRUCTIVE,segment);if(destructive)return{segment:bounded,category:"destructive",reason:destructive.reason??destructive.pattern.source,ruleId:destructive.id};if(ambiguous||/[<>]|\|\s*(?:sh|bash|zsh|fish|pwsh|powershell|cmd)\b/i.test(segment))return{segment:bounded,category:"unknown",reason:"ambiguous shell syntax"};let escalate=matchRule(ESCALATE,segment);if(escalate)return{segment:bounded,category:"escalate",reason:escalate.reason??escalate.pattern.source,ruleId:escalate.id};let safe=matchRule(SAFE,segment);if(safe)return{segment:bounded,category:"safe",reason:safe.reason??safe.pattern.source,ruleId:safe.id};return{segment:bounded,category:"unknown",reason:"command is not in the bounded classifier corpus"}}function getSharedClassifierGuardrailBlock(classification){if(classification.aggregate!=="catastrophic"&&classification.aggregate!=="destructive")return null;for(let segment of classification.segments){if(segment.category!==classification.aggregate||typeof segment.ruleId!=="string")continue;let rule=BLOCK_RULES_BY_ID.get(segment.ruleId);if(!rule?.liveGuardrail||rule.liveGuardrail.mode!=="immediate-block")continue;return Object.freeze({ruleId:rule.id,category:classification.aggregate,destructiveCategory:rule.liveGuardrail.destructiveCategory,message:rule.liveGuardrail.message})}return null}function classifyCommand(original){let originalDigest=digest2(typeof original==="string"?original:String(original));if(typeof original!=="string"||original.length===0)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});if(Buffer.byteLength(original,"utf8")>MAX_COMMAND_BYTES)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});let normalized=dcNormalizeCommand(original),unwrapped=dcUnwrapWrappers(normalized),candidates=[...new Set([normalized,unwrapped,...dcSplitSegments(normalized),...dcSplitSegments(unwrapped),...dcSplitSegments(normalized).map(dcUnwrapWrappers)])];if(candidates.length===0||candidates.length>MAX_SEGMENTS)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});let ambiguous=hasAmbiguousSyntax(normalized),segments=candidates.map((segment)=>classifySegment(segment.trim(),ambiguous)),aggregate=segments.reduce((highest,current)=>SEVERITY[current.category]>SEVERITY[highest]?current.category:highest,"safe"),frozenSegments=Object.freeze(segments.map((segment)=>Object.freeze(segment)));return Object.freeze({v:1,originalDigest,aggregate,ambiguous,segments:frozenSegments})}var MAX_COMMAND_BYTES=65536,MAX_SEGMENTS=128,MAX_EVIDENCE_CHARS=512,SEVERITY,CATASTROPHIC,DESTRUCTIVE,ESCALATE,SAFE,BLOCK_RULES_BY_ID;var init_command_classifier=__esm(()=>{init_destructive_command();SEVERITY={safe:0,escalate:1,unknown:2,destructive:3,catastrophic:4},CATASTROPHIC=[{id:"fork-bomb",pattern:/:\s*\(\s*\)\s*\{[^}]*\|[^}]*:/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"fork bomb",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"power-control",pattern:/\b(?:shutdown|reboot|halt|poweroff)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"system shutdown",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"mkfs-suffixed",pattern:/\bmkfs[./]/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"diskpart",pattern:/^diskpart(?:\.exe)?$/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"format-drive",pattern:/^format\s+[A-Za-z]:/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"vssadmin-delete",pattern:/^vssadmin(?:\.exe)?\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"wbadmin-delete",pattern:/^wbadmin(?:\.exe)?\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"bcdedit-delete",pattern:/^bcdedit(?:\.exe)?\s+\/delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"boot configuration delete",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"dd-data-wipe",pattern:/\bdd\b[^\n]*(?:of=\s*(?:\/dev\/|[A-Za-z]:)|if=\s*\/dev\/(?:zero|random|urandom))/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "dd" with destructive data-wipe parameters detected by the shared command classifier; critic approval cannot waive this policy'}},{id:"git-push-force",pattern:/\bgit\s+push\b[^\n]*(?:--force(?!-with-lease)|\s-f\b)/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"force push",message:"BLOCKED: Force push detected — git push --force is not allowed (use --force-with-lease instead)"}},{id:"curl-pipe-shell",pattern:/\b(?:curl|wget)\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"script pipe execution",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}}],DESTRUCTIVE=[{id:"git-reset-hard",pattern:/\bgit\s+(?:-C\s+\S+\s+)?reset\s+--hard\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git reset",message:'BLOCKED: "git reset --hard" detected — use --soft or --mixed with caution'}},{id:"git-reset-mixed-target",pattern:/\bgit\s+(?:-C\s+\S+\s+)?reset\s+--mixed\s+\S+/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git reset",message:'BLOCKED: "git reset --mixed" with a target branch/commit is not allowed'}},{id:"git-clean-force",pattern:/\bgit\s+(?:-C\s+\S+\s+)?clean\s+-[^\s]*[fdx]/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git clean",message:'BLOCKED: "git clean -fd" detected — permanently deletes untracked files and directories'}},{id:"rm-recursive",pattern:/\brm\b[^\n]*(?:-[^\s]*[rf]|--recursive|--force)/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive delete",message:"target-aware recursive delete"}},{id:"windows-recursive-delete",pattern:/\b(?:rmdir|rd|del)(?:\.exe)?\b[^\n]*\/[sqf]/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive delete",message:"target-aware Windows recursive delete"}},{id:"powershell-recursive-delete",pattern:/\bRemove-Item\b[^\n]*(?:-Recurse|-Force)/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive remove",message:"target-aware PowerShell recursive delete"}},{id:"find-delete",pattern:/\bfind\b[^\n]*\s-delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"find delete",message:'BLOCKED: "find -delete" detected — dynamic delete expansion is not allowed from shell commands'}},{id:"rsync-delete",pattern:/\brsync\b[^\n]*--delete(?:-after|-before|-during|-delay)?\b/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"rsync delete",message:"target-aware rsync delete"}},{id:"docker-system-prune",pattern:/\bdocker\s+system\s+prune\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"docker prune",message:'BLOCKED: "docker system prune" detected — destructive container operation'}},{id:"kubectl-delete",pattern:/\bkubectl\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"kubectl delete",message:'BLOCKED: "kubectl delete" detected — destructive cluster operation'}},{id:"sql-drop",pattern:/\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"sql drop",message:"BLOCKED: SQL DROP command detected — destructive database operation"}},{id:"sql-truncate",pattern:/\bTRUNCATE\s+TABLE\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"sql truncate",message:"BLOCKED: SQL TRUNCATE command detected — destructive database operation"}},{id:"sed-config-rewrite",pattern:/\bsed\s+-i\b[^\n]*(?:biome\.json|oxlintrc|eslint)/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"config rewrite",message:"BLOCKED: in-place configuration rewrite detected — protected lint or policy config edit matched the shared command classifier"}},{id:"sdelete",pattern:/^sdelete(?:\.exe)?\s+/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"secure delete",message:'BLOCKED: "sdelete" detected — secure file deletion (Sysinternals)'}},{id:"fsutil-destructive",pattern:/^fsutil(?:\.exe)?\s+(?:reparsepoint\s+delete|file\s+setzerodata)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "fsutil" destructive subcommand detected'}},{id:"takeown-recursive",pattern:/^takeown(?:\.exe)?\s+.*\/[rR]\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"ownership takeover",message:'BLOCKED: "takeown /R" (recursive ownership takeover) detected — often precedes destructive operations'}},{id:"cipher-wipe",pattern:/^cipher(?:\.exe)?\s+\/[wW]\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "cipher /w" detected — overwrites free disk space (data wipe operation)'}},{id:"robocopy-mirror",pattern:/^robocopy(?:\.exe)?\s+.*\/(?:MIR|mir)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"mirror sync",message:'BLOCKED: "robocopy /MIR" (mirror) detected — can delete files in the destination that do not exist in the source'}},{id:"chmod-permission-wipe",pattern:/^chmod\s+.*-[rR]\b.*000\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"permission wipe",message:'BLOCKED: "chmod -R 000" detected — removes all permissions recursively'}},{id:"chattr-immutable",pattern:/^chattr\s+.*\+i\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"immutable flag",message:'BLOCKED: "chattr +i" detected — makes files immutable'}},{id:"icacls-deny",pattern:/^icacls(?:\.exe)?\s+.*\/deny\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"permission deny",message:'BLOCKED: "icacls /deny" detected — denies filesystem permissions'}}],ESCALATE=[{id:"sudo-network-permissions",pattern:/\b(?:sudo|chmod|chown|curl|wget|ssh|scp|sftp|nc|netcat)\b/i},{id:"dynamic-eval",pattern:/\b(?:eval|Invoke-Expression|iex)\b/i}],SAFE=[{id:"safe-readonly-shell",pattern:/^(?:cat|head|tail|file|stat|wc|sort|uniq|cut|grep|rg|ag|ls|pwd|whoami|hostname|uname|date|which|type|tree)\b/i},{id:"safe-readonly-git",pattern:/^git\s+(?:-C\s+\S+\s+)?(?:status|log|show|diff|branch|describe|rev-parse|rev-list|ls-files|remote\s+-v)\b/i},{id:"safe-shell-builtin",pattern:/^(?:true|false|test|echo|printf)\b/i},{id:"safe-package-scripts",pattern:/^(?:bun|npm|yarn|pnpm)\s+(?:run\s+(?:typecheck|lint|test|build)|test|typecheck|lint)\b/i}],BLOCK_RULES_BY_ID=new Map([...CATASTROPHIC,...DESTRUCTIVE].map((rule)=>[rule.id,rule]))});import*as path47 from"node:path";function normalizeProtectedPath(value){return value.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function equalsOrDescendant(candidate,protectedPath){let left=process.platform==="win32"?candidate.toLowerCase():candidate,right=process.platform==="win32"?protectedPath.toLowerCase():protectedPath;return left===right||left.startsWith(`${right}/`)}function isPolicyProtectedPath(filePath,options={}){if(!filePath)return!1;let normalized=normalizeProtectedPath(filePath),segments=normalized.split("/").filter(Boolean);if(options.includeDefaults!==!1){if(segments.some((segment)=>DEFAULT_SEGMENTS.has(process.platform==="win32"?segment.toLowerCase():segment)))return!0;if(DEFAULT_PREFIXES.some((prefix)=>equalsOrDescendant(normalized,prefix)))return!0}return(options.additional??[]).some((entry)=>{let protectedPath=normalizeProtectedPath(entry);if(!protectedPath)return!1;if(equalsOrDescendant(normalized,protectedPath))return!0;if(protectedPath.includes("/"))return!1;return segments.some((segment)=>(process.platform==="win32"?segment.toLowerCase():segment)===(process.platform==="win32"?protectedPath.toLowerCase():protectedPath))})}function protectedRoots(projectRoot,additional=[]){return[...DEFAULT_PREFIXES,...DEFAULT_SEGMENTS,...additional].map((entry)=>path47.resolve(projectRoot,entry))}var DEFAULT_SEGMENTS,DEFAULT_PREFIXES,DEFAULT_PROTECTED_PATH_PREFIXES;var init_protected_path_policy=__esm(()=>{DEFAULT_SEGMENTS=new Set([".git",".swarm",".env","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","CODEOWNERS"]),DEFAULT_PREFIXES=[".github/workflows",".github/CODEOWNERS","src/sandbox","src/hooks/guardrails","src/security","src/evaluation","docs/releases","tests/fixtures/evaluation"],DEFAULT_PROTECTED_PATH_PREFIXES=DEFAULT_PREFIXES});function normalizePath(p){if(!p)return"";let result=p.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\.\//,"").replace(/(?:^|\/)\.\//g,"/");if(result=result.replace(/\/$/,""),result=result.replace(/\/\.$/,""),process.platform==="win32")result=result.toLowerCase();if(!result){let norm=p.replace(/\\/g,"/");if(norm==="."||norm==="./")return".";return""}return result}import*as fs27 from"node:fs";import*as path48 from"node:path";function isReadOnlyTool(toolName){if(!toolName)return!1;return READ_ONLY_TOOLS.has(toolName.toLowerCase())}function isWriteLikeTool(toolName){if(!toolName)return!1;return WRITE_LIKE_TOOLS.has(toolName.toLowerCase())}function isSubagentDelegation(toolName,args2){if(isTaskToolId(toolName)&&args2&&typeof args2==="object")return!0;let lower=normalizeToolNameLowerCase(toolName??"");return SUBAGENT_TOOLS.has(lower)}function isWithinDirectory(target,root){if(!target||!root)return!1;let resolvedTarget=path48.resolve(target),resolvedRoot=path48.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path48.sep)?resolvedRoot:resolvedRoot+path48.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}function isProtectedPath(filePath,config2){if(!filePath)return!1;let normalized=normalizePath(filePath);for(let prefix of ALWAYS_PROTECTED_PREFIXES){let np=normalizePath(prefix);if(normalized===np||normalized.startsWith(`${np}/`))return!0}let allowDefaults=config2?.permission_policy?.allow_defaults!==!1;return isPolicyProtectedPath(normalized,{includeDefaults:allowDefaults,additional:[...allowDefaults?PROTECTED_PATH_DEFAULTS:[],...config2?.permission_policy?.protected_paths??[]]})}function classifyPathRisk(filePath,context){if(!filePath)return{withinProjectRoot:!1,withinDeclaredScope:null,protected:!1,highRiskBuild:!1};let absolute=path48.isAbsolute(filePath)?filePath:path48.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs27.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs27.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path48.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative10=normalizePath(path48.relative(context.directory,absolute)),withinDeclaredScope=null;if(Array.isArray(context.declaredScope))withinDeclaredScope=context.declaredScope.length===0?!1:context.declaredScope.some((scope)=>{let s=normalizePath(scope);if(!s)return!1;return relative10===s||relative10.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative10.startsWith(e);return relative10===e||relative10.startsWith(`${e}/`)});return{withinProjectRoot,withinDeclaredScope,protected:!1,highRiskBuild}}function classifyCommandRisk(command,_cwd,_context){if(FULL_AUTO_SECRET_READ_PATTERN.test(command)||FULL_AUTO_SECRET_ENV_PATTERN.test(command)||FULL_AUTO_PRIMARY_PUSH_PATTERN.test(command))return{decision:"deny",reason:"full-auto consumer policy: command reads secrets or targets a primary branch push"};let classification=classifyCommand(command);if(classification.aggregate==="catastrophic"||classification.aggregate==="destructive")return{decision:"deny",reason:`shared classifier: ${classification.aggregate}`};if(classification.aggregate==="safe")return{decision:"allow",reason:"shared classifier: safe"};return{decision:"escalate_critic",reason:`shared classifier: ${classification.aggregate}`}}function extractPathArgs(toolName,args2){if(!args2||typeof args2!=="object")return[];let found=[];for(let key of PATH_ARG_KEYS){let v=args2[key];if(typeof v==="string"&&v.trim())found.push(v)}let filesArg=args2.files;if(Array.isArray(filesArg)){for(let f of filesArg)if(typeof f==="string"&&f.trim())found.push(f);else if(f&&typeof f==="object"&&typeof f.path==="string")found.push(f.path)}let editsArg=args2.edits;if(Array.isArray(editsArg)){for(let e of editsArg)if(e&&typeof e==="object"&&typeof e.file_path==="string")found.push(e.file_path)}if(toolName==="declare_scope"&&Array.isArray(args2.files));return found}function extractCommandArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.command==="string"&&args2.command||typeof args2.cmd==="string"&&args2.cmd||typeof args2.script==="string"&&args2.script||void 0}function extractURLArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.url==="string"&&args2.url||typeof args2.uri==="string"&&args2.uri||typeof args2.endpoint==="string"&&args2.endpoint||void 0}function isTrustedDomain(url2,config2){let domains=config2?.permission_policy?.trusted_domains??[];if(domains.length===0)return!1;let host="";try{host=new URL(url2).hostname.toLowerCase()}catch{return!1}return domains.some((d)=>{let dl=d.toLowerCase();return host===dl||host.endsWith(`.${dl}`)})}function resolveAgentCapabilityTools(roleName,pluginConfig){let tools=pluginConfig?.tool_filter?.overrides?.[roleName]??AGENT_TOOL_MAP[roleName]??[];if(pluginConfig?.memory?.enabled===!0)tools=Array.from(new Set([...tools,...MEMORY_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.external_skills?.curation_enabled===!0)tools=Array.from(new Set([...tools,...EXTERNAL_SKILL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.enabled===!0)tools=Array.from(new Set([...tools,...COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.general?.enabled===!0)tools=Array.from(new Set([...tools,...GENERAL_COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.turbo!==void 0)tools=Array.from(new Set([...tools,...TURBO_AGENT_TOOL_MAP[roleName]??[]]));let skillTools=SKILL_AGENT_TOOL_MAP[roleName]??[];if(skillTools.length>0)if(pluginConfig?.skills?.enabled===!0)tools=Array.from(new Set([...tools,...skillTools]));else{let skillSet=new Set(skillTools);tools=tools.filter((tool)=>!skillSet.has(tool))}if(pluginConfig?.skills?.enabled!==!0&&roleName!=="skill_improver"){let allSkillTools=new Set(SKILL_TOOL_NAMES);tools=tools.filter((tool)=>!allSkillTools.has(tool))}return tools}function resolveDelegationRisk(input,subagentName){let role=input.generatedAgentNames&&input.generatedAgentNames.length>0?resolveGeneratedAgentRole(subagentName,input.generatedAgentNames):getCanonicalAgentRole(subagentName);if(!isKnownCanonicalRole(role))return{risk:"high",reason:"subagent role is unknown or not registry-backed",role,tools:[],safeReadOnly:!1};let tools=resolveAgentCapabilityTools(role,input.pluginConfig);if(tools.length===0)return{risk:"high",reason:"subagent has no registered capability map",role,tools,safeReadOnly:!1};let dangerous=tools.some((tool)=>isWriteLikeTool(tool)||SHELL_TOOLS.has(tool)||NETWORK_TOOLS.has(tool)||tool==="swarm_command"||tool==="Task"||tool==="task"),unknown2=tools.some((tool)=>!isReadOnlyTool(tool)&&!isWriteLikeTool(tool)&&!SHELL_TOOLS.has(tool)&&!NETWORK_TOOLS.has(tool)&&tool!=="swarm_command");if(dangerous||unknown2)return{risk:"high",reason:dangerous?"delegated role can write, execute, publish, or recurse":"delegated role exposes non-read-only unknown capabilities",role,tools,safeReadOnly:!1};return{risk:"medium",reason:"delegated role is limited to registered read-only capabilities",role,tools,safeReadOnly:!0}}function classifyFullAutoToolAction(input){let tool=input.toolName?.toLowerCase()??"",config2=input.fullAutoConfig,mode=config2?.mode??"supervised";if(!(mode==="strict"||config2?.permission_policy?.enabled!==!1))return{action:"allow",reason:"permission policy disabled by config",tier:"local"};if(isReadOnlyTool(tool))return{action:"allow",reason:"read-only tool",tier:"safe"};if(isSubagentDelegation(tool,input.args)){let subagentName=typeof input.args?.subagent_type==="string"&&input.args.subagent_type||typeof input.args?.agent==="string"&&input.args.agent||"unknown",delegationRisk=resolveDelegationRisk(input,subagentName);if(mode!=="strict"&&delegationRisk.safeReadOnly)return{action:"allow",reason:`read-only subagent delegation allowed (${delegationRisk.role})`,tier:"local"};return{action:"escalate_critic",reason:`subagent delegation requires plan/scope verification (${delegationRisk.reason})`,risk:mode==="strict"?"high":delegationRisk.risk,context:{tool,subagent:subagentName,canonicalRole:delegationRisk.role,registeredTools:delegationRisk.tools,currentTaskID:input.currentTaskID,currentPhase:input.currentPhase}}}if(tool==="phase_complete")return{action:"escalate_critic",reason:"phase_complete requires Full-Auto approval evidence",risk:"high",context:{tool,currentPhase:input.currentPhase}};if(tool==="update_task_status"){let status=typeof input.args?.status==="string"&&input.args.status||"";if(status==="completed"){if(mode==="strict"||config2?.oversight?.on_task_completion===!0)return{action:"escalate_critic",reason:"task completion requires Full-Auto critic verification",risk:"medium",context:{tool,status}}}else{if(mode==="strict")return{action:"escalate_critic",reason:`strict mode: update_task_status with status=${status} requires critic verification`,risk:"medium",context:{tool,status}};return{action:"allow",reason:`update_task_status with status=${status} is a routine state change`,tier:"local"}}}if(tool==="save_plan")return{action:"escalate_critic",reason:"plan mutation requires Full-Auto critic verification",risk:"high",context:{tool}};if(NETWORK_TOOLS.has(tool)){let url2=extractURLArg(input.args);if(url2&&isTrustedDomain(url2,config2))return{action:"allow",reason:"network tool with trusted domain",tier:"local"};return{action:"escalate_critic",reason:"network/web tool — verify intent and target",risk:"medium",context:{tool,url:url2}}}if(SHELL_TOOLS.has(tool)){let command=extractCommandArg(input.args);if(!command)return{action:"deny",reason:"shell tool invoked without a command argument",code:"shell_no_command",recoverable:!0};let cmdRisk=classifyCommandRisk(command,input.workingDirectory??"",{directory:input.directory});if(cmdRisk.decision==="deny")return{action:"deny",reason:cmdRisk.reason,code:"shell_deny",recoverable:!0};if(cmdRisk.decision==="allow")return{action:"allow",reason:cmdRisk.reason,tier:"local"};return{action:"escalate_critic",reason:cmdRisk.reason,risk:"medium",context:{tool,command}}}if(isWriteLikeTool(tool)||tool==="patch"||tool==="edit"){let paths=extractPathArgs(tool,input.args);if(paths.length===0){if(new Set(["declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine"]).has(tool))return{action:"allow",reason:`pathless plan/evidence tool '${tool}' allowed under Full-Auto`,tier:"local"};return{action:"escalate_critic",reason:"write-like tool without explicit path — verify side effects",risk:"medium",context:{tool,args:input.args}}}for(let p of paths){let risk=classifyPathRisk(p,{directory:input.directory,declaredScope:input.declaredScope??null});if(!risk.withinProjectRoot)return{action:"deny",reason:`write target outside project root: ${p}`,code:"path_out_of_root",recoverable:!0};if(isProtectedPath(path48.relative(input.directory,path48.resolve(input.directory,p)),config2))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool}}}function buildStructuredDenial(decision,tool){return{full_auto_denial:!0,tool,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}var READ_ONLY_TOOLS,WRITE_LIKE_TOOLS,SHELL_TOOLS,NETWORK_TOOLS,SUBAGENT_TOOLS,HIGH_RISK_BUILD_PATHS,ALWAYS_PROTECTED_PREFIXES,PROTECTED_PATH_DEFAULTS,FULL_AUTO_SECRET_READ_PATTERN,FULL_AUTO_SECRET_ENV_PATTERN,FULL_AUTO_PRIMARY_PUSH_PATTERN,PATH_ARG_KEYS;var init_policy=__esm(()=>{init_constants();init_schema();init_normalize_tool_name();init_command_classifier();init_protected_path_policy();READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine","suggest_patch"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","gitingest"]),SUBAGENT_TOOLS=new Set(["agent","delegate"]),HIGH_RISK_BUILD_PATHS=["src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto/","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"];FULL_AUTO_SECRET_READ_PATTERN=/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)\b/i,FULL_AUTO_SECRET_ENV_PATTERN=/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,FULL_AUTO_PRIMARY_PUSH_PATTERN=/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i;PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"]});async function withTimeout(promise2,ms,timeoutError){let timer,timeoutPromise=new Promise((_,reject)=>{timer=setTimeout(()=>reject(timeoutError),ms)});try{return await Promise.race([promise2,timeoutPromise])}finally{if(timer!==void 0)clearTimeout(timer)}}async function withTimeoutSignal(operation,ms,timeoutError){if(!Number.isFinite(ms)||ms<0)throw RangeError("timeout must be a finite non-negative number");if(timeoutError.name==="Error")try{timeoutError.name="TimeoutError"}catch{}let controller=new AbortController,timer,timeoutPromise=new Promise((_,reject)=>{timer=_internals43.setTimeout(()=>{controller.abort(timeoutError),reject(timeoutError)},ms)});try{return await Promise.race([Promise.resolve().then(()=>operation(controller.signal)),timeoutPromise])}finally{if(timer!==void 0)_internals43.clearTimeout(timer)}}function yieldToEventLoop(){return new Promise((resolve26)=>{setTimeout(resolve26,0)})}var _internals43;var init_timeout=__esm(()=>{_internals43={setTimeout,clearTimeout}});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals44});import{existsSync as existsSync26,statSync as statSync15}from"node:fs";import*as path49 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{Language,Parser as TreeSitterParser}from"web-tree-sitter";async function initTreeSitter(){if(!treeSitterInitPromise)treeSitterInitPromise=(async()=>{if(_internals44.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals44.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path49.join(grammarsDir,"tree-sitter.wasm");if(!_internals44.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
|
|
701
701
|
The installed OpenCode plugin cache is incomplete or stale. Run 'bunx opencode-swarm update', then restart OpenCode so it fetches a fresh package from npm.`);await _internals44.parserInit({locateFile(scriptName){return path49.join(grammarsDir,scriptName)}})}})().catch((err)=>{throw treeSitterInitPromise=null,err});return treeSitterInitPromise}function sanitizeLanguageId(languageId){let normalized=languageId.toLowerCase();if(!/^[a-z0-9-]+$/.test(normalized))throw Error(`Invalid language ID: ${languageId}`);return normalized}function getWasmFileName(languageId){let sanitized=sanitizeLanguageId(languageId).toLowerCase();if(LANGUAGE_WASM_MAP[sanitized])return LANGUAGE_WASM_MAP[sanitized];return`tree-sitter-${sanitized}.wasm`}function resolveGrammarsDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/lang"),isCliBundle=normalized.endsWith("/cli");return isSource?path49.join(thisDir,"grammars"):isCliBundle?path49.join(thisDir,"..","lang","grammars"):path49.join(thisDir,"lang","grammars")}function getGrammarsDirAbsolute(){let thisDir=_internals44.getModuleDir();return resolveGrammarsDir(thisDir)}async function loadGrammar(languageId){if(typeof languageId!=="string"||languageId.length>100)throw Error("Invalid languageId: must be a string of at most 100 characters");let normalizedId=sanitizeLanguageId(languageId).toLowerCase();if(normalizedId.length===0)throw Error("Invalid languageId: empty after sanitization");if(parserCache.has(normalizedId))return parserCache.get(normalizedId);let existing=inflightLoads.get(normalizedId);if(existing)return existing;let loadPromise=(async()=>{await initTreeSitter();let parser=new TreeSitterParser,wasmFileName=getWasmFileName(normalizedId),wasmPath=path49.join(getGrammarsDirAbsolute(),wasmFileName);if(!_internals44.fileExists(wasmPath))throw Error(`Grammar file not found for ${languageId}: ${wasmPath}
|
|
702
702
|
Make sure to run 'bun run build' to copy grammar files to dist/lang/grammars/. If this is an installed OpenCode plugin cache, run 'bunx opencode-swarm update' and restart OpenCode.`);try{let language=await withTimeout(Language.load(wasmPath),GRAMMAR_LOAD_TIMEOUT_MS,Error(`Timed out after ${GRAMMAR_LOAD_TIMEOUT_MS}ms loading grammar`));parser.setLanguage(language)}catch(error49){throw Error(`Failed to load grammar for ${languageId}: ${error49 instanceof Error?error49.message:String(error49)}
|
|
703
703
|
WASM path: ${wasmPath}`)}return parserCache.set(normalizedId,parser),initializedLanguages.add(normalizedId),parser})();inflightLoads.set(normalizedId,loadPromise);try{return await loadPromise}finally{inflightLoads.delete(normalizedId)}}async function isGrammarAvailable(languageId){if(typeof languageId!=="string"||languageId.length>100)return!1;let normalizedId;try{normalizedId=sanitizeLanguageId(languageId).toLowerCase()}catch{return!1}if(normalizedId.length===0)return!1;if(parserCache.has(normalizedId))return!0;try{let wasmFileName=getWasmFileName(normalizedId),wasmPath=path49.join(getGrammarsDirAbsolute(),wasmFileName);return statSync15(wasmPath),!0}catch{return!1}}function clearParserCache(){parserCache.clear(),inflightLoads.clear(),initializedLanguages.clear(),treeSitterInitPromise=null}function getInitializedLanguages(){return Array.from(initializedLanguages)}function getSupportedLanguages(){return Object.keys(LANGUAGE_WASM_MAP)}var parserCache,inflightLoads,GRAMMAR_LOAD_TIMEOUT_MS=1e4,initializedLanguages,treeSitterInitPromise=null,_internals44,LANGUAGE_WASM_MAP;var init_runtime=__esm(()=>{init_timeout();parserCache=new Map,inflightLoads=new Map,initializedLanguages=new Set,_internals44={parserInit:TreeSitterParser.init,getModuleDir:()=>path49.dirname(fileURLToPath2(import.meta.url)),fileExists:existsSync26};LANGUAGE_WASM_MAP={javascript:"tree-sitter-javascript.wasm",typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",python:"tree-sitter-python.wasm",go:"tree-sitter-go.wasm",rust:"tree-sitter-rust.wasm",cpp:"tree-sitter-cpp.wasm",c:"tree-sitter-cpp.wasm",csharp:"tree-sitter-c-sharp.wasm",css:"tree-sitter-css.wasm",bash:"tree-sitter-bash.wasm",ruby:"tree-sitter-ruby.wasm",php:"tree-sitter-php.wasm",java:"tree-sitter-java.wasm",kotlin:"tree-sitter-kotlin.wasm",swift:"tree-sitter-swift.wasm",dart:"tree-sitter-dart.wasm",powershell:"tree-sitter-powershell.wasm",ini:"tree-sitter-ini.wasm",regex:"tree-sitter-regex.wasm"}});import{extname}from"node:path";function getLanguageForExtension(extension){return extensionMap.get(extension.toLowerCase())}async function getParserForFile(filePath){let extension=extname(filePath).toLowerCase(),language=getLanguageForExtension(extension);if(!language)return null;try{let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));return await loadGrammar2(language.id)}catch{return null}}var languageDefinitions,extensionMap;var init_registry=__esm(()=>{languageDefinitions=[{id:"javascript",extensions:[".js",".jsx",".mjs",".cjs"],commentNodes:["comment","line_comment","block_comment"]},{id:"typescript",extensions:[".ts"],commentNodes:["comment","line_comment","block_comment"]},{id:"python",extensions:[".py",".pyw"],commentNodes:["comment"]},{id:"go",extensions:[".go"],commentNodes:["comment"]},{id:"rust",extensions:[".rs"],commentNodes:["line_comment","block_comment"]},{id:"php",extensions:[".php",".phtml"],commentNodes:["comment"]},{id:"java",extensions:[".java"],commentNodes:["line_comment","block_comment"]},{id:"c",extensions:[".c",".h"],commentNodes:["comment"]},{id:"cpp",extensions:[".cpp",".cxx",".cc",".hpp",".hxx",".hh"],commentNodes:["comment"]},{id:"csharp",extensions:[".cs",".csx"],commentNodes:["comment"]},{id:"ruby",extensions:[".rb",".rake",".gemspec"],commentNodes:["comment"]},{id:"swift",extensions:[".swift"],commentNodes:["comment","multiline_comment"]},{id:"kotlin",extensions:[".kt",".kts"],commentNodes:["line_comment","multiline_comment"]},{id:"dart",extensions:[".dart"],commentNodes:["comment","documentation_comment"]},{id:"css",extensions:[".css"],commentNodes:["comment"]},{id:"bash",extensions:[".sh",".bash"],commentNodes:["comment"]},{id:"powershell",extensions:[".ps1",".psm1"],commentNodes:["comment"]},{id:"ini",extensions:[".ini",".cfg",".conf"],commentNodes:["comment"]},{id:"regex",extensions:[".regex"],commentNodes:[]},{id:"tsx",extensions:[".tsx"],commentNodes:["comment"]}],extensionMap=new Map;for(let definition of languageDefinitions)for(let extension of definition.extensions)extensionMap.set(extension,definition)});var exports_ast_diff={};__export(exports_ast_diff,{computeASTDiff:()=>computeASTDiff});import{extname as extname2}from"node:path";import{Query}from"web-tree-sitter";async function computeASTDiff(filePath,oldContent,newContent){let startTime=Date.now(),extension=extname2(filePath).toLowerCase(),language=getLanguageForExtension(extension);if(!language)return{filePath,language:null,changes:[],durationMs:Date.now()-startTime,usedAST:!1};try{let timeoutId,parser=await Promise.race([loadGrammar(language.id),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)}),oldTree=parser.parse(oldContent),newTree=parser.parse(newContent);if(!oldTree||!newTree)return{filePath,language:language.id,changes:[],durationMs:Date.now()-startTime,usedAST:!1,error:"Failed to parse file"};let oldSymbols=extractSymbols(oldTree,language),newSymbols=extractSymbols(newTree,language),changes=compareSymbols(oldSymbols,newSymbols);return oldTree.delete(),newTree.delete(),{filePath,language:language.id,changes,durationMs:Date.now()-startTime,usedAST:!0}}catch(error49){let errorMsg=error49 instanceof Error?error49.message:"Unknown error";if(errorMsg==="AST_TIMEOUT")log(`[ast-diff] Timeout for ${filePath}, falling back to raw diff`);return{filePath,language:language.id,changes:[],durationMs:Date.now()-startTime,usedAST:!1,error:errorMsg}}}function extractSymbols(tree,language){let symbols=[],queryStr=QUERIES[language.id];if(!queryStr)return symbols;try{let lang=tree.language;if(!lang)return symbols;let matches=new Query(lang,queryStr).matches(tree.rootNode);for(let match of matches){let symbol2=parseMatch(match,language.id);if(symbol2)symbols.push(symbol2)}let defEntries=symbols.filter((s)=>s.category!=="export"&&s.category!=="import");if(defEntries.length>0&&defEntries.length<symbols.length){let filtered=symbols.filter((symbol2)=>{if(symbol2.category!=="export"&&symbol2.category!=="import")return!0;return!defEntries.some((def)=>symbol2.lineStart===def.lineStart&&symbol2.lineEnd===def.lineEnd)});symbols.length=0,symbols.push(...filtered)}}catch{}return symbols}function parseMatch(match,languageId){let captures=match.captures,defCapture=captures.find((c)=>c.name.endsWith(".def")),nameCapture=captures.find((c)=>c.name.endsWith(".name"));if(!defCapture){let exportCapture=captures.find((c)=>c.name==="export"),importCapture=captures.find((c)=>c.name==="import"),categoryCapture=exportCapture||importCapture;if(!categoryCapture)return null;let node2=categoryCapture.node,text=node2.text.trim(),name=extractStatementName(text,categoryCapture.name);return{category:categoryCapture.name==="export"?"export":"import",name,lineStart:node2.startPosition.row+1,lineEnd:node2.endPosition.row+1}}let node=defCapture.node,nameNode=nameCapture?.node;return{category:inferCategory(captures[0]?.name||"other"),name:nameNode?.text||"anonymous",lineStart:node.startPosition.row+1,lineEnd:node.endPosition.row+1,signature:extractSignature(node,languageId)}}function extractStatementName(text,captureType){if(captureType==="import"){let fromMatch=text.match(/from\s+['"]([^'"]+)['"]/);if(fromMatch)return fromMatch[1];let stringMatch=text.match(/['"]([^'"]+)['"]/);if(stringMatch)return stringMatch[1]}else{let namedExport=text.match(/export\s+(?:default\s+)?(?:function|class|const|let|var|type|interface)\s+(\w+)/);if(namedExport)return namedExport[1];if(text.match(/export\s+default\s+(?:function|class)\b/))return"default";let braceExport=text.match(/export\s+\{([^}]+)\}/);if(braceExport)return braceExport[1].trim()}let tokens=text.split(/\s+/);return tokens.length>1?tokens.slice(0,3).join(" "):text.slice(0,30)}function inferCategory(captureName){if(captureName.includes("func"))return"function";if(captureName.includes("class"))return"class";if(captureName.includes("type")||captureName.includes("interface")||captureName.includes("struct")||captureName.includes("protocol")||captureName.includes("mixin")||captureName.includes("object")||captureName.includes("module"))return"type";if(captureName.includes("export"))return"export";if(captureName.includes("import")||captureName.includes("use")||captureName.includes("using"))return"import";if(captureName.includes("var"))return"variable";if(captureName.includes("command"))return"function";if(captureName.includes("rule"))return"type";return"other"}function extractSignature(node,languageId){let nodeTypes=paramNodeTypes[languageId]||[];for(let child of node.children)if(child&&nodeTypes.includes(child.type))return child.text;if(languageId==="javascript"||languageId==="typescript"||languageId==="tsx"){let paramsNode=node.children.find((c)=>c!==null&&c.type==="formal_parameters");if(paramsNode)return paramsNode.text}if(node.type==="class_declaration"||node.type==="class_definition"||node.type==="class"){let classBodyNode=node.children.find((c)=>c!==null&&(c.type==="class_body"||c.type==="declaration_list"));if(classBodyNode)return classBodyNode.text}return}function compareSymbols(oldSymbols,newSymbols){let changes=[],oldMap=new Map(oldSymbols.map((s)=>[s.name,s])),newMap=new Map(newSymbols.map((s)=>[s.name,s])),matchedOldSymbols=new Set;for(let newSymbol of newSymbols)if(!oldMap.has(newSymbol.name)){let matchingOldSymbol=findRenamedSymbol(newSymbol,oldSymbols,matchedOldSymbols);if(matchingOldSymbol)changes.push({type:"renamed",category:newSymbol.category,name:newSymbol.name,lineStart:newSymbol.lineStart,lineEnd:newSymbol.lineEnd,signature:newSymbol.signature,renamedFrom:matchingOldSymbol.name}),matchedOldSymbols.add(matchingOldSymbol);else changes.push({type:"added",category:newSymbol.category,name:newSymbol.name,lineStart:newSymbol.lineStart,lineEnd:newSymbol.lineEnd,signature:newSymbol.signature})}else{let oldSymbol=oldMap.get(newSymbol.name);if(matchedOldSymbols.add(oldSymbol),oldSymbol.lineStart!==newSymbol.lineStart||oldSymbol.lineEnd!==newSymbol.lineEnd||oldSymbol.signature!==newSymbol.signature)changes.push({type:"modified",category:newSymbol.category,name:newSymbol.name,lineStart:newSymbol.lineStart,lineEnd:newSymbol.lineEnd,signature:newSymbol.signature})}for(let oldSymbol of oldSymbols)if(!newMap.has(oldSymbol.name)&&!matchedOldSymbols.has(oldSymbol))changes.push({type:"removed",category:oldSymbol.category,name:oldSymbol.name,lineStart:oldSymbol.lineStart,lineEnd:oldSymbol.lineEnd,signature:oldSymbol.signature});return changes}function findRenamedSymbol(newSymbol,oldSymbols,matchedOldSymbols){if(newSymbol.category!=="function"&&newSymbol.category!=="type"&&newSymbol.category!=="class")return null;if(!newSymbol.signature)return null;if(newSymbol.category==="function"&&newSymbol.signature.replace(/\s/g,"")==="()")return null;let lineCount=newSymbol.lineEnd-newSymbol.lineStart;for(let oldSymbol of oldSymbols){if(matchedOldSymbols.has(oldSymbol)||oldSymbol.category!==newSymbol.category)continue;if(oldSymbol.signature!==newSymbol.signature)continue;let oldLineCount=oldSymbol.lineEnd-oldSymbol.lineStart,maxAllowedLines=Math.ceil(lineCount*1.2);if(oldLineCount>maxAllowedLines)continue;return oldSymbol}return null}var QUERIES,AST_TIMEOUT_MS=500,paramNodeTypes;var init_ast_diff=__esm(()=>{init_registry();init_runtime();init_logger();QUERIES={javascript:`
|
|
@@ -977,7 +977,7 @@ No plan content available. Start by creating a .swarm/plan.md file.
|
|
|
977
977
|
`);let inProgressPhase=phases.find((p)=>p.status==="IN PROGRESS"),completePhases=phases.filter((p)=>p.status==="COMPLETE"),pendingPhases=phases.filter((p)=>p.status==="PENDING");if(completePhases.length>0){let recentComplete=completePhases.slice(-5);if(completePhases.length>5)result.push(""),result.push(`## Earlier Phases (${completePhases.length-5} more)`),result.push(`- Phase 1-${completePhases.length-5}: Complete`);result.push(""),result.push("## Completed Phases");for(let phase of recentComplete){let taskLines=phase.contentLines.filter((l)=>l.trim().startsWith("- [")).map((l)=>l.replace(/^- \[[ xX]\]\s*/,"").replace(/\s*\[.*?\]/g,"").trim()).slice(0,3),taskSummary=taskLines.length>0?taskLines.join(", "):"All tasks complete";result.push(`- Phase ${phase.number}: ${phase.title}`),result.push(` - ${taskSummary}`)}}let incompleteTasks=inProgressPhase?inProgressPhase.contentLines.filter((l)=>l.trim().startsWith("- [ ]")).map((l)=>l.trim()):[];if(inProgressPhase)if(result.push(""),result.push(`## Phase ${inProgressPhase.number} [IN PROGRESS]`),result.push(`- ${inProgressPhase.title}`),incompleteTasks.length>0){let currentTask=incompleteTasks[0];result.push(""),result.push(`- Current: ${currentTask.replace("- [ ] ","")}`);let lookahead=incompleteTasks.slice(1,1+lookaheadCount);for(let i=0;i<lookahead.length;i++)result.push(`- Next: ${lookahead[i].replace("- [ ] ","")}`)}else result.push("- (No pending tasks)");let nextPending=pendingPhases[0];if(nextPending)result.push(""),result.push(`## Phase ${nextPending.number} [PENDING]`),result.push(`- ${nextPending.title}`);let output=result.join(`
|
|
978
978
|
`);if(output+=`
|
|
979
979
|
[/SWARM PLAN CURSOR]`,output.length>maxChars){let compactResult=[];if(compactResult.push("[SWARM PLAN CURSOR]"),completePhases.length>0){compactResult.push("## Completed Phases");let recentCompact=completePhases.slice(-3);for(let phase of recentCompact){let taskLines=phase.contentLines.filter((l)=>l.trim().startsWith("- [")).map((l)=>l.replace(/^- \[[ xX]\]\s*/,"").replace(/\s*\[.*?\]/g,"").trim()).slice(0,1),taskSummary=taskLines.length>0?taskLines[0]:"Complete";compactResult.push(`- Phase ${phase.number}: ${taskSummary}`)}if(completePhases.length>3)compactResult.push(`- Earlier: Phase 1-${completePhases.length-3} complete`)}if(inProgressPhase)if(compactResult.push(""),compactResult.push(`## Phase ${inProgressPhase.number} [IN PROGRESS]`),compactResult.push(`- ${inProgressPhase.title}`),incompleteTasks.length>0){let truncateTask=(task)=>{let text=task.replace("- [ ] ","");return text.length>60?`${text.slice(0,57)}...`:text};compactResult.push(`- Current: ${truncateTask(incompleteTasks[0])}`);let lookahead=incompleteTasks.slice(1,1+Math.min(lookaheadCount,1));for(let task of lookahead)compactResult.push(`- Next: ${truncateTask(task)}`)}else compactResult.push("- (No pending tasks)");if(nextPending)compactResult.push(""),compactResult.push(`## Phase ${nextPending.number} [PENDING]`),compactResult.push(`- ${nextPending.title}`);compactResult.push("[/SWARM PLAN CURSOR]"),output=compactResult.join(`
|
|
980
|
-
`)}return output}var init_extractors=__esm(()=>{init_utils2()});function normalizeToolName(toolName){if(!toolName)return;return toolName.replace(NAMESPACE_PREFIX_PATTERN,"")}function normalizeToolNameLowerCase(toolName){return toolName.replace(NAMESPACE_PREFIX_PATTERN,"").toLowerCase()}var NAMESPACE_PREFIX_PATTERN;var init_normalize_tool_name=__esm(()=>{NAMESPACE_PREFIX_PATTERN=/^[^:]+[:.]/});import{createHash as createHash32}from"node:crypto";import*as fs45 from"node:fs";import*as path72 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file2){if(file2.includes("\x00")||hasControlCharacter(file2))return null;let root=path72.resolve(directory),absolute=path72.resolve(root,file2),relative17=path72.relative(root,absolute).replaceAll("\\","/");if(!relative17||relative17===".."||relative17.startsWith("../")||path72.isAbsolute(relative17))return null;return relative17}function isWithinRoot2(root,candidate){let relative17=path72.relative(root,candidate);return relative17===""||relative17!==".."&&!relative17.startsWith(`..${path72.sep}`)&&!path72.isAbsolute(relative17)}function deletedPathIsContained(canonicalRoot,absolute){let current=path72.dirname(absolute);for(;;){try{let canonical=_internals66.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error49){if(error49.code!=="ENOENT")return!1}let parent=path72.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file2,options={}){if(typeof directory!=="string"||typeof file2!=="string")return{kind:"capture_failed",file:typeof file2==="string"?file2:"",code:"invalid_request",retryable:!1};if(file2.includes("\x00")||hasControlCharacter(file2))return{kind:"capture_failed",file:file2,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file2);if(!normalized)return{kind:"capture_failed",file:file2,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path72.resolve(directory,normalized);try{canonicalRoot=_internals66.realpathSync(path72.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals66.realpathSync(path72.dirname(absolute))}catch(error49){if(error49.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals66.realpathSync(path72.dirname(absolute))}catch(secondError){if(secondError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:secondError.code};secondFailed=!0}if(!secondFailed)canonicalParent=secondObservation;else{try{return _internals66.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals66.lstat(absolute)}catch(error49){if(error49.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals66.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path72.dirname(canonicalTarget)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}catch{return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1}}if(!before.isFile()||!Number.isSafeInteger(before.size)||before.size<0)return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};let openFlags=fs45.constants.O_RDONLY|(process.platform==="win32"?0:fs45.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals66.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals66.open(absolute,openFlags)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals66.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash3=createHash32("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals66.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals66.read(fd,chunk,0,chunk.byteLength,null)}catch(error49){let code=error49.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash3.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals66.fstat(fd,{bigint:!0});if(!sameSnapshot(openedBefore,openedAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};if(totalBytes!==Number(openedBefore.size))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let pathAfter;try{pathAfter=_internals66.stat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!pathAfter.isFile()||!sameSnapshot(openedBefore,pathAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let canonicalAfterRead;try{canonicalAfterRead=_internals66.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path72.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash3.digest("hex")}}finally{if(fd!==void 0)try{_internals66.close(fd)}catch{}}}function reviewerScopeCaptureToFingerprint(result){if(result.kind==="captured_file")return{file:result.file,kind:"file",size:result.size,hash:result.hash};if(result.kind==="captured_deleted")return{file:result.file,kind:"deleted"};return null}function reviewerScopeFileFingerprintsEqual(left,right){return left.file===right.file&&left.kind===right.kind&&(left.kind==="deleted"||right.kind==="file"&&left.size===right.size&&left.hash===right.hash)}var REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES=262144,REVIEWER_SCOPE_CAPTURE_ATTEMPTS=3,REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS=1e4,_internals66;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals66={open:fs45.openSync,fstat:(fd,options)=>fs45.fstatSync(fd,options),read:fs45.readSync,close:fs45.closeSync,lstat:fs45.lstatSync,stat:(path73,options)=>fs45.statSync(path73,options),realpathSync:fs45.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record2=output,nestedRecords=[record2.metadata,record2.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record2,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state)=>NON_SUCCESS_STATES.has(state)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state)=>!knownStates.has(state)))return"non_success";let metadata=nestedRecords[0];if(states.some((state)=>RUNNING_STATES.has(state))||metadata?.background===!0)return"running";if(states.some((state)=>SUCCESS_STATES.has(state)))return"success";if(typeof record2.output==="string")return"success";return Object.keys(record2).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state2()});import*as fs46 from"node:fs";import*as path73 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state}function clearStreak(state){state.nonProgressCalls=0,state.warnIssued=!1,state.denyTelemetryIssued=!1,state.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state){state.armed=!1,state.workspaceBaseline=null,state.needsWorkspaceBaseline=!1,clearStreak(state),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state){if(!state.armed)state.armed=!0,state.needsWorkspaceBaseline=!0,clearStreak(state);_internals67.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool,args2){if(normalizeToolNameLowerCase(tool??"")!=="task")return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs46.readFileSync(path73.join(directory,".swarm","plan.json"),"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan?.phases))return"unknown";for(let phase of plan.phases){if(!Array.isArray(phase?.tasks))continue;for(let task of phase.tasks)if(task?.status==="in_progress")return"open"}return"none"}catch{return"unknown"}}function isWriteToolName(normalizedTool){return WRITE_TOOL_NAMES.includes(normalizedTool)}function positiveInt(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function executionStallAdvisoryText(count){return`EXECUTION STALL: ${count} tool calls with no delegation completion, no file changes, and no status update. STOP investigating; delegate the work or report BLOCKED to the user.`}function executionStallDenialText(count,normalizedTool){return`EXECUTION_STALL: ${count} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals67.now(),state=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state.armed&&now-state.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state);state.lastToolCallAt=now;let role=canonicalDispatchRole(tool,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state)}if(!state.armed)return;state.nonProgressCalls+=1,state.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state.nonProgressCalls>=warnCalls&&!state.warnIssued){state.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state.nonProgressCalls));telemetry.executionStallWarning(sessionID,state.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool,options}=params,denial=null;try{if(options?.enabled===!1)return;let state=stallStates.get(sessionID);if(!state?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state.denyTelemetryIssued){state.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals67.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals67.captureWorkspaceSnapshotAsync(directory);if(!baseline)return{progress:!1,next:current};if(authoritative!==null)return{progress:authoritative.length>0,next:current};if(baseline.gitHead&¤t?.gitHead&&baseline.gitHead!==current.gitHead)return{progress:!0,next:current};let before=new Set(baseline.changedFiles??[]);return{progress:(current?.changedFiles??[]).some((entry)=>!before.has(entry)),next:current}}catch{return{progress:!1,next:baseline}}}async function recordExecutionStallToolAfter(params){let{sessionID,tool,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals67.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state);if(!state.armed)return;if(taskSettled&&_internals67.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state);return}if(progress){clearStreak(state),state.needsWorkspaceBaseline=!0;return}if(state.needsWorkspaceBaseline){state.needsWorkspaceBaseline=!1,state.callsSinceWorkspaceProbe=0;try{state.workspaceBaseline=await _internals67.captureWorkspaceSnapshotAsync(directory)}catch{state.workspaceBaseline=null}return}if(state.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state.callsSinceWorkspaceProbe=0,_internals67.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state);return}let probe2=await probeWorkspaceProgress(directory,state.workspaceBaseline);if(state.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals67;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state2();init_telemetry();init_normalize_tool_name();init_task_result_classifier();init_execution_episode();MUTATING_DELEGATION_ROLES=new Set(["coder","reviewer","test_engineer","security_reviewer"]),EXECUTION_STALL_DENIED_TOOLS=new Set(["read","glob","grep","bash","shell"]),stallStates=new Map,pendingDispatchRoles=new Map;_internals67={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path74 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path74.relative(path74.resolve(cwd),path74.resolve(cwd,filePath)).replace(/\\/g,"/"),{zone}=classifyFile(normalized);if(zone==="config")return!0;let allGlobs=extraGlobs&&extraGlobs.length>0?[...KNOWN_VERIFIER_CONFIG_GLOBS,...extraGlobs]:KNOWN_VERIFIER_CONFIG_GLOBS;for(let glob of allGlobs)if(getGlobMatcher(glob)(normalized))return!0;return!1}function isWriteTool(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isOutsideSwarmDir(filePath,directory){if(!filePath)return!1;let swarmDir=path74.resolve(directory,".swarm"),resolved=path74.resolve(directory,filePath),relative18=path74.relative(swarmDir,resolved);return relative18.startsWith("..")||path74.isAbsolute(relative18)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config2){let budget=config2.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function claimTurnBudget(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),ledger.used+=granted}return accounting.granted+=granted,{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){let ledger=turnLedgers.get(sessionID);if(!ledger)return;let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=Math.max(0,requestedTokens);let granted=Math.max(0,grantedTokens);if(accounting.granted+=granted,ledger.ceilingActive)ledger.used+=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used))}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface){let ledger=turnLedgers.get(sessionID);if(!ledger)return;let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.emitted+=Math.max(0,emittedTokens),accounting.truncated+=Math.max(0,truncatedTokens)}function deductProducerEmission(sessionID,producer,removedTokens){let ledger=turnLedgers.get(sessionID);if(!ledger)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,a])=>({producer,requested:a.requested,granted:a.granted,emitted:a.emitted,truncated:a.truncated,surface:a.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var turnLedgers,MAX_TRACKED_SESSIONS=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&"A_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set2,key){if(set2.has(key))return!1;while(set2.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set2.values().next().value;if(oldest===void 0)break;set2.delete(oldest)}return set2.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals68.observeResolution({modelID,providerID,directory,resolution:resolution.source,aliasKeyClass:resolution.source==="user_provider_model"?"compound":resolution.source==="user_model"?"model":resolution.source==="user_default"?"default":void 0,invalidOverride}),{limit:resolution.tokens,source:classifyModelLimitSource(resolution.source),resolution:resolution.source}}function recordInvalidOverrides(modelID,providerID,configOverrides){if(!configOverrides||typeof configOverrides!=="object")return!1;let normalizedModel=modelID?.trim().toLowerCase(),normalizedCompound=`${providerID??""}/${modelID??""}`.trim().toLowerCase(),relevantInvalid=!1;for(let[key,value]of Object.entries(configOverrides)){if(isUsableConfiguredWindow(value))continue;let keyClass=key==="default"?"default":key.includes("/")?"compound":"model",normalizedKey=key.trim().toLowerCase();if(keyClass==="default"||keyClass==="model"&&normalizedModel!==void 0&&normalizedKey===normalizedModel||keyClass==="compound"&&normalizedKey===normalizedCompound)relevantInvalid=!0;let identity=`${modelID||"unknown"}::${providerID||"unknown"}::${keyClass}::${String(value)}`;if(rememberBoundedModelIdentity(invalidOverrideReports,identity))warn(`[model-limits] context_budget.model_limits.${key}=${String(value)} for ${modelID||"(no model)"}@${providerID||"(no provider)"} is not a usable limit (finite number ≥ 1); skipping it — not coercing.`,{modelID,providerID,keyClass,value})}return relevantInvalid}function warnNormalizedKeyCollisions(configOverrides){let byNormalized=new Map;for(let key of Object.keys(configOverrides)){let normalized=key.trim().toLowerCase();byNormalized.set(normalized,[...byNormalized.get(normalized)??[],key])}for(let[normalized,keys]of byNormalized){if(keys.length<2)continue;let identity=`collision::${normalized}`;if(!rememberBoundedModelIdentity(invalidOverrideReports,identity))continue;warn(`[model-limits] context_budget.model_limits has ${keys.length} keys that normalize identically (${keys.join(", ")}); only the last one in config order takes effect under normalized matching.`,{keys})}}function findNativeLimit(modelID){if(NATIVE_MODEL_LIMITS[modelID]!==void 0)return NATIVE_MODEL_LIMITS[modelID];let bestMatch;for(let key of Object.keys(NATIVE_MODEL_LIMITS))if(modelID.startsWith(key)){if(!bestMatch||key.length>bestMatch.length)bestMatch=key}return bestMatch?NATIVE_MODEL_LIMITS[bestMatch]:void 0}function logFirstCall(modelID,providerID,source,limit){let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(rememberBoundedModelIdentity(loggedFirstCalls,key))log(`[model-limits] Resolved limit for ${modelID||"(no model)"}@${providerID||"(no provider)"}: ${limit} (source: ${source})`)}function maybeWarnUndersizedDefault(modelID,providerID,source,resolvedTokens,liveContextLimit){if(source!=="user_default")return;if(!isUsableContextWindow(liveContextLimit))return;let liveTokens=Math.floor(liveContextLimit);if(liveTokens<=resolvedTokens)return;let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(!rememberBoundedModelIdentity(warnedUndersizedDefaults,key))return;warn(`[model-limits] context_budget.model_limits.default=${resolvedTokens} is below live model window ${liveTokens} for ${modelID||"(no model)"}@${providerID||"(no provider)"}; keeping the configured default.`,{modelID,providerID,resolvedTokens,liveTokens,source})}var NATIVE_MODEL_LIMITS,PROVIDER_CAPS,MAX_TRACKED_MODEL_IDENTITIES=256,loggedFirstCalls,warnedUndersizedDefaults,SOURCE_CLASS_BY_RESOLUTION,_internals68,invalidOverrideReports;var init_model_limits=__esm(()=>{init_learning_health();init_utils();NATIVE_MODEL_LIMITS={"claude-sonnet-4":200000,"claude-opus-4":200000,"claude-haiku-4":200000,"gpt-5":400000,"gpt-5.1-codex":400000,"gpt-5.1":264000,"gpt-4.1":1047576,"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,o3:200000,"o4-mini":200000,"deepseek-r1":163840,"deepseek-chat":163840,"qwen3.5":131072,"MiniMax-M3":1e6,"MiniMax-M2.7":204800},PROVIDER_CAPS={copilot:128000,"github-copilot":128000};loggedFirstCalls=new Set,warnedUndersizedDefaults=new Set;SOURCE_CLASS_BY_RESOLUTION={user_provider_model:"override",user_model:"override",user_default:"override",live_model_limit:"host",static_provider_cap:"provider_cap",static_native:"native",static_default:"fallback"};_internals68={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map2,sessionId,messageId){map2.delete(sessionId),map2.set(sessionId,messageId);while(map2.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map2.keys().next().value;if(stalest===void 0)break;map2.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
|
|
980
|
+
`)}return output}var init_extractors=__esm(()=>{init_utils2()});import{createHash as createHash32}from"node:crypto";import*as fs45 from"node:fs";import*as path72 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file2){if(file2.includes("\x00")||hasControlCharacter(file2))return null;let root=path72.resolve(directory),absolute=path72.resolve(root,file2),relative17=path72.relative(root,absolute).replaceAll("\\","/");if(!relative17||relative17===".."||relative17.startsWith("../")||path72.isAbsolute(relative17))return null;return relative17}function isWithinRoot2(root,candidate){let relative17=path72.relative(root,candidate);return relative17===""||relative17!==".."&&!relative17.startsWith(`..${path72.sep}`)&&!path72.isAbsolute(relative17)}function deletedPathIsContained(canonicalRoot,absolute){let current=path72.dirname(absolute);for(;;){try{let canonical=_internals66.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error49){if(error49.code!=="ENOENT")return!1}let parent=path72.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file2,options={}){if(typeof directory!=="string"||typeof file2!=="string")return{kind:"capture_failed",file:typeof file2==="string"?file2:"",code:"invalid_request",retryable:!1};if(file2.includes("\x00")||hasControlCharacter(file2))return{kind:"capture_failed",file:file2,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file2);if(!normalized)return{kind:"capture_failed",file:file2,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path72.resolve(directory,normalized);try{canonicalRoot=_internals66.realpathSync(path72.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals66.realpathSync(path72.dirname(absolute))}catch(error49){if(error49.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals66.realpathSync(path72.dirname(absolute))}catch(secondError){if(secondError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:secondError.code};secondFailed=!0}if(!secondFailed)canonicalParent=secondObservation;else{try{return _internals66.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals66.lstat(absolute)}catch(error49){if(error49.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals66.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path72.dirname(canonicalTarget)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}catch{return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1}}if(!before.isFile()||!Number.isSafeInteger(before.size)||before.size<0)return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};let openFlags=fs45.constants.O_RDONLY|(process.platform==="win32"?0:fs45.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals66.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals66.open(absolute,openFlags)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals66.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash3=createHash32("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals66.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals66.read(fd,chunk,0,chunk.byteLength,null)}catch(error49){let code=error49.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash3.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals66.fstat(fd,{bigint:!0});if(!sameSnapshot(openedBefore,openedAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};if(totalBytes!==Number(openedBefore.size))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let pathAfter;try{pathAfter=_internals66.stat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!pathAfter.isFile()||!sameSnapshot(openedBefore,pathAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let canonicalAfterRead;try{canonicalAfterRead=_internals66.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path72.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash3.digest("hex")}}finally{if(fd!==void 0)try{_internals66.close(fd)}catch{}}}function reviewerScopeCaptureToFingerprint(result){if(result.kind==="captured_file")return{file:result.file,kind:"file",size:result.size,hash:result.hash};if(result.kind==="captured_deleted")return{file:result.file,kind:"deleted"};return null}function reviewerScopeFileFingerprintsEqual(left,right){return left.file===right.file&&left.kind===right.kind&&(left.kind==="deleted"||right.kind==="file"&&left.size===right.size&&left.hash===right.hash)}var REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES=262144,REVIEWER_SCOPE_CAPTURE_ATTEMPTS=3,REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS=1e4,_internals66;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals66={open:fs45.openSync,fstat:(fd,options)=>fs45.fstatSync(fd,options),read:fs45.readSync,close:fs45.closeSync,lstat:fs45.lstatSync,stat:(path73,options)=>fs45.statSync(path73,options),realpathSync:fs45.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record2=output,nestedRecords=[record2.metadata,record2.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record2,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state)=>NON_SUCCESS_STATES.has(state)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state)=>!knownStates.has(state)))return"non_success";let metadata=nestedRecords[0];if(states.some((state)=>RUNNING_STATES.has(state))||metadata?.background===!0)return"running";if(states.some((state)=>SUCCESS_STATES.has(state)))return"success";if(typeof record2.output==="string")return"success";return Object.keys(record2).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state2()});import*as fs46 from"node:fs";import*as path73 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state}function clearStreak(state){state.nonProgressCalls=0,state.warnIssued=!1,state.denyTelemetryIssued=!1,state.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state){state.armed=!1,state.workspaceBaseline=null,state.needsWorkspaceBaseline=!1,clearStreak(state),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state){if(!state.armed)state.armed=!0,state.needsWorkspaceBaseline=!0,clearStreak(state);_internals67.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool,args2){if(!isTaskToolId(tool??""))return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs46.readFileSync(path73.join(directory,".swarm","plan.json"),"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan?.phases))return"unknown";for(let phase of plan.phases){if(!Array.isArray(phase?.tasks))continue;for(let task of phase.tasks)if(task?.status==="in_progress")return"open"}return"none"}catch{return"unknown"}}function isWriteToolName(normalizedTool){return WRITE_TOOL_NAMES.includes(normalizedTool)}function positiveInt(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function executionStallAdvisoryText(count){return`EXECUTION STALL: ${count} tool calls with no delegation completion, no file changes, and no status update. STOP investigating; delegate the work or report BLOCKED to the user.`}function executionStallDenialText(count,normalizedTool){return`EXECUTION_STALL: ${count} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals67.now(),state=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state.armed&&now-state.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state);state.lastToolCallAt=now;let role=canonicalDispatchRole(tool,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state)}if(!state.armed)return;state.nonProgressCalls+=1,state.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state.nonProgressCalls>=warnCalls&&!state.warnIssued){state.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state.nonProgressCalls));telemetry.executionStallWarning(sessionID,state.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool,options}=params,denial=null;try{if(options?.enabled===!1)return;let state=stallStates.get(sessionID);if(!state?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state.denyTelemetryIssued){state.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals67.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals67.captureWorkspaceSnapshotAsync(directory);if(!baseline)return{progress:!1,next:current};if(authoritative!==null)return{progress:authoritative.length>0,next:current};if(baseline.gitHead&¤t?.gitHead&&baseline.gitHead!==current.gitHead)return{progress:!0,next:current};let before=new Set(baseline.changedFiles??[]);return{progress:(current?.changedFiles??[]).some((entry)=>!before.has(entry)),next:current}}catch{return{progress:!1,next:baseline}}}async function recordExecutionStallToolAfter(params){let{sessionID,tool,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals67.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state);if(!state.armed)return;if(taskSettled&&_internals67.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state);return}if(progress){clearStreak(state),state.needsWorkspaceBaseline=!0;return}if(state.needsWorkspaceBaseline){state.needsWorkspaceBaseline=!1,state.callsSinceWorkspaceProbe=0;try{state.workspaceBaseline=await _internals67.captureWorkspaceSnapshotAsync(directory)}catch{state.workspaceBaseline=null}return}if(state.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state.callsSinceWorkspaceProbe=0,_internals67.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state);return}let probe2=await probeWorkspaceProgress(directory,state.workspaceBaseline);if(state.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals67;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state2();init_telemetry();init_normalize_tool_name();init_task_result_classifier();init_execution_episode();MUTATING_DELEGATION_ROLES=new Set(["coder","reviewer","test_engineer","security_reviewer"]),EXECUTION_STALL_DENIED_TOOLS=new Set(["read","glob","grep","bash","shell"]),stallStates=new Map,pendingDispatchRoles=new Map;_internals67={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path74 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path74.relative(path74.resolve(cwd),path74.resolve(cwd,filePath)).replace(/\\/g,"/"),{zone}=classifyFile(normalized);if(zone==="config")return!0;let allGlobs=extraGlobs&&extraGlobs.length>0?[...KNOWN_VERIFIER_CONFIG_GLOBS,...extraGlobs]:KNOWN_VERIFIER_CONFIG_GLOBS;for(let glob of allGlobs)if(getGlobMatcher(glob)(normalized))return!0;return!1}function isWriteTool(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isOutsideSwarmDir(filePath,directory){if(!filePath)return!1;let swarmDir=path74.resolve(directory,".swarm"),resolved=path74.resolve(directory,filePath),relative18=path74.relative(swarmDir,resolved);return relative18.startsWith("..")||path74.isAbsolute(relative18)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config2){let budget=config2.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function claimTurnBudget(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),ledger.used+=granted}return accounting.granted+=granted,{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){let ledger=turnLedgers.get(sessionID);if(!ledger)return;let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=Math.max(0,requestedTokens);let granted=Math.max(0,grantedTokens);if(accounting.granted+=granted,ledger.ceilingActive)ledger.used+=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used))}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface){let ledger=turnLedgers.get(sessionID);if(!ledger)return;let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.emitted+=Math.max(0,emittedTokens),accounting.truncated+=Math.max(0,truncatedTokens)}function deductProducerEmission(sessionID,producer,removedTokens){let ledger=turnLedgers.get(sessionID);if(!ledger)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,a])=>({producer,requested:a.requested,granted:a.granted,emitted:a.emitted,truncated:a.truncated,surface:a.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var turnLedgers,MAX_TRACKED_SESSIONS=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&"A_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set2,key){if(set2.has(key))return!1;while(set2.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set2.values().next().value;if(oldest===void 0)break;set2.delete(oldest)}return set2.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals68.observeResolution({modelID,providerID,directory,resolution:resolution.source,aliasKeyClass:resolution.source==="user_provider_model"?"compound":resolution.source==="user_model"?"model":resolution.source==="user_default"?"default":void 0,invalidOverride}),{limit:resolution.tokens,source:classifyModelLimitSource(resolution.source),resolution:resolution.source}}function recordInvalidOverrides(modelID,providerID,configOverrides){if(!configOverrides||typeof configOverrides!=="object")return!1;let normalizedModel=modelID?.trim().toLowerCase(),normalizedCompound=`${providerID??""}/${modelID??""}`.trim().toLowerCase(),relevantInvalid=!1;for(let[key,value]of Object.entries(configOverrides)){if(isUsableConfiguredWindow(value))continue;let keyClass=key==="default"?"default":key.includes("/")?"compound":"model",normalizedKey=key.trim().toLowerCase();if(keyClass==="default"||keyClass==="model"&&normalizedModel!==void 0&&normalizedKey===normalizedModel||keyClass==="compound"&&normalizedKey===normalizedCompound)relevantInvalid=!0;let identity=`${modelID||"unknown"}::${providerID||"unknown"}::${keyClass}::${String(value)}`;if(rememberBoundedModelIdentity(invalidOverrideReports,identity))warn(`[model-limits] context_budget.model_limits.${key}=${String(value)} for ${modelID||"(no model)"}@${providerID||"(no provider)"} is not a usable limit (finite number ≥ 1); skipping it — not coercing.`,{modelID,providerID,keyClass,value})}return relevantInvalid}function warnNormalizedKeyCollisions(configOverrides){let byNormalized=new Map;for(let key of Object.keys(configOverrides)){let normalized=key.trim().toLowerCase();byNormalized.set(normalized,[...byNormalized.get(normalized)??[],key])}for(let[normalized,keys]of byNormalized){if(keys.length<2)continue;let identity=`collision::${normalized}`;if(!rememberBoundedModelIdentity(invalidOverrideReports,identity))continue;warn(`[model-limits] context_budget.model_limits has ${keys.length} keys that normalize identically (${keys.join(", ")}); only the last one in config order takes effect under normalized matching.`,{keys})}}function findNativeLimit(modelID){if(NATIVE_MODEL_LIMITS[modelID]!==void 0)return NATIVE_MODEL_LIMITS[modelID];let bestMatch;for(let key of Object.keys(NATIVE_MODEL_LIMITS))if(modelID.startsWith(key)){if(!bestMatch||key.length>bestMatch.length)bestMatch=key}return bestMatch?NATIVE_MODEL_LIMITS[bestMatch]:void 0}function logFirstCall(modelID,providerID,source,limit){let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(rememberBoundedModelIdentity(loggedFirstCalls,key))log(`[model-limits] Resolved limit for ${modelID||"(no model)"}@${providerID||"(no provider)"}: ${limit} (source: ${source})`)}function maybeWarnUndersizedDefault(modelID,providerID,source,resolvedTokens,liveContextLimit){if(source!=="user_default")return;if(!isUsableContextWindow(liveContextLimit))return;let liveTokens=Math.floor(liveContextLimit);if(liveTokens<=resolvedTokens)return;let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(!rememberBoundedModelIdentity(warnedUndersizedDefaults,key))return;warn(`[model-limits] context_budget.model_limits.default=${resolvedTokens} is below live model window ${liveTokens} for ${modelID||"(no model)"}@${providerID||"(no provider)"}; keeping the configured default.`,{modelID,providerID,resolvedTokens,liveTokens,source})}var NATIVE_MODEL_LIMITS,PROVIDER_CAPS,MAX_TRACKED_MODEL_IDENTITIES=256,loggedFirstCalls,warnedUndersizedDefaults,SOURCE_CLASS_BY_RESOLUTION,_internals68,invalidOverrideReports;var init_model_limits=__esm(()=>{init_learning_health();init_utils();NATIVE_MODEL_LIMITS={"claude-sonnet-4":200000,"claude-opus-4":200000,"claude-haiku-4":200000,"gpt-5":400000,"gpt-5.1-codex":400000,"gpt-5.1":264000,"gpt-4.1":1047576,"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,o3:200000,"o4-mini":200000,"deepseek-r1":163840,"deepseek-chat":163840,"qwen3.5":131072,"MiniMax-M3":1e6,"MiniMax-M2.7":204800},PROVIDER_CAPS={copilot:128000,"github-copilot":128000};loggedFirstCalls=new Set,warnedUndersizedDefaults=new Set;SOURCE_CLASS_BY_RESOLUTION={user_provider_model:"override",user_model:"override",user_default:"override",live_model_limit:"host",static_provider_cap:"provider_cap",static_native:"native",static_default:"fallback"};_internals68={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map2,sessionId,messageId){map2.delete(sessionId),map2.set(sessionId,messageId);while(map2.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map2.keys().next().value;if(stalest===void 0)break;map2.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
|
|
981
981
|
`)}function getMostRecentAssistantText(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="assistant")return getMessageText(messages[i]);return""}function isTransientProviderFailureText(text){if(!text.trim())return!1;if(!/provider[_\s-]?unavailable|network\s+connection\s+lost|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN|connection\s+reset|connection\s+refused/i.test(text))return!1;let status=extractStatusCode(text);return status!==null&&TRANSIENT_STATUS_CODES.has(status)||TRANSIENT_MODEL_ERROR_PATTERN.test(text)}function getProviderFailureFingerprint(text){return String(hashArgs({providerFailure:text.slice(-4000)}))}function createMessagesTransformHandler(ctx){let{effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId}=ctx;return async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastMessage=messages[messages.length-1],sessionId=lastMessage.info?.sessionID;if(!sessionId)return;let session=swarmState.agentSessions.get(sessionId),activeAgent=swarmState.activeAgent.get(sessionId)??session?.agentName,targetAgent=[...messages].reverse().find((message)=>message.info?.role==="user"&&typeof message.info.agent==="string"&&message.info.agent.length>0)?.info.agent;{let configuredModel=targetAgent?ctx.resolveAgentModel?.(targetAgent):void 0,targetModel=configuredModel?parseAgentModel(configuredModel):void 0,{modelID}=targetModel??extractModelInfo(messages);if(modelID&&isLowCapabilityModel(modelID))for(let msg of messages){if(msg.info?.role!=="system")continue;for(let part of msg.parts)try{if(part==null)continue;if(part.type!=="text"||typeof part.text!=="string")continue;if(!part.text.includes("<!-- BEHAVIORAL_GUIDANCE_START -->"))continue;part.text=part.text.replace(/<!--\s*BEHAVIORAL_GUIDANCE_START\s*-->[\s\S]*?<!--\s*BEHAVIORAL_GUIDANCE_END\s*-->/g,"[Enforcement: programmatic gates active]")}catch(error49){log("[Guardrails] behavioral guidance replacement failed",{error:error49 instanceof Error?error49.message:String(error49)})}}}let isArchitectSession=activeAgent?stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME:session?stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME:!1;if(isArchitectSession&&session){let{modelID,providerID}=extractModelInfo(messages);if(modelID){let observedFull=providerID?`${providerID}/${modelID}`:modelID,previousObserved=session.lastObservedModel;if(session.sessionRehydratedAt>0&&session.model_fallback_index===0&&previousObserved&&previousObserved!==observedFull&&!session.resumeModelAdvisoryDone)pushAdvisory(session,`MODEL CHANGED ACROSS RESUME: this run previously observed model "${previousObserved}"; the active model is now "${observedFull}". If this switch was unintended, re-select the intended model (or use /swarm handoff) before continuing.`),session.resumeModelAdvisoryDone=!0;if(!session.configModelAdvisoryDone&&session.model_fallback_index===0){let configuredArchitect=getSwarmAgents()?.architect?.model;if(configuredArchitect&&configuredArchitect!==observedFull&&configuredArchitect!==modelID)pushAdvisory(session,`MODEL CONFIG NOTE: your config pins the architect to "${configuredArchitect}", but the UI has "${observedFull}" active. The UI selection wins for the primary/architect role (its configured model is intentionally not applied), so this difference is expected — switch the UI model if you meant to run "${configuredArchitect}".`),session.configModelAdvisoryDone=!0}session.lastObservedModel=observedFull,session.lastObservedProviderID=providerID}}let guidanceCarriers=findGuidanceCarriers(messages);if(isArchitectSession&&session){let lastAssistantText=getMostRecentAssistantText(messages);if(isTransientProviderFailureText(lastAssistantText)){let fingerprint2=getProviderFailureFingerprint(lastAssistantText),alreadyPending=session.pendingAdvisoryMessages?.some((message)=>message.startsWith(TRANSIENT_PROVIDER_RECOVERY_TAG)),alreadyInjected=guidanceCarriers.some((message)=>getMessageText(message).includes(TRANSIENT_PROVIDER_RECOVERY_TAG));if(session.lastProviderRecoveryFingerprint!==fingerprint2&&!alreadyPending&&!alreadyInjected)pushAdvisory(session,`${TRANSIENT_PROVIDER_RECOVERY_TAG}: The previous Architect response appears to have been interrupted by a transient provider/network error. On this turn, continue from the last stable step, inspect current repo or plan state if needed, and keep working instead of treating the interrupted response as task completion.`),session.lastProviderRecoveryFingerprint=fingerprint2}else session.lastProviderRecoveryFingerprint=void 0}if(isArchitectSession){let countedMsgId=lastCountedAssistantMsgId.get(sessionId);if(countedMsgId!==void 0){let countedIdx=messages.findIndex((m)=>m.info?.id===countedMsgId);if(countedIdx<0)lastCountedAssistantMsgId.delete(sessionId);else if(messages.slice(countedIdx+1).some((m)=>m.info?.role==="user"))consecutiveNoToolTurns.set(sessionId,0),lastCountedAssistantMsgId.delete(sessionId)}let lastAssistantMsg;for(let i=messages.length-1;i>=0;i--)if(messages[i].info?.role==="assistant"){lastAssistantMsg=messages[i];break}if(lastAssistantMsg)if(lastAssistantMsg.parts?.some((part)=>part.type==="tool_use"))consecutiveNoToolTurns.set(sessionId,0);else{let textLen=lastAssistantMsg.parts?.filter((p)=>p.type==="text"&&typeof p.text==="string").reduce((sum,p)=>sum+p.text.length,0)??0,lastAssistantMsgId=lastAssistantMsg.info?.id,countsAsMedium=textLen>=RUNAWAY_MEDIUM_MIN&&textLen<=4000&&typeof lastAssistantMsgId==="string"&&lastAssistantMsgId.length>0&&isExecutionEpisodeArmed(sessionId);if(countsAsMedium&&lastAssistantMsgId)rememberCountedAssistantMsg(lastCountedAssistantMsgId,sessionId,lastAssistantMsgId);if(textLen>4000||countsAsMedium){let count=(consecutiveNoToolTurns.get(sessionId)??0)+1;consecutiveNoToolTurns.set(sessionId,count);let maxTurns=cfg.runaway_output_max_turns;if(count>=maxTurns){let stopCarrier=ensureGuidanceCarrier(messages,"guardrails");if(!messageTextOf(stopCarrier).includes("RUNAWAY OUTPUT STOP"))prependGuidanceText(stopCarrier,"guardrails",`[RUNAWAY OUTPUT STOP]
|
|
982
982
|
You have produced ${count} consecutive responses without using any tools. You MUST call a tool in your next response.
|
|
983
983
|
[/RUNAWAY OUTPUT STOP]
|
|
@@ -1107,7 +1107,7 @@ Usage through swarm_command: \`/swarm review [--base <ref> | --range <from..to|f
|
|
|
1107
1107
|
`).replace(/\r/g,`
|
|
1108
1108
|
`),lines=normalized.split(`
|
|
1109
1109
|
`),minIndent=Number.POSITIVE_INFINITY;for(let line of lines){if(line.trim().length===0)continue;let indent=line.match(/^[ \t]*/)?.[0].length??0;if(indent<minIndent)minIndent=indent}if(minIndent===0||!Number.isFinite(minIndent))return normalized;return lines.map((line)=>line.length>=minIndent?line.slice(minIndent):line).join(`
|
|
1110
|
-
`)}function detectLoop(sessionId,toolName,args2){if(
|
|
1110
|
+
`)}function detectLoop(sessionId,toolName,args2){if(!isTaskToolId(toolName))return{looping:!1,count:0,pattern:""};let session=swarmState.agentSessions.get(sessionId);if(!session)return{looping:!1,count:0,pattern:""};if(!session.loopDetectionWindow)session.loopDetectionWindow=[];let argsRecord=args2!=null&&typeof args2==="object"&&!Array.isArray(args2)?args2:void 0,hash3=createActionIdentity({tool:toolName,args:argsRecord}).pattern,now=Date.now();if(session.loopDetectionWindow.push({hash:hash3,timestamp:now}),session.loopDetectionWindow.length>10)session.loopDetectionWindow.shift();let window2=session.loopDetectionWindow,consecutiveCount=0;for(let i=window2.length-1;i>=0;i--)if(window2[i].hash===hash3)consecutiveCount++;else break;return{looping:consecutiveCount>=3,count:consecutiveCount,pattern:hash3}}var init_loop_detector=__esm(()=>{init_action_identity();init_state2();init_normalize_tool_name()});var require_0=__commonJS((exports,module)=>{module.exports=function(fn2){return function(){return fn2.apply(null,arguments)}}});var require_1=__commonJS((exports,module)=>{module.exports=function(fn2){return function(a){return fn2.apply(null,arguments)}}});var require_2=__commonJS((exports,module)=>{module.exports=function(fn2){return function(a,b){return fn2.apply(null,arguments)}}});var require_3=__commonJS((exports,module)=>{module.exports=function(fn2){return function(a,b,c){return fn2.apply(null,arguments)}}});var require_4=__commonJS((exports,module)=>{module.exports=function(fn2){return function(a,b,c,d){return fn2.apply(null,arguments)}}});var require_5=__commonJS((exports,module)=>{module.exports=function(fn2){return function(a,b,c,d,e){return fn2.apply(null,arguments)}}});var require_N=__commonJS((exports,module)=>{var arityFn=[require_0(),require_1(),require_2(),require_3(),require_4(),require_5()];module.exports=function(fn2,n){if(n&&n<=5)return arityFn[n](fn2);else return fn2}});var require_compose_function=__commonJS((exports,module)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.default=compose;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _arityN=require_N(),_arityN2=_interopRequireDefault(_arityN),compose2=function(f,g){return function(){return f(g.apply(void 0,arguments))}};function compose(){for(var _len=arguments.length,functions=Array(_len),_key=0;_key<_len;_key++)functions[_key]=arguments[_key];var funcs=functions.filter(function(fn2){return typeof fn2==="function"}),lastIdx=funcs.length-1,arity2=0;if(funcs.length<=0)throw Error("No funcs passed");if(lastIdx>=0&&funcs[lastIdx])arity2=funcs[lastIdx].length;return(0,_arityN2.default)(funcs.reduce(compose2),arity2)}module.exports=exports.default});var require_shell_lexer=__commonJS((exports,module)=>{var compose=require_compose_function(),posixShellLexer=(mode,options)=>({lex(){let tk=this.tokenizer.next().value,tkType=tk.originalType,text=tk.value;if(this.yytext={text},tk.expansion)this.yytext.expansion=tk.expansion;if(tk.originalText)this.yytext.originalText=tk.originalText;if(tk.type)this.yytext.type=tk.type;if(tk.maybeSimpleCommandName)this.yytext.maybeSimpleCommandName=tk.maybeSimpleCommandName;if(tk.joined)this.yytext.joined=tk.joined;if(tk.fieldIdx!==void 0)this.yytext.fieldIdx=tk.fieldIdx;if(options.insertLOC&&tk.loc)this.yytext.loc=tk.loc;if(tk.loc)this.yylineno=tk.loc.start.row-1;return tkType},setInput(source){let tokenizer=mode.tokenizer(options),previousPhases=[tokenizer],phases=[tokenizer].concat(mode.lexerPhases.map((phase)=>{let ph=phase(options,mode,previousPhases);return previousPhases=previousPhases.concat(ph),ph})),tokenize=compose.apply(null,phases.reverse());this.tokenizer=tokenize(source)}});module.exports=posixShellLexer});var require_logger_phase=__commonJS((exports,module)=>{var logger=(name)=>()=>function*(tokens){for(let tk of tokens){if(!tk)console.log(`In ${name} token null.`);console.log(name,"<<<",tk,">>>"),yield tk}};module.exports=logger});var require_has_own_property=__commonJS((exports,module)=>{var _hasOwnProperty=Object.prototype.hasOwnProperty;module.exports=function(obj,prop){return _hasOwnProperty.call(obj,prop)}});var require_filter_obj=__commonJS((exports,module)=>{module.exports=function(obj,predicate){var ret={},keys=Object.keys(obj),isArr=Array.isArray(predicate);for(var i=0;i<keys.length;i++){var key2=keys[i],val=obj[key2];if(isArr?predicate.indexOf(key2)!==-1:predicate(key2,val,obj))ret[key2]=val}return ret}});var require_operators=__commonJS((exports,module)=>{var operators={"&":"AND","|":"PIPE","(":"OPEN_PAREN",")":"CLOSE_PAREN",">":"GREAT","<":"LESS","&&":"AND_IF","||":"OR_IF",";;":"DSEMI","<<":"DLESS",">>":"DGREAT","<&":"LESSAND",">&":"GREATAND","<>":"LESSGREAT","<<-":"DLESSDASH",">|":"CLOBBER",";":"SEMICOLON"};module.exports=operators});var require_tokens=__commonJS((exports)=>{var hasOwnProperty=require_has_own_property(),filter=require_filter_obj(),operators=require_operators();class Token{constructor(fields){let definedFields=filter(fields,(key2,value)=>value!==void 0);if(Object.assign(this,definedFields),this._===void 0)this._={}}is(type){return this.type===type}appendTo(chunk){return new Token(Object.assign({},this,{value:this.value+chunk}))}changeTokenType(type,value){return new Token({type,value,loc:this.loc,_:this._,expansion:this.expansion})}setValue(value){return new Token(Object.assign({},this,{value}))}alterValue(value){return new Token(Object.assign({},this,{value,originalText:this.originalText||this.value}))}addExpansions(){return new Token(Object.assign({},this,{expansion:[]}))}setExpansions(expansion){return new Token(Object.assign({},this,{expansion}))}}exports.token=(args2)=>new Token(args2);function mkToken(type,value,loc,expansion){let tk=new Token({type,value,loc});if(expansion&&expansion.length)tk.expansion=expansion;return tk}exports.mkToken=mkToken;exports.mkFieldSplitToken=function(joinedTk,value,fieldIdx){return new Token({type:joinedTk.type,value,joined:joinedTk.value,fieldIdx,loc:joinedTk.loc,expansion:joinedTk.expansion,originalText:joinedTk.originalText})};exports.appendTo=(tk,chunk)=>tk.appendTo(chunk);exports.changeTokenType=(tk,type,value)=>tk.changeTokenType(type,value);exports.setValue=(tk,value)=>tk.setValue(value);exports.alterValue=(tk,value)=>tk.alterValue(value);exports.addExpansions=(tk)=>tk.addExpansions();exports.setExpansions=(tk,expansion)=>tk.setExpansions(expansion);exports.tokenOrEmpty=function(state){if(state.current!==""&&state.current!==`
|
|
1111
1111
|
`){let expansion=(state.expansion||[]).map((xp)=>{return Object.assign({},xp,{loc:{start:xp.loc.start.char-state.loc.start.char,end:xp.loc.end.char-state.loc.start.char}})});return[mkToken("TOKEN",state.current,{start:Object.assign({},state.loc.start),end:Object.assign({},state.loc.previous)},expansion)]}return[]};exports.operatorTokens=function(state){return[mkToken(operators[state.current],state.current,{start:Object.assign({},state.loc.start),end:Object.assign({},state.loc.previous)})]};exports.newLine=function(){return mkToken("NEWLINE",`
|
|
1112
1112
|
`)};exports.continueToken=function(expectedChar){return mkToken("CONTINUE",expectedChar)};exports.eof=function(){return mkToken("EOF","")};exports.isPartOfOperator=function(text){return Object.keys(operators).some((op)=>op.slice(0,text.length)===text)};exports.isOperator=function(text){return hasOwnProperty(operators,text)};exports.applyTokenizerVisitor=(visitor)=>(tk,idx,iterable)=>{if(hasOwnProperty(visitor,tk.type)){let visit=visitor[tk.type];return visit(tk,iterable)}if(hasOwnProperty(visitor,"defaultMethod")){let visit=visitor.defaultMethod;return visit(tk,iterable)}return tk}});var require_is_valid_name=__commonJS((exports,module)=>{module.exports=function(text){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(text)}});var require_curry=__commonJS((exports,module)=>{var slice=Array.prototype.slice,toArray=function(a){return slice.call(a)},tail=function(a){return slice.call(a,1)},createFn=function(fn2,args2,totalArity){var remainingArity=totalArity-args2.length;switch(remainingArity){case 0:return function(){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 1:return function(a){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 2:return function(a,b){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 3:return function(a,b,c){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 4:return function(a,b,c,d){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 5:return function(a,b,c,d,e){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 6:return function(a,b,c,d,e,f){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 7:return function(a,b,c,d,e,f,g){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 8:return function(a,b,c,d,e,f,g,h){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 9:return function(a,b,c,d,e,f,g,h,i){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};case 10:return function(a,b,c,d,e,f,g,h,i,j){return processInvocation(fn2,concatArgs(args2,arguments),totalArity)};default:return createEvalFn(fn2,args2,remainingArity)}},concatArgs=function(args1,args2){return args1.concat(toArray(args2))},createEvalFn=function(fn,args,arity){var argList=makeArgList(arity),fnStr="false||function("+argList+"){ return processInvocation(fn, concatArgs(args, arguments)); }";return eval(fnStr)},makeArgList=function(len){var a=[];for(var i=0;i<len;i+=1)a.push("a"+i.toString());return a.join(",")},trimArrLength=function(arr,length){if(arr.length>length)return arr.slice(0,length);else return arr},processInvocation=function(fn2,argsArr,totalArity){if(argsArr=trimArrLength(argsArr,totalArity),argsArr.length===totalArity)return fn2.apply(null,argsArr);return createFn(fn2,argsArr,totalArity)},curry=function(fn2){return createFn(fn2,[],fn2.length)};curry.to=curry(function(arity2,fn2){return createFn(fn2,[],arity2)});curry.adaptTo=curry(function(num,fn2){return curry.to(num,function(context){var args2=tail(arguments).concat(context);return fn2.apply(this,args2)})});curry.adapt=function(fn2){return curry.adaptTo(fn2.length,fn2)};module.exports=curry});var require_iterable_transform_replace=__commonJS((exports,module)=>{function _interopDefault(ex){return ex&&typeof ex==="object"&&"default"in ex?ex.default:ex}var curry=_interopDefault(require_curry());function replace(oldItem,newItem,array2){return array2.map((item)=>{if(item===oldItem)return newItem;return item})}var main=curry(replace);module.exports=main});var require_utils2=__commonJS((exports)=>{exports.loggerPhase=require_logger_phase();exports.tokens=require_tokens();exports.isValidName=require_is_valid_name();exports.replaceRule=require_iterable_transform_replace()});var require_identity_function=__commonJS((exports,module)=>{module.exports=function(x){return x}});var require_is_iterable=__commonJS((exports,module)=>{module.exports=function(val){return typeof Symbol<"u"&&Symbol&&"iterator"in Symbol&&val!=null&&typeof val[Symbol.iterator]==="function"}});var require_map_iterable=__commonJS((exports,module)=>{var curry=require_curry(),isIterable=require_is_iterable();function initDefault(data){return data}function map2(options,data){if(typeof options!=="function"&&(typeof options!=="object"||options===null))throw TypeError("Callback argument must be a function or option object");if(!isIterable(data))throw TypeError("Data argument must be an iterable");let idx=0,init=options.init||initDefault,callback=options.callback||options,ctx=init(data),dataIterator=data[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){let item=dataIterator.next();if(!item.done)item.value=callback(item.value,idx++,ctx);return item}}}module.exports=curry(map2)});var require_object_values=__commonJS((exports,module)=>{module.exports=function(obj){var keys=Object.keys(obj),ret=[];for(var i=0;i<keys.length;i++)ret.push(obj[keys[i]]);return ret}});var require_transform_spread_iterable=__commonJS((exports,module)=>{function*spread(source){for(let item of source)if(typeof item[Symbol.iterator]==="function")yield*item;else yield item}module.exports=spread});var require_alias_substitution=__commonJS((exports,module)=>{var compose=require_compose_function(),identity=require_identity_function(),map2=require_map_iterable(),values=require_object_values(),merge2=require_transform_spread_iterable(),tokens=require_tokens(),expandAlias=(preAliasLexer,resolveAlias,reservedWords)=>{function*tryExpandToken(token,expandingAliases){if(expandingAliases.indexOf(token.value)!==-1){yield token;return}let result=resolveAlias(token.value);if(result===void 0)yield token;else for(let newToken of preAliasLexer(result))if(newToken.is("WORD")||reservedWords.some((word)=>newToken.is(word)))yield*tryExpandToken(newToken,expandingAliases.concat(token.value));else if(!newToken.is("EOF"))yield newToken}function expandToken(tk){return Array.from(tryExpandToken(tk,[]))}let visitor={WORD:expandToken};return reservedWords.forEach((w)=>{visitor[w]=expandToken}),visitor};module.exports=(options,mode,previousPhases)=>{if(typeof options.resolveAlias!=="function")return identity;let preAliasLexer=compose.apply(null,previousPhases.reverse()),visitor=expandAlias(preAliasLexer,options.resolveAlias,values(mode.enums.reservedWords));return compose(merge2,map2(tokens.applyTokenizerVisitor(visitor)))}});var require_bash=__commonJS((exports,module)=>{var bashAliasSubstitution=require_alias_substitution(),parameterOperators={["^([a-zA-Z_][a-zA-Z0-9_]*):([^:]*):?([^:]*)$"]:{op:"substring",parameter:(m)=>m[1],offset:(m)=>parseInt(m[2],10),length:(m)=>parseInt(m[3],10)||void 0},["^!([a-zA-Z_][a-zA-Z0-9_]*)(\\*|@)$"]:{op:"prefix",prefix:(m)=>m[1],expandWords:(m)=>m[2]==="@",parameter:()=>{return}},["^!([a-zA-Z_][a-zA-Z0-9_]*)(\\[\\*\\]|\\[@\\])$"]:{op:"arrayIndices",parameter:(m)=>m[1],expandWords:(m)=>m[2]==="[@]"},["^([a-zA-Z_][a-zA-Z0-9_]*)\\/(\\/)?([^\\/])+\\/(.*)$"]:{op:"stringReplace",parameter:(m)=>m[1],substitute:(m)=>m[3],replace:(m)=>m[4],globally:(m)=>m[2]==="/"},["^([a-zA-Z_][a-zA-Z0-9_]*)(\\^\\^|\\^|,,|,)(.*)$"]:{op:"caseChange",parameter:(m)=>m[1],pattern:(m)=>m[3]||"?",case:(m)=>m[2][0]===","?"lower":"upper",globally:(m)=>m[2].length===2},["^([a-zA-Z_][a-zA-Z0-9_]*)@([Q|E|P|A|a])$"]:{op:"transformation",parameter:(m)=>m[1],kind:(m)=>{switch(m[2]){case"Q":return"quoted";case"E":return"escape";case"P":return"prompt";case"A":return"assignment";case"a":return"flags";default:return"unknown"}}},["^!(.+)$"]:{op:"indirection",word:(m)=>m[1],parameter:()=>{return}}};module.exports={inherits:"posix",init:(posixMode,utils)=>{let phaseCatalog=Object.assign({},posixMode.phaseCatalog,{bashAliasSubstitution}),lexerPhases=utils.replaceRule(phaseCatalog.aliasSubstitution,bashAliasSubstitution,posixMode.lexerPhases),bashOperators=Object.assign(parameterOperators,posixMode.enums.parameterOperators),enums=Object.assign({},posixMode.enums,{parameterOperators:bashOperators});return Object.assign({},posixMode,{phaseCatalog,lexerPhases,enums})}}});var require_is_number=__commonJS((exports,module)=>{/*!
|
|
1113
1113
|
* is-number <https://github.com/jonschlinkert/is-number>
|
|
@@ -1171,7 +1171,7 @@ ${line}`)}else{let prefix=fileEndsWithNewline2(filePath)?"":`
|
|
|
1171
1171
|
`;break}case"file_write":line=`${JSON.stringify({...entry,path:redactPath(entry.path),reason:truncateUtf8Safe(redactEmbeddedPaths(entry.reason),maxReason),resolvedScope:redactPath(entry.resolvedScope)})}
|
|
1172
1172
|
`;break;case"scope_violation":line=`${JSON.stringify({...entry,path:redactPath(entry.path),declaredScope:redactPath(entry.declaredScope),resolvedScope:redactPath(entry.resolvedScope)})}
|
|
1173
1173
|
`;break}try{appendShellAuditLineSync(ctx.directory,line)}catch(error49){log("guardrail audit: append failed",{directory:ctx.directory,error:error49})}}var SHELL_AUDIT_FIELD_CLASSES,REQUIRED_STRING_FIELDS;var init_audit_log=__esm(()=>{init_logger();init_helpers();init_shell_audit_store();SHELL_AUDIT_FIELD_CLASSES=Object.freeze({ts:"timestamp",sessionID:"identifier",agent:"identifier",tool:"identifier",type:"decision-type",command:"redacted-command",commandHash:"content-hash",path:"redacted-path",reason:"free-text-redacted",resolvedScope:"redacted-path",declaredScope:"redacted-path",action:"enum",destructiveCategory:"enum",executorMechanism:"enum",skipReason:"enum"}),REQUIRED_STRING_FIELDS=["ts","sessionID","agent","tool","type"]});import*as fsSync9 from"node:fs";import*as os14 from"node:os";import*as path82 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path82.join(dir,"package.json");if(!_internals74.existsSync(manifestPath))return null;let name=JSON.parse(_internals74.readFileSync(manifestPath,"utf-8"))?.name;return typeof name==="string"?name:null}catch{return null}}function resolvePackageRoot(){if(cachedPackageRoot!==void 0)return cachedPackageRoot.root;let root=null;try{let dir=path82.dirname(fileURLToPath3(_internals74.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path82.dirname(dir);if(parent===dir)break;dir=parent}}catch{root=null}return cachedPackageRoot={root},root}function isSelfDevelopmentWorkspace(directory){if(!directory)return!1;let resolved;try{resolved=canonicalRootKeyFresh(directory)}catch{return!1}let cached2=selfDevelopmentWorkspaces.get(resolved);if(cached2!==void 0)return cached2;let isSelfDev=readPackageName(resolved)==="opencode-swarm";if(selfDevelopmentWorkspaces.size>=MAX_CACHED_WORKSPACE_ROOTS){let oldest=selfDevelopmentWorkspaces.keys().next().value;if(oldest!==void 0)selfDevelopmentWorkspaces.delete(oldest)}return selfDevelopmentWorkspaces.set(resolved,isSelfDev),isSelfDev}function comparablePath(value){return process.platform==="win32"?value.toLowerCase():value}function isInsidePackageRoot(root,target){try{let rel=path82.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path82.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals74.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path82.join(home,rest):home}function extractGuardedPathCandidates(normalizedTool,args2){let argsObj=args2??{},raw=[];if(normalizedTool==="bash"||normalizedTool==="shell"){let command=typeof argsObj.command==="string"?argsObj.command.slice(0,MAX_SCANNED_COMMAND_LENGTH):void 0;if(command){let matcher=new RegExp(SHELL_PATH_CANDIDATE_PATTERN.source,SHELL_PATH_CANDIDATE_PATTERN.flags);for(let match of command.matchAll(matcher)){let token=match[1];if(token&&token.length>1)raw.push(token);if(raw.length>=MAX_SHELL_PATH_CANDIDATES)break}}}else for(let key2 of SCALAR_PATH_KEYS2){let value=argsObj[key2];if(typeof value==="string"&&value.length>0)raw.push(value)}let resolved=[];for(let candidate of raw){let expanded=expandHome(candidate);if(!expanded)continue;if(!path82.isAbsolute(expanded))continue;try{resolved.push(path82.resolve(expanded))}catch{}}return resolved}function enforceInternalsGuard(params){let{sessionID,tool,args:args2,directory,options}=params;if(options?.enabled===!1)return;let normalizedTool=normalizeToolNameLowerCase(tool??"");if(!GUARDED_TOOLS.has(normalizedTool))return;let match=null,relativeTarget="";try{let packageRoot=_internals74.resolvePackageRoot();if(!packageRoot)return;if(_internals74.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path82.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path82.relative(packageRoot,candidate).replace(/\\/g,"/")||"<package root>";break}}catch{return}if(!match)return;try{telemetry.swarmInternalsReadDenied(sessionID,normalizedTool,relativeTarget)}catch{}throw Error(SWARM_INTERNALS_DENIAL_MESSAGE)}var SWARM_INTERNALS_DENIAL_MESSAGE="SWARM_INTERNALS_OFF_LIMITS: the swarm plugin's installed files are never the fix for a gate error. Fix the dispatch/state the error names, or report the blocker to the user.",GUARDED_TOOLS,SCALAR_PATH_KEYS2,MAX_PACKAGE_ROOT_WALK_DEPTH=12,MAX_CACHED_WORKSPACE_ROOTS=32,SHELL_PATH_CANDIDATE_PATTERN,MAX_SHELL_PATH_CANDIDATES=64,MAX_SCANNED_COMMAND_LENGTH=8192,cachedPackageRoot,selfDevelopmentWorkspaces,_internals74;var init_internals_guard=__esm(()=>{init_telemetry();init_canonical_root();init_normalize_tool_name();GUARDED_TOOLS=new Set(["read","glob","grep","bash","shell"]),SCALAR_PATH_KEYS2=["filePath","file_path","path","file","target"],SHELL_PATH_CANDIDATE_PATTERN=/(?:^|[\s'"`;|&<>()=,])((?:~|[A-Za-z]:)?[\\/][^\s'"`;|&<>()]*)/g,selfDevelopmentWorkspaces=new Map;_internals74={moduleUrl:()=>import.meta.url,existsSync:(p)=>fsSync9.existsSync(p),readFileSync:(p,enc)=>fsSync9.readFileSync(p,enc),homedir:()=>os14.homedir(),resolvePackageRoot,isSelfDevelopmentWorkspace,resetCaches:()=>{cachedPackageRoot=void 0,selfDevelopmentWorkspaces.clear()}}});import*as path83 from"node:path";function normalizeSandboxMechanism2(mechanism){return mechanism.toLowerCase().replace(/[^a-z0-9]+/g,"")}function pluginOwnsExecutorEnv(mechanism){if(mechanism.startsWith("native-runner/"))return!0;switch(mechanism){case"sandbox-exec":case"powershell-wrapper":case"Bubblewrap":return!0;default:return!1}}function throwDestructiveBlock(destructiveCategory,message){throw new DestructiveCommandBlockedError(message,destructiveCategory)}function createToolBeforeHandler(ctx){let{effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,getSandboxExecutor,assessSandboxEnforcement:assessSandboxEnforcement2,rememberReviewerScopeWrite,rememberScopeLeaseCandidate}=ctx;setMacOSSandboxPolicy(cfg.sandbox_macos_enabled??!1);let executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},internalsGuardOptions={enabled:cfg.enabled},sessionWorkspaceDirectory=(sessionID)=>resolveSessionWorkspaceDirectory(sessionID,effectiveDirectory);function resolveActiveScopeBinding(sessionID){let session=swarmState.agentSessions.get(sessionID),taskId=session?.currentTaskId??null,bindingDirectory=sessionWorkspaceDirectory(sessionID),resolution=taskId?resolveAuthorizedScopeBindingDetailed({directory:bindingDirectory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSessionDetailed({directory:bindingDirectory,activeSessionId:sessionID}),binding=resolution.status==="found"?resolution.binding:null;if(!binding){let diagnostic=formatScopeResolutionDiagnostic({resolution,taskId,sessionId:sessionID});if(diagnostic)throw Error(diagnostic)}if(!taskId&&binding&&session)session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];return binding}function resolveDeclaredScope(sessionID){let session=swarmState.agentSessions.get(sessionID);if(!session?.currentTaskId)return session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null;return resolveActiveScopeBinding(sessionID)?.files??null}function isArchitect(sessionId){let activeAgent=swarmState.activeAgent.get(sessionId);if(activeAgent){if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME)return!0}let session=swarmState.agentSessions.get(sessionId);if(session){if(stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME)return!0}return!1}function handleInterpreterGating(sessionID,tool){let normalizedTool=normalizeToolName(tool).toLowerCase();if(normalizedTool!=="bash"&&normalizedTool!=="shell")return;if(!interpreterAllowedAgents)return;let rawAgent=swarmState.activeAgent.get(sessionID),agentRole=rawAgent?stripKnownSwarmPrefix(rawAgent).toLowerCase():"unknown";if(!interpreterAllowedAgents.some((a)=>a.toLowerCase()===agentRole))throw Error(`BLOCKED: Agent "${agentRole}" is not permitted to use the bash/shell interpreter. Allowed agents: [${interpreterAllowedAgents.map((a)=>`"${a}"`).join(", ")}]`)}function checkDestructiveCommand(sessionID,tool,args2){if(tool!=="bash"&&tool!=="shell")return;if(cfg.block_destructive_commands===!1)return;let rawAgent=swarmState.activeAgent.get(sessionID),isCoder=(rawAgent?stripKnownSwarmPrefix(rawAgent).toLowerCase():"unknown")==="coder",session=swarmState.agentSessions.get(sessionID),activeBinding=isCoder&&session?.currentTaskId?resolveActiveScopeBinding(sessionID):null,bindingIdentity=activeBinding,verifiedScope=bindingIdentity&&typeof bindingIdentity.bindingId==="string"&&typeof bindingIdentity.generationId==="string"?{bindingId:bindingIdentity.bindingId,generationId:bindingIdentity.generationId,files:bindingIdentity.files}:void 0,declaredScope=activeBinding?.files??(session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null),toolArgs=args2,rawCommand=typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!rawCommand)return;let sharedClassification=classifyCommand(rawCommand),sharedGuardrailBlock=getSharedClassifierGuardrailBlock(sharedClassification);if(sharedGuardrailBlock)throwDestructiveBlock(sharedGuardrailBlock.destructiveCategory,sharedGuardrailBlock.message);let cwd=sessionWorkspaceDirectory(sessionID),command=dcNormalizeCommand(rawCommand),unwrapped=dcUnwrapWrappers(command),outerSegments=dcSplitSegments(command),innerSegments=dcSplitSegments(unwrapped),perSegmentUnwrapped=outerSegments.map((s)=>dcUnwrapWrappers(s)),allSegments=[...new Set([...outerSegments,...innerSegments,...perSegmentUnwrapped])],swarmShellVars=new Map;for(let segment of allSegments){let seg=segment.trim();if(!seg)continue;for(let m of seg.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=(?:"([^"]*)"|'([^']*)'|([^\s;&|()]+))/g)){let value=m[2]??m[3]??m[4]??"";if(m[1])swarmShellVars.set(m[1],value)}let junctionBlock=dcCheckJunctionCreation(seg,cwd);if(junctionBlock)throwDestructiveBlock("junction/symlink creation",junctionBlock);let rmTargets=dcExtractRecursiveRmTargets(seg);if(rmTargets){let decision=dcEvaluateRecursiveDeleteTargets({targets:rmTargets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive delete",decision.reason)}if(/^(?:rmdir|rd)(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets=dcExtractWindowsCmdTargets(seg);if(targets.length===0)throwDestructiveBlock("recursive directory delete","BLOCKED: Windows recursive directory delete (rmdir /s or rd /s) detected. Verify the target is not a junction/symlink.");let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive directory delete",decision.reason)}if(/^del(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets=dcExtractWindowsCmdTargets(seg);if(targets.length>0){let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive file delete",decision.reason)}}if(/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]ecurse\b/i.test(seg)||/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]\b/i.test(seg)){let targets=dcExtractPowerShellTargets(seg);if(targets.length>0){let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive remove",decision.reason)}else throwDestructiveBlock("recursive remove","BLOCKED: PowerShell Remove-Item with -Recurse detected — cannot verify target safety")}if(/Get-ChildItem\b.*\|\s*Remove-Item\b.*-[Rr]ecurse/i.test(seg)||/gci\b.*\|\s*ri\b.*-[Rr]ecurse/i.test(seg))throwDestructiveBlock("recursive remove",'BLOCKED: PowerShell pipeline "Get-ChildItem | Remove-Item -Recurse" detected — verify target safety and avoid recursive deletion through symlinks/junctions');let worktreeRemoveMatch=/^git\s+worktree\s+remove\s+(.+)$/i.exec(seg);if(worktreeRemoveMatch){let normalizedArgs=worktreeRemoveMatch[1].trim().split(/\s+/).filter(Boolean).map((a)=>a.replace(/^["']|["']$/g,"")),isForceToken=(a)=>{let lower=a.toLowerCase();return/^-f+$/.test(lower)||lower.length>2&&"--force".startsWith(lower)};if(normalizedArgs.some(isForceToken)){let pathArgs=normalizedArgs.filter((a)=>!a.startsWith("-")),target=pathArgs.length===1?pathArgs[0].trim():null;if(!(target!=null&&target.length>0&&(declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(target,declaredScope,cwd)||isPathUnderSwarmWorktreeBase(target,cwd,worktreeBaseDirOverrides??[]))))throwDestructiveBlock("git worktree remove",'BLOCKED: "git worktree remove --force" detected — can delete working tree contents')}}if(/^rsync\b.*--delete(?:-after|-before|-during|-delay)?\b/.test(seg)){let rsyncTarget=seg.split(/\s+/).slice(1).filter((a)=>!a.startsWith("-")&&!a.includes("@")).pop();if(!(rsyncTarget!=null&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(rsyncTarget,declaredScope,cwd)))throwDestructiveBlock("rsync delete",'BLOCKED: "rsync --delete" detected — can delete files in the destination. Verify source is not empty.')}if(/^\\?mv\s/i.test(seg)){let mvMatch=seg.match(/^\\?mv\s+(.+)$/i);if(mvMatch){let argsStr=mvMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/.test(argsStr))throwDestructiveBlock("swarm path move",'BLOCKED: "mv" targeting .swarm/ detected — move operations under .swarm/ are not allowed from shell commands')}}if(/^\\?(?:move|ren)(?:\.exe)?\s/i.test(seg)){let moveMatch=seg.match(/^\\?(?:move|ren)(?:\.exe)?\s+(.+)$/i);if(moveMatch){let argsStr=moveMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/i.test(argsStr))throwDestructiveBlock("move/rename",'BLOCKED: "move" or "ren" targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands')}}if(/^\\?(?:Move-Item|Rename-Item|move|mi|mv|ren|rni)\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("move/rename","BLOCKED: PowerShell Move-Item or Rename-Item targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands");if(/^\\?rm\b/i.test(seg)&&!/^\\?rm\s+(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("swarm path delete",'BLOCKED: "rm" targeting .swarm/ detected — deleting files under .swarm/ is not allowed from shell commands');if(/\bcp\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg)&&/\brm\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("copy-and-delete bypass",'BLOCKED: "cp" of .swarm/ file followed by "rm" of .swarm/ source detected — copy-and-delete bypass is not allowed');if(/^rsync\b.*--remove-source-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "rsync" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^tar\b.*--remove-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "tar" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^zip\b.*\s-m\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "zip" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^7z\b.*\s-sdel\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "7z" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');{let HUMAN_ONLY_SWARM_SUBCOMMANDS=HUMAN_ONLY_SWARM_COMMANDS,probe2=seg.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*(?:="[^"]*"|='[^']*'|=\S+)\s+)+/,"").replace(/^eval(?:\s+--)?\s+["']?/,"").replace(/["']\s*$/,"").replace(/^\$\(\s*/,"").replace(/^\(\s*/,"").replace(/\s*\)$/,"").replace(/^`/,"").replace(/`$/,"").trim();for(let i=0;i<4;i++){let before=probe2;if(probe2=probe2.replace(/^env\s+(?:-i\b|--ignore-environment\b|-u\s+\S+|-[a-zA-Z]+\s+)*\s*/,"").replace(/^command\s+(?:-[pvV]\s+)*/,"").replace(/^(?:[A-Za-z_][A-Za-z0-9_]*(?:="[^"]*"|='[^']*'|=\S+)\s+)+/,"").trim(),probe2===before)break}let dequote=(input)=>input.replace(/["']/g,""),resolveVars=(input)=>input.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g,(full,name)=>swarmShellVars.has(name)?swarmShellVars.get(name):full),RUNNER_SHAPE=/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?(?:bunx|npx|pnpx|npm|pnpm|yarn|bun|node|deno|tsx|ts-node|opencode-swarm)\b[^|;&]*?\brun\s+\$/i;for(let variant of[resolveVars(probe2),dequote(resolveVars(probe2))])if(RUNNER_SHAPE.test(variant))throwDestructiveBlock("human-only swarm command",'BLOCKED: "opencode-swarm run" invoked with an unresolvable shell variable or command substitution in the subcommand position. Re-run with the literal subcommand name so the human-only policy can be evaluated.');let probeVariants=[probe2,dequote(probe2),resolveVars(probe2),dequote(resolveVars(probe2))],matchCaptures=(re)=>{let captures=[];for(let variant of probeVariants){let m=variant.match(re);if(m?.[1])captures.push(m[1])}return captures},blockIfHumanOnly=(captures)=>{for(let captured of captures){let normalized=captured.trim().split(/\s+/).join(" "),firstToken=normalized.includes(" ")?normalized.split(" ")[0]:normalized,cmdName=HUMAN_ONLY_SWARM_SUBCOMMANDS.has(normalized)?normalized:firstToken;if(HUMAN_ONLY_SWARM_SUBCOMMANDS.has(normalized)||HUMAN_ONLY_SWARM_SUBCOMMANDS.has(firstToken))throwDestructiveBlock("human-only swarm command",`BLOCKED: "${cmdName}" is a human-only swarm command and may not be invoked from shell by an agent. Present the situation to the user and ask them to run \`/swarm ${cmdName}\` themselves.`)}};blockIfHumanOnly(matchCaptures(/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?(?:bunx|npx|pnpx|npm(?:\s+(?:exec|x)(?:\s+--)?)?|pnpm(?:\s+(?:dlx|exec))?|yarn(?:\s+(?:dlx|exec))?|bun(?:\s+x)?|node|deno\s+run|tsx|ts-node)\b[^|;&]*?\bopencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)),blockIfHumanOnly(matchCaptures(/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?opencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)),blockIfHumanOnly(matchCaptures(/\bcli[/\\]+index\.[mc]?(?:js|ts)\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i))}{let normForPathCheck=seg.replace(/\\/g,"/").replace(/\/(?:\.\/+)+/g,"/").replace(/\/{2,}/g,"/");if(/\.swarm\/spec-staleness\.json\b/i.test(normForPathCheck)){let trimmed=seg.trim(),looksReadOnly=/^(?:cat|less|more|head|tail|file|stat|ls|dir|Get-Content|gc|Get-Item|gi|type)\b/i.test(trimmed),hasWriteRedirect=/>{1,2}\s*[^\s>]/.test(trimmed);if(!looksReadOnly||hasWriteRedirect)throwDestructiveBlock("system file tampering","BLOCKED: shell command targeting .swarm/spec-staleness.json detected. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.")}}}}function detectShellType(command){if(/^(powershell|ps1|\.\s*\\|Remove-Item|Copy-Item|Move-Item|Start-Process|New-Object|Get-ChildItem|Set-Content|Add-Content|Out-File|Invoke-WebRequest|Invoke-RestMethod|IEX|iex)\b/i.test(command)||command.includes("$PSVersionTable")||command.includes("$env:")||/-EncodedCommand|-ExecutionPolicy|Enable-PSRemoting/i.test(command))return"powershell";if(/^(cmd|c:\/|set \w+=|\.\d+|del \/|rd \/|mkdir|chdir|echo |copy |move |ren |fc |diskpart)/i.test(command)||/%[^%\s]+%/.test(command)||/\b(set|echo|if|exist)\s+/i.test(command))return"cmd";if(/^(bash|sh|zsh|ksh|ash|dash|fish|ruby|python|perl|npm|yarn|node|cargo|go|rustc|mv|cp|rm|chmod|chown|mkdir|ln|tar|gzip|gunzip|ssh|scp|rsync|sudo|su -|export |source |\.\s+)/i.test(command)||command.includes("|")||command.includes("&&")||command.includes(">>")||/\$\{?\w+\}?/.test(command))return"bash";return"unix"}function checkShellWriteScope(sessionID,callID,tool,args2,commandOverride){if(tool!=="bash"&&tool!=="shell")return;let session=swarmState.agentSessions.get(sessionID),toolArgs=args2,command=typeof commandOverride==="string"?commandOverride.trim():typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!command)return;let normalizedTool=tool,shellType="posix";if(normalizedTool==="bash")shellType="posix";else shellType=detectShellType(command);if(detectInteractiveSession(command,shellType==="unix"||shellType==="bash"?"posix":shellType))throw Error("BLOCKED: interactive/session tool detected — rejecting for safety");let detect=(c)=>normalizedTool==="bash"?detectPosixWrites(c):shellType==="powershell"||shellType==="cmd"?detectWindowsWrites(c,shellType):detectPosixWrites(c),primaryAnalysis=detect(command);if(primaryAnalysis.parseError)throw Error("BLOCKED: bash write detection failed to parse command — rejecting for safety");let commandSegments=dcSplitSegments(command),unwrappedSegments=commandSegments.map((s)=>dcUnwrapWrappers(s)),didUnwrap=commandSegments.some((s,i)=>unwrappedSegments[i]!==s),detectionCommand=didUnwrap?unwrappedSegments.join(`
|
|
1174
|
-
`):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(analysis.parseError)throw Error("BLOCKED: bash write detection failed to parse command — rejecting for safety");if(!analysis.hasWrites||analysis.writes.length===0)return;let declaredScope=resolveDeclaredScope(sessionID),shellWriteAgent=swarmState.activeAgent.get(sessionID);if(!shellWriteAgent)throw Error(`WRITE BLOCKED: No active agent registered for session "${sessionID}". Call startAgentSession before issuing shell write operations.`);let shellWriteRole=stripKnownSwarmPrefix(shellWriteAgent).toLowerCase(),isArch=shellWriteRole==="architect",isCoder=shellWriteRole==="coder",shellRoleCapability=AUTHORITY_ROLE_CAPABILITIES[shellWriteRole],isImmutableNonWriter=shellRoleCapability==="read-only"||shellRoleCapability==="dedicated-tool-only";if(isCoder&&(!declaredScope||declaredScope.length===0))throw Error(`SCOPE_NOT_DECLARED: ${shellWriteAgent} cannot perform shell writes without an active Task-correlated scope binding. ACTION[architect]: call declare_scope with the exact workspace-relative paths and replace_existing=true, then dispatch a new Task call.`);let noScopeLenient=!isArch&&!isCoder&&!isImmutableNonWriter&&(!declaredScope||declaredScope.length===0),shellDirectory=sessionWorkspaceDirectory(sessionID),resolvedWrites=resolveWriteTargets(detectionCommand,analysis.writes,shellDirectory);for(let write of resolvedWrites){if(write.resolvedPath===null){if(write.original.category==="here_doc"&&write.original.path===null)continue;if(write.original.category==="interpreter_eval")throw Error(`BLOCKED: ${write.original.operator} evaluates inline code whose write targets cannot be verified against the declared scope — rejecting for safety. Write files with the write/edit tools or a checked-in script, and invoke installed tools directly (e.g. \`pytest\`, \`ruff\`) instead of an inline \`python -c\` / \`node -e\` eval.`);throw Error(`BLOCKED: bash/shell write to a dynamic path target${write.original.path?` "${write.original.path}"`:""} that cannot be statically resolved (shell variable or command substitution) — rejecting for safety.`)}if(noScopeLenient&&universalDenyPrefixes.length>0){for(let prefix of universalDenyPrefixes)if(matchesAuthorityDenyPrefix(write.resolvedPath,prefix,shellDirectory))throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: Path is under universal deny prefix "${prefix}"`)}if(noScopeLenient)continue;let authorityCheck=checkFileAuthorityWithRules(shellWriteAgent,write.resolvedPath,shellDirectory,precomputedAuthorityRules,{declaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"protected_state_mutation",paths:[write.resolvedPath]}):void 0;throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}if(declaredScope&&declaredScope.length>0&&!isInDeclaredScope(write.resolvedPath,declaredScope,shellDirectory)){let safeTarget=sanitizeDiagnosticText(write.resolvedPath,320),scopeSummary=declaredScope.slice(0,10).map((entry)=>sanitizeDiagnosticText(entry,160)).join(", "),omitted=Math.max(0,declaredScope.length-10);throw Error(`WRITE BLOCKED: SCOPE_VIOLATION: shell write target "${safeTarget}" is outside the active scope [${scopeSummary}${omitted>0?`, ... (+${omitted} more)`:""}]. ACTION[architect]: if the target is intended, call declare_scope for the exact workspace-relative path and redispatch; otherwise correct the command.`)}if(isCoder&&session?.currentTaskId){let writeBinding=resolveActiveScopeBinding(sessionID);if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path83.relative(path83.resolve(shellDirectory),path83.resolve(shellDirectory,write.resolvedPath)).replace(/\\/g,"/");if(recordReviewerScopeGenerationFile({parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget}))rememberReviewerScopeWrite?.({callID,parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget})}}}if(isCoder&&session?.currentTaskId){let binding=resolveActiveScopeBinding(sessionID);if(binding)rememberScopeLeaseCandidate?.({callID,sessionID,tool,directory:shellDirectory,binding,targets:resolvedWrites.flatMap((write)=>write.resolvedPath===null?[]:[path83.resolve(shellDirectory,write.resolvedPath)]),args:args2})}}async function applySandboxExecution(sessionID,callID,tool,args2,agent,command,auditEnabled){if(tool!=="bash"&&tool!=="shell")return;let toolArgs=args2,rawCommand=typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!rawCommand||!toolArgs)return;let executor=await getSandboxExecutor(),sandboxConfig=cfg.sandbox,originalCommandHash=hashArgs({command:rawCommand}),commandIdentity=`cmd=${originalCommandHash}`,assessment=await assessSandboxEnforcement2(sandboxConfig?{mode:sandboxConfig.mode,require_filesystem:sandboxConfig.require_filesystem,require_network:sandboxConfig.require_network,require_process:sandboxConfig.require_process,network_mode:sandboxConfig.network_mode,network_allowlist:sandboxConfig.network_allowlist,writable_roots:sandboxConfig.writable_roots}:void 0),capabilityIdentity=`cap=${assessment.capability.identity}`,recordOutcome2=(outcome)=>recordSandboxWrapOutcome({...outcome,sessionID,callID,originalCommandHash,originalCommand:rawCommand,assessmentCacheKey:assessment.cacheKey,executorMechanism:executor?.mechanism??"none",capabilityMechanism:assessment.capability.mechanism}),clearRecordedOutcome=()=>{clearSandboxWrapOutcome(sessionID,callID)};if(sandboxConfig?.mode==="required"){let assessmentSupported=assessment.supported!==!1,assessmentUnsupported=assessment.unsupported??[],missing=!executor||!executor.isAvailable()?["executor"]:assessment.missing;if(!executor||!executor.isAvailable()||!assessmentSupported||!assessment.satisfied){let missingOrUnsupported=assessmentSupported?missing.join(", "):assessmentUnsupported.join(", "),skipReason=missing[0]==="executor"?`required sandbox executor unavailable [${commandIdentity} ${capabilityIdentity}]`:!assessmentSupported?`required sandbox policy unsupported (${missingOrUnsupported}) [${commandIdentity} ${capabilityIdentity}]`:`required sandbox capability unsatisfied (${missingOrUnsupported}) [${commandIdentity} ${capabilityIdentity}]`;throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:skipReason}),clearRecordedOutcome(),appendGuardrailDecision({type:"sandbox_skip",ts:new Date().toISOString(),sessionID,agent,tool,command,executorMechanism:executor?.mechanism??"none",skipReason},{directory:effectiveDirectory,enabled:auditEnabled}),Error(`[sandbox] BLOCKED: Required sandbox policy unsatisfied (${missingOrUnsupported}). [${commandIdentity} ${capabilityIdentity}] Command will not be executed unsandboxed.`)}}if(!executor||!executor.isAvailable()){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"executor not available"}),!hasWarnedSandboxUnavailable)hasWarnedSandboxUnavailable=!0,criticalWarn("[guardrails] sandbox executor unavailable; shell commands will run unsandboxed. Run /swarm diagnose for details.");appendGuardrailDecision({type:"sandbox_skip",ts:new Date().toISOString(),sessionID,agent,tool,command,executorMechanism:executor?.mechanism??"none",skipReason:"executor not available"},{directory:effectiveDirectory,enabled:auditEnabled});return}let declaredPaths=resolveDeclaredScope(sessionID);if(!declaredPaths||declaredPaths.length===0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"no declared scope"}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy needs a declared writable scope; command will not execute unsandboxed.");return}let resolved=resolveScopePaths(declaredPaths,sessionWorkspaceDirectory(sessionID)),configuredWritableRoots=resolveScopePaths(sandboxConfig?.writable_roots??[],sessionWorkspaceDirectory(sessionID));if(configuredWritableRoots.rejected.length>0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:`configured writable_roots rejected (${configuredWritableRoots.rejected.map((item)=>item.path).join(", ")})`}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy contains writable_roots outside the session workspace; command will not execute unsandboxed.");return}if(resolved.paths.length===0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"resolved scope empty"}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy resolved no writable scope; command will not execute unsandboxed.");return}let writablePaths=[...new Set([...resolved.paths,...configuredWritableRoots.paths])];try{let envOverrides=pluginOwnsExecutorEnv(executor.mechanism)?executor.getEnvOverrides():void 0,wrappedCommand=executor.wrapCommand(rawCommand,writablePaths,void 0,envOverrides,{network_mode:sandboxConfig?.network_mode??"off",network_allowlist:sandboxConfig?.network_allowlist??[],writable_roots:configuredWritableRoots.paths});if(wrappedCommand.trim()===rawCommand)throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"sandbox wrapper returned the original command unchanged"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: ${executor.mechanism} returned the original command unchanged. [${commandIdentity} ${capabilityIdentity}] Command will not be executed unsandboxed.`);if(normalizeSandboxMechanism2(executor.mechanism)!==normalizeSandboxMechanism2(assessment.capability.mechanism))throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"sandbox executor mechanism no longer matches the assessed capability"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: sandbox executor mechanism drifted from the assessed capability (${executor.mechanism} != ${assessment.capability.mechanism}). [${commandIdentity} ${capabilityIdentity}]`);toolArgs.command=wrappedCommand,recordOutcome2({finalCommandHash:hashArgs({command:wrappedCommand}),wrapped:!0,capabilityIdentity:assessment.capability.identity,reason:"wrapped"}),markToolExecutionSandboxWrapped(sessionID,callID),appendGuardrailDecision({type:"sandbox_wrap",ts:new Date().toISOString(),sessionID,agent,tool,command:rawCommand,executorMechanism:executor.mechanism},{directory:effectiveDirectory,enabled:auditEnabled})}catch(err){recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:err instanceof Error?err.message:String(err)}),clearRecordedOutcome(),forgetToolExecution(sessionID,callID);let message=`[sandbox] BLOCKED: Failed to wrap command with ${executor.mechanism}: ${err}. Command will not be executed unsandboxed.`,circuit=recordNonTransientFailure(sessionID,"sandbox_wrapper_failure",message,{tool,args:{command:rawCommand},armAttempt:!0});if(circuit?.hardStop)throw Error(nonTransientHardStopMessage(circuit));throw Error(message)}}async function checkGateLimits(params){let{sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount}=params;if(agentConfig.max_tool_calls>0&&window2.toolCalls>=agentConfig.max_tool_calls)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"tool_calls",window2.toolCalls),warn("Circuit breaker: tool call limit hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,resolvedMaxCalls:agentConfig.max_tool_calls,currentCalls:window2.toolCalls}),Error(`\uD83D\uDED1 LIMIT REACHED: Tool calls exhausted (${window2.toolCalls}/${agentConfig.max_tool_calls}). Finish the current operation and return your progress summary.`);if(agentConfig.max_duration_minutes>0&&elapsedMinutes>=agentConfig.max_duration_minutes)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"duration",elapsedMinutes),warn("Circuit breaker: duration limit hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,resolvedMaxMinutes:agentConfig.max_duration_minutes,elapsedMinutes:Math.floor(elapsedMinutes)}),Error(`\uD83D\uDED1 LIMIT REACHED: Duration exhausted (${Math.floor(elapsedMinutes)}/${agentConfig.max_duration_minutes} min). Finish the current operation and return your progress summary.`);if(repetitionCount>=agentConfig.max_repetitions)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"repetition",repetitionCount),Error(`\uD83D\uDED1 LIMIT REACHED: Repeated the same tool call ${repetitionCount} times. This suggests a loop. Return your progress summary.`);if(window2.consecutiveErrors>=agentConfig.max_consecutive_errors)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"consecutive_errors",window2.consecutiveErrors),Error(`\uD83D\uDED1 LIMIT REACHED: ${window2.consecutiveErrors} consecutive tool errors detected. Return your progress summary with details of what went wrong. Run /swarm reset-session to clear the circuit breaker without restarting your session.`);let idleMinutes=(Date.now()-window2.lastSuccessTimeMs)/60000;if(idleMinutes>=agentConfig.idle_timeout_minutes)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"idle_timeout",idleMinutes),warn("Circuit breaker: idle timeout hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,idleTimeoutMinutes:agentConfig.idle_timeout_minutes,idleMinutes:Math.floor(idleMinutes)}),Error(`\uD83D\uDED1 LIMIT REACHED: No successful tool call for ${Math.floor(idleMinutes)} minutes (idle timeout: ${agentConfig.idle_timeout_minutes} min). This suggests the agent may be stuck. Return your progress summary.`);if(!window2.warningIssued){let toolPct=agentConfig.max_tool_calls>0?window2.toolCalls/agentConfig.max_tool_calls:0,durationPct=agentConfig.max_duration_minutes>0?elapsedMinutes/agentConfig.max_duration_minutes:0,repPct=repetitionCount/agentConfig.max_repetitions,errorPct=window2.consecutiveErrors/agentConfig.max_consecutive_errors,reasons=[];if(agentConfig.max_tool_calls>0&&toolPct>=agentConfig.warning_threshold)reasons.push(`tool calls ${window2.toolCalls}/${agentConfig.max_tool_calls}`);if(durationPct>=agentConfig.warning_threshold)reasons.push(`duration ${Math.floor(elapsedMinutes)}/${agentConfig.max_duration_minutes} min`);if(repPct>=agentConfig.warning_threshold)reasons.push(`repetitions ${repetitionCount}/${agentConfig.max_repetitions}`);if(errorPct>=agentConfig.warning_threshold)reasons.push(`errors ${window2.consecutiveErrors}/${agentConfig.max_consecutive_errors}`);if(reasons.length>0)window2.warningIssued=!0,window2.warningReason=reasons.join(", ")}}function handleDelegatedWriteTracking(sessionID,tool,args2){if(!swarmState.agentSessions.get(sessionID)?.delegationActive&&isArchitect(sessionID)){let coderDeleg=isAgentDelegation(tool,args2);if(coderDeleg.isDelegation&&coderDeleg.targetAgent==="coder"){let coderSession=swarmState.agentSessions.get(sessionID);if(coderSession){let taskId=coderSession.currentTaskId??coderSession.lastCoderDelegationTaskId??`${sessionID}:unknown`;if(coderSession.currentTaskId=taskId,resetModifiedFilesForTask(coderSession,taskId),!coderSession.revisionLimitHit)coderSession.coderRevisions=0}}}}function isAgentDelegation(toolName,args2){let normalized=normalizeToolName(toolName);if(normalized!=="Task"&&normalized!=="task")return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function handleLoopDetection(sessionID,tool,args2){if(normalizeToolNameLowerCase(tool)!=="task")return;let loopArgs=args2,loopResult=detectLoop(sessionID,tool,loopArgs);if(loopResult.count>=5)throw Error(`CIRCUIT BREAKER: Delegation loop detected (${loopResult.count} identical patterns). Further identical delegations are blocked. Diagnose or rescope the task before retrying.`);else if(loopResult.count>=3&&loopResult.count<5){let agentName=typeof loopArgs?.subagent_type==="string"?loopArgs.subagent_type:"agent",loopSession=swarmState.agentSessions.get(sessionID);if(loopSession){let loopPattern=loopResult.pattern,modifiedFiles=loopSession.currentTaskId?getModifiedFilesForTask(loopSession,loopSession.currentTaskId):[],accomplishmentSummary=modifiedFiles.length>0?`Modified ${modifiedFiles.length} file(s): ${modifiedFiles.slice(0,3).join(", ")}${modifiedFiles.length>3?"...":""}`:"No files modified yet",alternativeSuggestions={coder:"Try a different task spec, simplify the constraint, or escalate to user",reviewer:"Try a different review dimension or escalate to user",test_engineer:"Run a specific test file with targeted scope",explorer:"Narrow the search scope or check a specific file directly"},cleanAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),suggestion=alternativeSuggestions[cleanAgent]??"Try a different agent, different instructions, or escalate to the user";loopSession.loopWarningPending={agent:agentName,message:[`LOOP DETECTED: Pattern "${loopPattern}" repeated 3 times.`,`Agent: ${agentName}`,`Accomplished: ${accomplishmentSummary}`,`Suggested action: ${suggestion}`,"If still stuck after trying alternatives, escalate to the user."].join(`
|
|
1174
|
+
`):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(analysis.parseError)throw Error("BLOCKED: bash write detection failed to parse command — rejecting for safety");if(!analysis.hasWrites||analysis.writes.length===0)return;let declaredScope=resolveDeclaredScope(sessionID),shellWriteAgent=swarmState.activeAgent.get(sessionID);if(!shellWriteAgent)throw Error(`WRITE BLOCKED: No active agent registered for session "${sessionID}". Call startAgentSession before issuing shell write operations.`);let shellWriteRole=stripKnownSwarmPrefix(shellWriteAgent).toLowerCase(),isArch=shellWriteRole==="architect",isCoder=shellWriteRole==="coder",shellRoleCapability=AUTHORITY_ROLE_CAPABILITIES[shellWriteRole],isImmutableNonWriter=shellRoleCapability==="read-only"||shellRoleCapability==="dedicated-tool-only";if(isCoder&&(!declaredScope||declaredScope.length===0))throw Error(`SCOPE_NOT_DECLARED: ${shellWriteAgent} cannot perform shell writes without an active Task-correlated scope binding. ACTION[architect]: call declare_scope with the exact workspace-relative paths and replace_existing=true, then dispatch a new Task call.`);let noScopeLenient=!isArch&&!isCoder&&!isImmutableNonWriter&&(!declaredScope||declaredScope.length===0),shellDirectory=sessionWorkspaceDirectory(sessionID),resolvedWrites=resolveWriteTargets(detectionCommand,analysis.writes,shellDirectory);for(let write of resolvedWrites){if(write.resolvedPath===null){if(write.original.category==="here_doc"&&write.original.path===null)continue;if(write.original.category==="interpreter_eval")throw Error(`BLOCKED: ${write.original.operator} evaluates inline code whose write targets cannot be verified against the declared scope — rejecting for safety. Write files with the write/edit tools or a checked-in script, and invoke installed tools directly (e.g. \`pytest\`, \`ruff\`) instead of an inline \`python -c\` / \`node -e\` eval.`);throw Error(`BLOCKED: bash/shell write to a dynamic path target${write.original.path?` "${write.original.path}"`:""} that cannot be statically resolved (shell variable or command substitution) — rejecting for safety.`)}if(noScopeLenient&&universalDenyPrefixes.length>0){for(let prefix of universalDenyPrefixes)if(matchesAuthorityDenyPrefix(write.resolvedPath,prefix,shellDirectory))throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: Path is under universal deny prefix "${prefix}"`)}if(noScopeLenient)continue;let authorityCheck=checkFileAuthorityWithRules(shellWriteAgent,write.resolvedPath,shellDirectory,precomputedAuthorityRules,{declaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"protected_state_mutation",paths:[write.resolvedPath]}):void 0;throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}if(declaredScope&&declaredScope.length>0&&!isInDeclaredScope(write.resolvedPath,declaredScope,shellDirectory)){let safeTarget=sanitizeDiagnosticText(write.resolvedPath,320),scopeSummary=declaredScope.slice(0,10).map((entry)=>sanitizeDiagnosticText(entry,160)).join(", "),omitted=Math.max(0,declaredScope.length-10);throw Error(`WRITE BLOCKED: SCOPE_VIOLATION: shell write target "${safeTarget}" is outside the active scope [${scopeSummary}${omitted>0?`, ... (+${omitted} more)`:""}]. ACTION[architect]: if the target is intended, call declare_scope for the exact workspace-relative path and redispatch; otherwise correct the command.`)}if(isCoder&&session?.currentTaskId){let writeBinding=resolveActiveScopeBinding(sessionID);if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path83.relative(path83.resolve(shellDirectory),path83.resolve(shellDirectory,write.resolvedPath)).replace(/\\/g,"/");if(recordReviewerScopeGenerationFile({parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget}))rememberReviewerScopeWrite?.({callID,parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget})}}}if(isCoder&&session?.currentTaskId){let binding=resolveActiveScopeBinding(sessionID);if(binding)rememberScopeLeaseCandidate?.({callID,sessionID,tool,directory:shellDirectory,binding,targets:resolvedWrites.flatMap((write)=>write.resolvedPath===null?[]:[path83.resolve(shellDirectory,write.resolvedPath)]),args:args2})}}async function applySandboxExecution(sessionID,callID,tool,args2,agent,command,auditEnabled){if(tool!=="bash"&&tool!=="shell")return;let toolArgs=args2,rawCommand=typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!rawCommand||!toolArgs)return;let executor=await getSandboxExecutor(),sandboxConfig=cfg.sandbox,originalCommandHash=hashArgs({command:rawCommand}),commandIdentity=`cmd=${originalCommandHash}`,assessment=await assessSandboxEnforcement2(sandboxConfig?{mode:sandboxConfig.mode,require_filesystem:sandboxConfig.require_filesystem,require_network:sandboxConfig.require_network,require_process:sandboxConfig.require_process,network_mode:sandboxConfig.network_mode,network_allowlist:sandboxConfig.network_allowlist,writable_roots:sandboxConfig.writable_roots}:void 0),capabilityIdentity=`cap=${assessment.capability.identity}`,recordOutcome2=(outcome)=>recordSandboxWrapOutcome({...outcome,sessionID,callID,originalCommandHash,originalCommand:rawCommand,assessmentCacheKey:assessment.cacheKey,executorMechanism:executor?.mechanism??"none",capabilityMechanism:assessment.capability.mechanism}),clearRecordedOutcome=()=>{clearSandboxWrapOutcome(sessionID,callID)};if(sandboxConfig?.mode==="required"){let assessmentSupported=assessment.supported!==!1,assessmentUnsupported=assessment.unsupported??[],missing=!executor||!executor.isAvailable()?["executor"]:assessment.missing;if(!executor||!executor.isAvailable()||!assessmentSupported||!assessment.satisfied){let missingOrUnsupported=assessmentSupported?missing.join(", "):assessmentUnsupported.join(", "),skipReason=missing[0]==="executor"?`required sandbox executor unavailable [${commandIdentity} ${capabilityIdentity}]`:!assessmentSupported?`required sandbox policy unsupported (${missingOrUnsupported}) [${commandIdentity} ${capabilityIdentity}]`:`required sandbox capability unsatisfied (${missingOrUnsupported}) [${commandIdentity} ${capabilityIdentity}]`;throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:skipReason}),clearRecordedOutcome(),appendGuardrailDecision({type:"sandbox_skip",ts:new Date().toISOString(),sessionID,agent,tool,command,executorMechanism:executor?.mechanism??"none",skipReason},{directory:effectiveDirectory,enabled:auditEnabled}),Error(`[sandbox] BLOCKED: Required sandbox policy unsatisfied (${missingOrUnsupported}). [${commandIdentity} ${capabilityIdentity}] Command will not be executed unsandboxed.`)}}if(!executor||!executor.isAvailable()){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"executor not available"}),!hasWarnedSandboxUnavailable)hasWarnedSandboxUnavailable=!0,criticalWarn("[guardrails] sandbox executor unavailable; shell commands will run unsandboxed. Run /swarm diagnose for details.");appendGuardrailDecision({type:"sandbox_skip",ts:new Date().toISOString(),sessionID,agent,tool,command,executorMechanism:executor?.mechanism??"none",skipReason:"executor not available"},{directory:effectiveDirectory,enabled:auditEnabled});return}let declaredPaths=resolveDeclaredScope(sessionID);if(!declaredPaths||declaredPaths.length===0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"no declared scope"}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy needs a declared writable scope; command will not execute unsandboxed.");return}let resolved=resolveScopePaths(declaredPaths,sessionWorkspaceDirectory(sessionID)),configuredWritableRoots=resolveScopePaths(sandboxConfig?.writable_roots??[],sessionWorkspaceDirectory(sessionID));if(configuredWritableRoots.rejected.length>0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:`configured writable_roots rejected (${configuredWritableRoots.rejected.map((item)=>item.path).join(", ")})`}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy contains writable_roots outside the session workspace; command will not execute unsandboxed.");return}if(resolved.paths.length===0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"resolved scope empty"}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy resolved no writable scope; command will not execute unsandboxed.");return}let writablePaths=[...new Set([...resolved.paths,...configuredWritableRoots.paths])];try{let envOverrides=pluginOwnsExecutorEnv(executor.mechanism)?executor.getEnvOverrides():void 0,wrappedCommand=executor.wrapCommand(rawCommand,writablePaths,void 0,envOverrides,{network_mode:sandboxConfig?.network_mode??"off",network_allowlist:sandboxConfig?.network_allowlist??[],writable_roots:configuredWritableRoots.paths});if(wrappedCommand.trim()===rawCommand)throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"sandbox wrapper returned the original command unchanged"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: ${executor.mechanism} returned the original command unchanged. [${commandIdentity} ${capabilityIdentity}] Command will not be executed unsandboxed.`);if(normalizeSandboxMechanism2(executor.mechanism)!==normalizeSandboxMechanism2(assessment.capability.mechanism))throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"sandbox executor mechanism no longer matches the assessed capability"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: sandbox executor mechanism drifted from the assessed capability (${executor.mechanism} != ${assessment.capability.mechanism}). [${commandIdentity} ${capabilityIdentity}]`);toolArgs.command=wrappedCommand,recordOutcome2({finalCommandHash:hashArgs({command:wrappedCommand}),wrapped:!0,capabilityIdentity:assessment.capability.identity,reason:"wrapped"}),markToolExecutionSandboxWrapped(sessionID,callID),appendGuardrailDecision({type:"sandbox_wrap",ts:new Date().toISOString(),sessionID,agent,tool,command:rawCommand,executorMechanism:executor.mechanism},{directory:effectiveDirectory,enabled:auditEnabled})}catch(err){recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:err instanceof Error?err.message:String(err)}),clearRecordedOutcome(),forgetToolExecution(sessionID,callID);let message=`[sandbox] BLOCKED: Failed to wrap command with ${executor.mechanism}: ${err}. Command will not be executed unsandboxed.`,circuit=recordNonTransientFailure(sessionID,"sandbox_wrapper_failure",message,{tool,args:{command:rawCommand},armAttempt:!0});if(circuit?.hardStop)throw Error(nonTransientHardStopMessage(circuit));throw Error(message)}}async function checkGateLimits(params){let{sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount}=params;if(agentConfig.max_tool_calls>0&&window2.toolCalls>=agentConfig.max_tool_calls)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"tool_calls",window2.toolCalls),warn("Circuit breaker: tool call limit hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,resolvedMaxCalls:agentConfig.max_tool_calls,currentCalls:window2.toolCalls}),Error(`\uD83D\uDED1 LIMIT REACHED: Tool calls exhausted (${window2.toolCalls}/${agentConfig.max_tool_calls}). Finish the current operation and return your progress summary.`);if(agentConfig.max_duration_minutes>0&&elapsedMinutes>=agentConfig.max_duration_minutes)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"duration",elapsedMinutes),warn("Circuit breaker: duration limit hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,resolvedMaxMinutes:agentConfig.max_duration_minutes,elapsedMinutes:Math.floor(elapsedMinutes)}),Error(`\uD83D\uDED1 LIMIT REACHED: Duration exhausted (${Math.floor(elapsedMinutes)}/${agentConfig.max_duration_minutes} min). Finish the current operation and return your progress summary.`);if(repetitionCount>=agentConfig.max_repetitions)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"repetition",repetitionCount),Error(`\uD83D\uDED1 LIMIT REACHED: Repeated the same tool call ${repetitionCount} times. This suggests a loop. Return your progress summary.`);if(window2.consecutiveErrors>=agentConfig.max_consecutive_errors)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"consecutive_errors",window2.consecutiveErrors),Error(`\uD83D\uDED1 LIMIT REACHED: ${window2.consecutiveErrors} consecutive tool errors detected. Return your progress summary with details of what went wrong. Run /swarm reset-session to clear the circuit breaker without restarting your session.`);let idleMinutes=(Date.now()-window2.lastSuccessTimeMs)/60000;if(idleMinutes>=agentConfig.idle_timeout_minutes)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"idle_timeout",idleMinutes),warn("Circuit breaker: idle timeout hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,idleTimeoutMinutes:agentConfig.idle_timeout_minutes,idleMinutes:Math.floor(idleMinutes)}),Error(`\uD83D\uDED1 LIMIT REACHED: No successful tool call for ${Math.floor(idleMinutes)} minutes (idle timeout: ${agentConfig.idle_timeout_minutes} min). This suggests the agent may be stuck. Return your progress summary.`);if(!window2.warningIssued){let toolPct=agentConfig.max_tool_calls>0?window2.toolCalls/agentConfig.max_tool_calls:0,durationPct=agentConfig.max_duration_minutes>0?elapsedMinutes/agentConfig.max_duration_minutes:0,repPct=repetitionCount/agentConfig.max_repetitions,errorPct=window2.consecutiveErrors/agentConfig.max_consecutive_errors,reasons=[];if(agentConfig.max_tool_calls>0&&toolPct>=agentConfig.warning_threshold)reasons.push(`tool calls ${window2.toolCalls}/${agentConfig.max_tool_calls}`);if(durationPct>=agentConfig.warning_threshold)reasons.push(`duration ${Math.floor(elapsedMinutes)}/${agentConfig.max_duration_minutes} min`);if(repPct>=agentConfig.warning_threshold)reasons.push(`repetitions ${repetitionCount}/${agentConfig.max_repetitions}`);if(errorPct>=agentConfig.warning_threshold)reasons.push(`errors ${window2.consecutiveErrors}/${agentConfig.max_consecutive_errors}`);if(reasons.length>0)window2.warningIssued=!0,window2.warningReason=reasons.join(", ")}}function handleDelegatedWriteTracking(sessionID,tool,args2){if(!swarmState.agentSessions.get(sessionID)?.delegationActive&&isArchitect(sessionID)){let coderDeleg=isAgentDelegation(tool,args2);if(coderDeleg.isDelegation&&coderDeleg.targetAgent==="coder"){let coderSession=swarmState.agentSessions.get(sessionID);if(coderSession){let taskId=coderSession.currentTaskId??coderSession.lastCoderDelegationTaskId??`${sessionID}:unknown`;if(coderSession.currentTaskId=taskId,resetModifiedFilesForTask(coderSession,taskId),!coderSession.revisionLimitHit)coderSession.coderRevisions=0}}}}function isAgentDelegation(toolName,args2){if(!isTaskToolId(toolName))return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function handleLoopDetection(sessionID,tool,args2){if(!isTaskToolId(tool))return;let loopArgs=args2,loopResult=detectLoop(sessionID,tool,loopArgs);if(loopResult.count>=5)throw Error(`CIRCUIT BREAKER: Delegation loop detected (${loopResult.count} identical patterns). Further identical delegations are blocked. Diagnose or rescope the task before retrying.`);else if(loopResult.count>=3&&loopResult.count<5){let agentName=typeof loopArgs?.subagent_type==="string"?loopArgs.subagent_type:"agent",loopSession=swarmState.agentSessions.get(sessionID);if(loopSession){let loopPattern=loopResult.pattern,modifiedFiles=loopSession.currentTaskId?getModifiedFilesForTask(loopSession,loopSession.currentTaskId):[],accomplishmentSummary=modifiedFiles.length>0?`Modified ${modifiedFiles.length} file(s): ${modifiedFiles.slice(0,3).join(", ")}${modifiedFiles.length>3?"...":""}`:"No files modified yet",alternativeSuggestions={coder:"Try a different task spec, simplify the constraint, or escalate to user",reviewer:"Try a different review dimension or escalate to user",test_engineer:"Run a specific test file with targeted scope",explorer:"Narrow the search scope or check a specific file directly"},cleanAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),suggestion=alternativeSuggestions[cleanAgent]??"Try a different agent, different instructions, or escalate to the user";loopSession.loopWarningPending={agent:agentName,message:[`LOOP DETECTED: Pattern "${loopPattern}" repeated 3 times.`,`Agent: ${agentName}`,`Accomplished: ${accomplishmentSummary}`,`Suggested action: ${suggestion}`,"If still stuck after trying alternatives, escalate to the user."].join(`
|
|
1175
1175
|
`),timestamp:Date.now()}}}}function handleTestSuiteBlocking(tool,args2){if(tool!=="bash"&&tool!=="shell")return;let bashArgs=args2,cmd=(typeof bashArgs?.command==="string"?bashArgs.command:"").trim();if(/^(bun\s+test|npm\s+test|npx\s+vitest|bunx\s+vitest)\b/.test(cmd)){let tokens=cmd.split(/\s+/),runnerTokenCount=tokens[0]==="npx"||tokens[0]==="bunx"?3:2;if(!tokens.slice(runnerTokenCount).some((token)=>token.length>0&&!token.startsWith("-")&&(token.includes("/")||token.includes("\\")||token.endsWith(".ts")||token.endsWith(".js")||token.endsWith(".tsx")||token.endsWith(".jsx")||token.endsWith(".mts")||token.endsWith(".mjs"))))throw Error("BLOCKED: Full test suite execution is not allowed in-session. Run a specific test file instead: bun test path/to/file.test.ts")}}function extractAllPatchPayloads(args2){let toolArgs=args2;if(!toolArgs)return[];let out=[];for(let key2 of PATCH_PAYLOAD_KEYS){let v=toolArgs[key2];if(typeof v==="string"&&v.length>0)out.push(v)}let cmd=toolArgs.cmd;if(Array.isArray(cmd)){for(let entry of cmd)if(typeof entry==="string"&&entry.length>0)out.push(entry)}return out}function getHumanOnlyAlternation(){return[...HUMAN_ONLY_SWARM_COMMANDS].map((c)=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).sort((a,b)=>b.length-a.length).join("|")}function patchPayloadHasHumanOnlyInvocation(args2){let payloads=extractAllPatchPayloads(args2);if(payloads.length===0)return!1;let alternation=getHumanOnlyAlternation(),re=new RegExp(`\\bopencode-swarm\\b[\\s\\S]*?\\brun\\s+(${alternation})\\b`,"i");return payloads.some((p)=>re.test(p))}function extractPatchTargetPaths(tool,args2){if(tool!=="apply_patch"&&tool!=="swarm_apply_patch"&&tool!=="patch")return[];let toolArgs=args2,paths=new Set;if(Array.isArray(toolArgs?.files)){for(let f of toolArgs.files)if(typeof f==="string"&&f.length>0&&f!=="/dev/null")paths.add(f)}let patchText;for(let key2 of["input","patch","diff"]){let v=toolArgs?.[key2];if(typeof v==="string"){patchText=v;break}}if(patchText===void 0)for(let key2 of PATCH_PAYLOAD_KEYS){if(key2==="patch"||key2==="input"||key2==="diff")continue;let v=toolArgs?.[key2];if(typeof v==="string"){patchText=v;break}}if(patchText===void 0&&Array.isArray(toolArgs?.cmd))patchText=toolArgs.cmd[1];if(typeof patchText!=="string")return Array.from(paths);if(patchText.length>1e6)throw Error("WRITE BLOCKED: Patch payload exceeds 1 MB — authority cannot be verified for all modified paths. Split into smaller patches.");let normalizedPatchText=normalizePatchIndentation(patchText),patchPathPattern=/\*\*\*\s+(?:Update|Add|Delete)\s+File:\s*(.+)/gi,diffPathPattern=/\+\+\+\s+b\/(.+)/gm,gitDiffPathPattern=/^diff --git a\/(.+?) b\/(.+?)$/gm,minusPathPattern=/^---\s+a\/(.+)$/gm,traditionalMinusPattern=/^---\s+([^\s].+?)(?:\t.*)?$/gm,traditionalPlusPattern=/^\+\+\+\s+([^\s].+?)(?:\t.*)?$/gm;for(let match of normalizedPatchText.matchAll(patchPathPattern))paths.add(match[1].trim());for(let match of normalizedPatchText.matchAll(diffPathPattern)){let p=match[1].trim();if(p!=="/dev/null")paths.add(p)}for(let match of normalizedPatchText.matchAll(gitDiffPathPattern)){let aPath=match[1].trim(),bPath=match[2].trim();if(aPath!=="/dev/null")paths.add(aPath);if(bPath!=="/dev/null")paths.add(bPath)}for(let match of normalizedPatchText.matchAll(minusPathPattern)){let p=match[1].trim();if(p!=="/dev/null")paths.add(p)}for(let match of normalizedPatchText.matchAll(traditionalMinusPattern)){let p=match[1].trim();if(p!=="/dev/null"&&!p.startsWith("a/")&&!p.startsWith("b/"))paths.add(p)}for(let match of normalizedPatchText.matchAll(traditionalPlusPattern)){let p=match[1].trim();if(p!=="/dev/null"&&!p.startsWith("a/")&&!p.startsWith("b/"))paths.add(p)}return Array.from(paths)}function handlePlanAndScopeProtection(sessionID,tool,args2){let toolArgs=args2,targetPath=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(tool==="apply_patch"||tool==="swarm_apply_patch"||tool==="patch"){if(patchPayloadHasHumanOnlyInvocation(args2))throw Error("BLOCKED: apply_patch/swarm_apply_patch would introduce a script invoking a human-only swarm CLI subcommand. Present the situation to the user and ask them to run the command themselves.")}if(typeof targetPath==="string"&&targetPath.length>0){let resolvedTarget=path83.resolve(effectiveDirectory,targetPath).toLowerCase(),planMdPath=path83.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path83.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase();if(resolvedTarget===planMdPath||resolvedTarget===planJsonPath)throw Error("PLAN STATE VIOLATION: Direct writes to .swarm/plan.md and .swarm/plan.json are blocked. plan.md is auto-regenerated from plan.json by PlanSyncWorker. Use save_plan for ALL structural plan changes (adding/removing tasks, updating descriptions, dependencies, or phase names). Use update_task_status() for task status only. Use phase_complete() for phase transitions only.");let specStalenessPath=path83.resolve(effectiveDirectory,".swarm","spec-staleness.json").toLowerCase();if(resolvedTarget===specStalenessPath)throw Error("SPEC_DRIFT_VIOLATION: Direct writes to .swarm/spec-staleness.json are blocked. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.");let content=toolArgs?.content??toolArgs?.text??toolArgs?.new_string??toolArgs?.newText;if(typeof content==="string"&&new RegExp(`\\bopencode-swarm\\b[\\s\\S]*?\\brun\\s+(${getHumanOnlyAlternation()})\\b`,"i").test(content))throw Error("BLOCKED: write/edit tool would create a script invoking a human-only swarm CLI subcommand. Present the situation to the user and ask them to run the command themselves.")}if(!targetPath&&(tool==="apply_patch"||tool==="swarm_apply_patch"||tool==="patch"))for(let p of extractPatchTargetPaths(tool,args2)){let resolvedP=path83.resolve(effectiveDirectory,p),planMdPath=path83.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path83.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase(),specStalenessPath=path83.resolve(effectiveDirectory,".swarm","spec-staleness.json").toLowerCase();if(resolvedP.toLowerCase()===planMdPath||resolvedP.toLowerCase()===planJsonPath)throw Error("PLAN STATE VIOLATION: Direct writes to .swarm/plan.md and .swarm/plan.json are blocked. plan.md is auto-regenerated from plan.json by PlanSyncWorker. Use save_plan for ALL structural plan changes (adding/removing tasks, updating descriptions, dependencies, or phase names). Use update_task_status() for task status only. Use phase_complete() for phase transitions only.");if(resolvedP.toLowerCase()===specStalenessPath)throw Error("SPEC_DRIFT_VIOLATION: Direct writes to .swarm/spec-staleness.json are blocked. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.");if(isOutsideSwarmDir(p,effectiveDirectory)&&(isSourceCodePath(p)||hasTraversalSegments(p))){let session=swarmState.agentSessions.get(sessionID);if(session)session.architectWriteCount++,warn("Architect direct code edit detected via patch tool",{tool,sessionID,targetPath:p,writeCount:session.architectWriteCount});break}}if(typeof targetPath==="string"&&targetPath.length>0&&isOutsideSwarmDir(targetPath,effectiveDirectory)&&isSourceCodePath(path83.relative(effectiveDirectory,path83.resolve(effectiveDirectory,targetPath)))){let session=swarmState.agentSessions.get(sessionID);if(session){if(session.architectWriteCount++,warn("Architect direct code edit detected",{tool,sessionID,targetPath,writeCount:session.architectWriteCount}),session.lastGateFailure&&Date.now()-session.lastGateFailure.timestamp<120000){let failedGate=session.lastGateFailure.tool,failedTaskId=session.lastGateFailure.taskId;warn("Self-fix after gate failure detected",{failedGate,failedTaskId,currentTool:tool,sessionID}),session.selfFixAttempted=!0}}}}function resolveSessionAndWindow(sessionID){let rawActiveAgent=swarmState.activeAgent.get(sessionID),strippedAgent=rawActiveAgent?stripKnownSwarmPrefix(rawActiveAgent):void 0;if(strippedAgent===ORCHESTRATOR_NAME)return null;if(strippedAgent&&isNativeOpencodeAgent(strippedAgent))return null;let existingSession=swarmState.agentSessions.get(sessionID);if(existingSession){let sessionAgent=stripKnownSwarmPrefix(existingSession.agentName);if(sessionAgent===ORCHESTRATOR_NAME)return null;if(isNativeOpencodeAgent(sessionAgent))return null}let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME,session=ensureAgentSession(sessionID,agentName),resolvedName=stripKnownSwarmPrefix(session.agentName);if(resolvedName===ORCHESTRATOR_NAME)return null;if(isNativeOpencodeAgent(resolvedName))return null;let agentConfig=resolveGuardrailsConfig(cfg,session.agentName);if(agentConfig.max_duration_minutes===0&&agentConfig.max_tool_calls===0)return null;if(!getActiveWindow(sessionID)){let fallbackAgent=swarmState.activeAgent.get(sessionID)??session.agentName;if(stripKnownSwarmPrefix(fallbackAgent)!==ORCHESTRATOR_NAME)beginInvocation(sessionID,fallbackAgent)}let window2=getActiveWindow(sessionID);if(!window2)return null;return{agentConfig,window:window2}}function isNativeOpencodeAgent(agentName){return OPENCODE_NATIVE_AGENTS.has(agentName.toLowerCase())}function trackToolCall(window2,tool,args2){if(window2.hardLimitHit)throw Error("\uD83D\uDED1 CIRCUIT BREAKER: Agent blocked. Hard limit was previously triggered. Stop making tool calls and return your progress summary.");window2.toolCalls++;let hash3=hashArgs(args2);if(window2.recentToolCalls.push({tool,argsHash:hash3,timestamp:Date.now()}),window2.recentToolCalls.length>20)window2.recentToolCalls.shift();let repetitionCount=0;if(window2.recentToolCalls.length>0){let lastEntry=window2.recentToolCalls[window2.recentToolCalls.length-1];for(let i=window2.recentToolCalls.length-1;i>=0;i--){let entry=window2.recentToolCalls[i];if(entry.tool===lastEntry.tool&&entry.argsHash===lastEntry.argsHash)repetitionCount++;else break}}let elapsedMinutes=(Date.now()-window2.startedAtMs)/60000;return{repetitionCount,elapsedMinutes}}return async(input,output)=>{assertNonTransientCircuitAllowsTool(input.sessionID,{tool:input.tool,args:output.args});let resolvedSessionWindow=swarmState.agentSessions.has(input.sessionID)||swarmState.activeAgent.has(input.sessionID)?resolveSessionAndWindow(input.sessionID):null,session=swarmState.agentSessions.get(input.sessionID),rawAgentForScope=swarmState.activeAgent.get(input.sessionID),isCoder=rawAgentForScope!==void 0&&stripKnownSwarmPrefix(rawAgentForScope).toLowerCase()==="coder";consecutiveNoToolTurns.set(input.sessionID,0),observeExecutionStallToolCall({sessionID:input.sessionID,tool:input.tool,args:output.args,callID:input.callID,options:executionStallOptions}),handleDelegatedWriteTracking(input.sessionID,input.tool,output.args),handleLoopDetection(input.sessionID,input.tool,output.args),handleTestSuiteBlocking(input.tool,output.args);let rawShellCommand=(()=>{let bashArgs=output.args;return typeof bashArgs?.command==="string"?bashArgs.command:""})(),normalizedAuditTool=normalizeToolName(input.tool).toLowerCase();if(normalizedAuditTool==="bash"||normalizedAuditTool==="shell")appendGuardrailDecision({type:"shell",ts:new Date().toISOString(),sessionID:input.sessionID,agent:(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})(),tool:input.tool,command:(()=>{let bashArgs=output.args,rawCmd=typeof bashArgs?.command==="string"?bashArgs.command:"";return redactShellCommand(rawCmd)})()},{directory:effectiveDirectory,enabled:shellAuditEnabled});handleInterpreterGating(input.sessionID,input.tool);try{checkDestructiveCommand(input.sessionID,input.tool,output.args)}catch(err){let destructiveCategory=err instanceof DestructiveCommandBlockedError?err.destructiveCategory:"destructive shell command";throw appendGuardrailDecision({type:"destructive_block",ts:new Date().toISOString(),sessionID:input.sessionID,agent:(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})(),tool:input.tool,command:(()=>{let bashArgs=output.args;return typeof bashArgs?.command==="string"?bashArgs.command:""})(),destructiveCategory},{directory:effectiveDirectory,enabled:shellAuditEnabled}),err}try{checkShellWriteScope(input.sessionID,input.callID,input.tool,output.args,rawShellCommand)}catch(err){let toolArgs=output.args,declaredScope=resolveDeclaredScope(input.sessionID),declaredScopeText=declaredScope!=null&&declaredScope.length>0?declaredScope.join(", "):"",resolvedScopeText=declaredScope!=null&&declaredScope.length>0?resolveScopePaths(declaredScope,sessionWorkspaceDirectory(input.sessionID)).paths.join(", "):"",pathMatch=/[^\s]+/.exec(err instanceof Error?err.message:String(err)),targetPath=(()=>{let p=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(typeof p==="string"&&p.length>0)return p;let rawMessage=err instanceof Error?err.message:String(err),extracted=/(?:write|target|file|path|scope|prefix)[^:]*:\s*(?:"([^"]+)"|'([^']+)'|(\S+))/i.exec(rawMessage)??/(?:write|target|file|path)\s+(?:"([^"]+)"|'([^']+)'|(\S+))/i.exec(rawMessage),candidate=extracted!=null?extracted[1]??extracted[2]??extracted[3]??extracted[4]??extracted[5]??extracted[6]:null;if(candidate&&candidate.length>0&&candidate.length<200)return candidate;if(pathMatch)return pathMatch[0];return"<shell write>"})(),agentName=(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})();throw appendGuardrailDecision({type:"scope_violation",ts:new Date().toISOString(),sessionID:input.sessionID,agent:agentName,tool:input.tool,path:targetPath,declaredScope:declaredScopeText,resolvedScope:resolvedScopeText,action:"bash"},{directory:effectiveDirectory,enabled:shellAuditEnabled}),err}let agentNameForSandbox=(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})();if(rememberToolExecution(input.sessionID,input.callID,input.tool,rawShellCommand),await applySandboxExecution(input.sessionID,input.callID,input.tool,output.args,agentNameForSandbox,rawShellCommand,shellAuditEnabled),enforceSpecDriftGate(effectiveDirectory,input.tool),isArchitect(input.sessionID)&&isWriteTool(input.tool))handlePlanAndScopeProtection(input.sessionID,input.tool,output.args);let writeDirectory=sessionWorkspaceDirectory(input.sessionID),resolvedFileTargets=null;if(isWriteTool(input.tool)){let resolution=resolveWriteTargets2(normalizeToolName(input.tool),output.args,{directory:writeDirectory});if(resolution.status==="unverifiable")throw Error(`WRITE TARGET UNVERIFIABLE: ${resolution.reason}`);else resolvedFileTargets=resolution.paths;let writeBinding=session?.currentTaskId&&isCoder?resolveActiveScopeBinding(input.sessionID):null;if(writeBinding)rememberScopeLeaseCandidate?.({callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:writeDirectory,binding:writeBinding,targets:(resolvedFileTargets??[]).map((target)=>path83.resolve(writeDirectory,target)),args:output.args})}if(isWriteTool(input.tool))for(let targetPath of resolvedFileTargets??[]){let agentName=swarmState.activeAgent.get(input.sessionID);if(!agentName)throw Error(`WRITE BLOCKED: No active agent registered for session "${input.sessionID}". Call startAgentSession before issuing write tool calls.`);let lstatBlock=checkWriteTargetForSymlink(targetPath,writeDirectory);if(lstatBlock)throw appendGuardrailDecision({type:"file_write",ts:new Date().toISOString(),sessionID:input.sessionID,agent:agentName,tool:input.tool,path:targetPath,reason:lstatBlock,resolvedScope:(()=>{let scope=resolveDeclaredScope(input.sessionID);return scope!=null&&scope.length>0?scope.join(", "):""})()},{directory:effectiveDirectory,enabled:shellAuditEnabled}),Error(lstatBlock);let writeBinding=session?.currentTaskId&&isCoder?resolveActiveScopeBinding(input.sessionID):null,writeDeclaredScope=writeBinding?.files??null,authorityCheck=checkFileAuthorityWithRules(agentName,targetPath,writeDirectory,precomputedAuthorityRules,{declaredScope:writeDeclaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID:input.sessionID,childSessionID:input.sessionID,category:"protected_state_mutation",paths:[targetPath]}):void 0;throw appendGuardrailDecision({type:"file_write",ts:new Date().toISOString(),sessionID:input.sessionID,agent:agentName,tool:input.tool,path:targetPath,reason:authorityCheck.reason,resolvedScope:(()=>{let scope=writeDeclaredScope;return scope!=null&&scope.length>0?scope.join(", "):""})()},{directory:effectiveDirectory,enabled:shellAuditEnabled}),Error(`WRITE BLOCKED: Agent "${agentName}" is not authorised to write "${targetPath}". Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}let trackingSession=swarmState.agentSessions.get(input.sessionID),auditContext=trackingSession?.delegationActive?"delegated":"direct",auditOperation=["apply_patch","swarm_apply_patch","patch"].includes(normalizeToolName(input.tool))?"patch":"write";if(isConfigFilePath(targetPath,writeDirectory,authorityConfig?.verifier_config_paths)){let normalizedPath=path83.relative(path83.resolve(writeDirectory),path83.resolve(writeDirectory,targetPath)).replace(/\\/g,"/"),logEntry={agent:agentName,path:normalizedPath,allowed:authorityCheck.allowed,type:`${auditContext}_${auditOperation}`};if(!authorityCheck.allowed&&"reason"in authorityCheck)logEntry.reason=authorityCheck.reason;warn("Config file write attempt",logEntry)}if(trackingSession?.delegationActive){let taskId=trackingSession.currentTaskId??trackingSession.lastCoderDelegationTaskId??`${input.sessionID}:unknown`;trackingSession.currentTaskId=taskId,recordModifiedFileForTask(trackingSession,taskId,targetPath)}if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path83.relative(path83.resolve(writeDirectory),path83.resolve(writeDirectory,targetPath)).replace(/\\/g,"/");if(recordReviewerScopeGenerationFile({parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget}))rememberReviewerScopeWrite?.({callID:input.callID,parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget})}}let resolved=resolvedSessionWindow;if(resolved){let{agentConfig,window:window2}=resolved,{repetitionCount,elapsedMinutes}=trackToolCall(window2,input.tool,output.args);await checkGateLimits({sessionID:input.sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount})}{let prmSession=swarmState.agentSessions.get(input.sessionID);if(prmSession?.prmHardStopPending){prmSession.prmHardStopPending=!1;let patternType=prmSession.prmLastPatternDetected?.pattern??"unknown";throw telemetry.prmHardStopDelivered(input.sessionID,patternType,prmSession.prmEscalationLevel,prmSession.prmPatternCounts?.get(patternType)??0),Error("\uD83D\uDED1 PRM HARD STOP: Pattern escalation maximum reached. Stop tool calls and return progress summary.")}}if(enforceInternalsGuard({sessionID:input.sessionID,tool:input.tool,args:output.args,directory:effectiveDirectory,options:internalsGuardOptions}),enforceExecutionStallDenial({sessionID:input.sessionID,tool:input.tool,options:executionStallOptions}),!resolved)return;setStoredInputArgs(input.callID,output.args)}}var hasWarnedSandboxUnavailable=!1,DestructiveCommandBlockedError;var init_tool_before=__esm(()=>{init_tool_policy();init_constants();init_schema();init_severe_result();init_executor();init_scope_resolver();init_skip_state();init_path_identity();init_scope_persistence();init_scope_resolution_diagnostic();init_command_classifier();init_state2();init_telemetry();init_utils();init_core3();init_loop_detector();init_normalize_tool_name();init_shell_write_detect();init_write_target_resolver();init_audit_log();init_destructive_command();init_execution_stall();init_file_authority();init_guardrails();init_internals_guard();init_nontransient_circuit();init_stored_input_args();init_helpers();DestructiveCommandBlockedError=class DestructiveCommandBlockedError extends Error{destructiveCategory;constructor(message,destructiveCategory){super(message);this.destructiveCategory=destructiveCategory;this.name="DestructiveCommandBlockedError"}}});import*as fsSync10 from"node:fs";import*as path84 from"node:path";function emitDurableAttributionAdvisory(sessionID,key2,message){let now=Date.now(),prior=durableAttributionAdvisoryBySession.get(sessionID);if(prior&&prior.key===key2&&now-prior.at<DURABLE_ATTRIBUTION_ADVISORY_COOLDOWN_MS)return;if(!prior&&durableAttributionAdvisoryBySession.size>=MAX_DURABLE_ATTRIBUTION_ADVISORY_SESSIONS){let oldest=durableAttributionAdvisoryBySession.keys().next().value;if(oldest!==void 0)durableAttributionAdvisoryBySession.delete(oldest)}durableAttributionAdvisoryBySession.set(sessionID,{key:key2,at:now});let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,message);else criticalWarn(`[guardrails] ${message}`)}function stageAWriteErrorCode(error49){let message=error49 instanceof Error?error49.message:String(error49),match=/^[A-Z][A-Z0-9_]+/.exec(message);return match?match[0]:null}function extractGateCallFiles(args2){if(!args2||typeof args2!=="object")return null;let raw=args2.files;if(Array.isArray(raw)){let files=raw.filter((entry)=>typeof entry==="string"&&entry!=="");return files.length>0?files:null}let changed2=args2.changed_files;if(Array.isArray(changed2)){let files=changed2.map((entry)=>typeof entry==="string"?entry:entry&&typeof entry==="object"&&typeof entry.path==="string"?entry.path:null).filter((entry)=>entry!==null&&entry!=="");return files.length>0?files:null}return null}async function resolveDurableGateTaskId(directory,callerFiles){try{let{states,truncated}=await listCoderSettlementWalStates(directory),eligible=[],inFlightAtCoderDelegated=new Set;for(let state of states){if(!isStrictTaskId(state.taskId))continue;if(state.state==="DISPATCHED"||state.state==="PREPARED"){if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state.taskId)).state==="coder_delegated")inFlightAtCoderDelegated.add(state.taskId);continue}if(state.state!=="COMMITTED")continue;if(state.accepted!==!0)continue;if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state.taskId)).state==="coder_delegated")eligible.push(state)}let ambiguousIds=new Set([...eligible.map((s)=>s.taskId),...inFlightAtCoderDelegated]);if(ambiguousIds.size>1)return{ambiguous:[...ambiguousIds].sort()};if(eligible.length===1){let candidate=eligible[0];if(truncated)return{unbound:candidate.taskId,reason:"truncated"};let declared=candidate.declaredFiles,normalizedCallerFiles=callerFiles!==null?normalizeScopeFiles(callerFiles):null;if(normalizedCallerFiles!==null&&normalizedCallerFiles.length>0&&declared!==null&&declared!==void 0&&declared.length>0&&declared.some((f)=>f!==""&&normalizedCallerFiles.includes(f)))return{taskId:candidate.taskId};return{unbound:candidate.taskId,reason:"files_mismatch"}}return null}catch(error49){return warn("Durable gate attribution fallback failed",{error:String(error49)}),null}}function enforceSpecDriftGate(directory,toolName){if(!directory)return;if(!SPEC_DRIFT_BLOCKED_TOOLS.has(toolName))return;let stalePath=path84.join(directory,".swarm","spec-staleness.json");if(fsSync10.existsSync(stalePath)){let diffInfo=null;try{diffInfo=computeSpecDiff(directory)}catch{}let message=`SPEC_DRIFT_BLOCK: tool "${toolName}" is blocked because .swarm/spec-staleness.json exists. Run /swarm clarify to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run /swarm acknowledge-spec-drift to dismiss, then retry.`;if(diffInfo){let sectionSummary=diffInfo.changedSections.length>0?`
|
|
1176
1176
|
Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:"";message+=`
|
|
1177
1177
|
|
|
@@ -1180,7 +1180,7 @@ Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:""
|
|
|
1180
1180
|
`+diffInfo.diff+`
|
|
1181
1181
|
[End spec diff]`}else message+=`
|
|
1182
1182
|
|
|
1183
|
-
(no recorded snapshot to diff against)`;throw Error(message)}}function isPlainObject3(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function readSignalField(source,key2){try{return source[key2]}catch{return}}function pushSignalValue(parts,value){if(typeof value==="string"){parts.push(value);return}if(typeof value==="number"||typeof value==="boolean")parts.push(String(value))}function appendSelectedFields(parts,source,keys){for(let key2 of keys)pushSignalValue(parts,readSignalField(source,key2))}function appendNestedErrorSignal(parts,value){if(typeof value==="string"){parts.push(value);return}if(value instanceof Error){parts.push(value.name,value.message),appendSelectedFields(parts,value,["code","status","statusCode"]);return}if(!isPlainObject3(value))return;appendSelectedFields(parts,value,["code","status","statusCode","message","error_type"])}function extractErrorSignal(errorContent){if(typeof errorContent==="string")return errorContent;if(errorContent==null)return"";let parts=[];try{if(errorContent instanceof Error)return parts.push(errorContent.name,errorContent.message),appendSelectedFields(parts,errorContent,["code","status","statusCode"]),parts.join(" ");if(!isPlainObject3(errorContent))return"";appendSelectedFields(parts,errorContent,["code","status","statusCode","message","error_type"]),appendNestedErrorSignal(parts,readSignalField(errorContent,"error"));let metadata=readSignalField(errorContent,"metadata");if(isPlainObject3(metadata))appendSelectedFields(parts,metadata,["code","status","statusCode","error_type"]);appendNestedErrorSignal(parts,readSignalField(errorContent,"cause"))}catch{return parts.join(" ")}return parts.join(" ")}function touchNoOpSession(sessionID,count){toolCallsSinceLastWrite.delete(sessionID),toolCallsSinceLastWrite.set(sessionID,count),evictNoOpStateIfOverBound()}function evictNoOpStateIfOverBound(){while(toolCallsSinceLastWrite.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=toolCallsSinceLastWrite.keys().next().value;if(stalestKey===void 0)break;toolCallsSinceLastWrite.delete(stalestKey),noOpWarningIssued.delete(stalestKey),noOpStrongWarningIssued.delete(stalestKey)}while(noOpWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpWarningIssued.delete(stalestKey)}while(noOpStrongWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpStrongWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpStrongWarningIssued.delete(stalestKey)}}function extractPhaseNumber2(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function isWriteTool2(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isGateTool(toolName){let normalized=normalizeToolName(toolName);return["diff","syntax_check","placeholder_scan","imports","lint","build_check","pre_check_batch","secretscan","sast_scan","quality_budget"].includes(normalized)}function isAgentDelegation(toolName,args2){let normalized=normalizeToolName(toolName);if(normalized!=="Task"&&normalized!=="task")return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function createGuardrailsHooks(directory,directoryOrConfig,config2,authorityConfig,worktreeBaseDirOverrides,resolveAgentModel){let guardrailsConfig;if(directory&&typeof directory==="object"&&"enabled"in directory)warn("[guardrails] Legacy call without directory, falling back to process.cwd()"),guardrailsConfig=directory;else if(directoryOrConfig&&typeof directoryOrConfig==="object"&&"enabled"in directoryOrConfig)guardrailsConfig=directoryOrConfig;else guardrailsConfig=config2;let effectiveDirectory=(()=>{if(typeof directory==="string")return directory;let cwd=process.cwd();return warn(`[guardrails] effectiveDirectory resolved to process.cwd() "${cwd}" — `+"pass an explicit directory string to createGuardrailsHooks to avoid .swarm artifacts in wrong locations"),cwd})();if(guardrailsConfig?.enabled===!1)return{toolBefore:async()=>{},toolAfter:async()=>{},messagesTransform:async()=>{}};let precomputedAuthorityRules=buildEffectiveRules(authorityConfig),verifierPaths=authorityConfig?.verifier_config_paths;if(verifierPaths&&verifierPaths.length>0){let existingArchitect=precomputedAuthorityRules.architect??{};precomputedAuthorityRules.architect={...existingArchitect,blockedGlobs:[...existingArchitect.blockedGlobs??[],...verifierPaths]}}let universalDenyPrefixes=authorityConfig?.universal_deny_prefixes??[],cfg=guardrailsConfig,requiredQaGates=cfg.qa_gates?.required_tools??["diff","syntax_check","placeholder_scan","lint","pre_check_batch"],requireReviewerAndTestEngineer=cfg.qa_gates?.require_reviewer_test_engineer??!0,interpreterAllowedAgents=cfg.interpreter_allowed_agents,shellAuditEnabled=cfg.shell_audit_log??!0,consecutiveNoToolTurns=new Map,lastCountedAssistantMsgId=new Map,pendingReviewerScopeWrites=new Map,pendingGateTasksBySession=new Map,takePendingGateTask=(sessionID,callID)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID),pending=sessionTasks?.get(callID);if(sessionTasks){if(sessionTasks.delete(callID),sessionTasks.size===0)pendingGateTasksBySession.delete(sessionID)}return pending},rememberPendingGateTask=(sessionID,callID,taskId,generation)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID);if(!sessionTasks){if(pendingGateTasksBySession.size>=MAX_PENDING_GATE_RECEIPT_SESSIONS)throw Error("GATE_RECEIPT_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionTasks=new Map,pendingGateTasksBySession.set(sessionID,sessionTasks)}if(!sessionTasks.has(callID)&&sessionTasks.size>=MAX_PENDING_GATE_RECEIPTS_PER_SESSION)throw Error("GATE_RECEIPT_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionTasks.set(callID,{sessionID,taskId,generation})},scopeLeaseRenewal=createScopeLeaseRenewalTracker(),rememberReviewerScopeWrite=(input)=>{if(!pendingReviewerScopeWrites.has(input.callID)&&pendingReviewerScopeWrites.size>=256){let oldest=pendingReviewerScopeWrites.keys().next().value;if(oldest!==void 0)pendingReviewerScopeWrites.delete(oldest)}let pending=pendingReviewerScopeWrites.get(input.callID)??[],candidate={parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,file:input.file};if(!pending.some((entry)=>entry.parentSessionID===candidate.parentSessionID&&entry.taskId===candidate.taskId&&entry.coderCallID===candidate.coderCallID&&entry.file===candidate.file)&&pending.length<256)pending.push(candidate);pendingReviewerScopeWrites.set(input.callID,pending)},executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},baseToolBefore=createToolBeforeHandler({effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,rememberReviewerScopeWrite,rememberScopeLeaseCandidate:scopeLeaseRenewal.remember,getSandboxExecutor:_internals75.getSandboxExecutor,assessSandboxEnforcement:_internals75.assessSandboxEnforcement}),toolBefore=async(input,output)=>{if(isGateTool(input.tool)){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId;if(!taskId){let callerFiles=extractGateCallFiles(output.args),fallback=await _internals75.resolveDurableGateTaskId(effectiveDirectory,callerFiles);if(fallback){if("taskId"in fallback)taskId=fallback.taskId;else if("ambiguous"in fallback&&fallback.ambiguous.length>0){let shown=fallback.ambiguous.slice(0,10),more=fallback.ambiguous.length-shown.length;emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00${fallback.ambiguous.join(",")}`,`STAGE A ATTRIBUTION AMBIGUOUS: ${fallback.ambiguous.length} tasks are settled at coder_delegated (${shown.join(", ")}${more>0?`, +${more} more`:""}) but this session has no task correlation after reset-session. Stage A evidence cannot be attributed safely. Run /swarm recover to repair Stage A attribution, then re-run the gate.`)}else if("unbound"in fallback)emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00unbound\x00${fallback.unbound}`,fallback.reason==="truncated"?`STAGE A ATTRIBUTION UNVERIFIABLE: task ${fallback.unbound} looks like the sole durable candidate at coder_delegated, but the settlement scan is truncated (more than 200 historical settlements) so a second candidate cannot be ruled out. Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`:`STAGE A ATTRIBUTION UNBOUND: task ${fallback.unbound} is the sole durable candidate at coder_delegated, but this gate call's scanned files do not match its declared changes (or no file scope was provided). Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`)}}if(taskId){let workflow=isStrictTaskId(taskId)?getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId)):null;rememberPendingGateTask(input.sessionID,input.callID,taskId,workflow?.generation??0)}}try{await baseToolBefore(input,output)}catch(error49){throw takePendingGateTask(input.sessionID,input.callID),error49}},messagesTransform=createMessagesTransformHandler({effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId,resolveAgentModel});return{toolBefore,toolAfter:async(input,output)=>{let pendingGateTask=takePendingGateTask(input.sessionID,input.callID)??(_internals75.allowUncorrelatedGateReceipts?(()=>{let testSession=swarmState.agentSessions.get(input.sessionID);return testSession?{sessionID:input.sessionID,taskId:testSession.currentTaskId??`${input.sessionID}:unknown`,generation:testSession.currentTaskId&&isStrictTaskId(testSession.currentTaskId)?testSession.taskWorkflowCache?.get(testSession.currentTaskId)?.generation??0:0}:void 0})():void 0),pendingReviewerScopeWrite=pendingReviewerScopeWrites.get(input.callID);pendingReviewerScopeWrites.delete(input.callID);let correlatedExecution=takeToolExecution(input.sessionID,input.callID);if(correlatedExecution&&!isToolExecutionCurrent(input.sessionID,correlatedExecution)){await scopeLeaseRenewal.consume({...input,output:null});return}let malformedOutput=!output||typeof output!=="object",safeOutput=malformedOutput?{title:"",output:"",metadata:null}:output;await scopeLeaseRenewal.consume({...input,output:malformedOutput?null:safeOutput});let session=swarmState.agentSessions.get(input.sessionID);if(session){if(isGateTool(input.tool)&&pendingGateTask?.sessionID===input.sessionID){let taskId=pendingGateTask.taskId;if(!session.gateLog.has(taskId))session.gateLog.set(taskId,new Set);session.gateLog.get(taskId)?.add(input.tool);let outputStr=typeof safeOutput.output==="string"?safeOutput.output:"";if(normalizeToolName(input.tool)==="pre_check_batch"){let verdict=decodePreCheckResult(safeOutput.output);if(verdict.kind==="fail"||verdict.kind==="invalid"){if(session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now(),code:verdict.code},verdict.kind==="fail"&&isStrictTaskId(taskId))try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_failed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next)}catch(err){let code=stageAWriteErrorCode(err);if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A failure write failed for task ${taskId}: ${code}. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch failed but the rework transition was rejected. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to persist Stage A failure",{taskId,error:String(err)})}}else if(verdict.kind==="pass"){if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)==="pre_check_batch")session.lastGateFailure=null;if(!isStrictTaskId(taskId))advanceTaskState(session,taskId,"pre_check_passed");try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_passed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next)}catch(err){let code=stageAWriteErrorCode(err);if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A write failed for task ${taskId}: ${code} — pre_check_batch result was NOT attributed. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch passed but the workflow transition was rejected, so Stage B dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to advance task state after pre_check_batch pass",{taskId,error:String(err)})}}}else if(safeOutput.output===null||safeOutput.output===void 0||outputStr.includes("FAIL")||outputStr.includes("error")||outputStr.toLowerCase().includes("gates_passed: false"))session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now()};else if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)===normalizeToolName(input.tool))session.lastGateFailure=null}let inputArgs=input.args??getStoredInputArgs(input.callID),delegation=isAgentDelegation(input.tool,inputArgs);if(delegation.isDelegation&&(delegation.targetAgent==="reviewer"||delegation.targetAgent==="test_engineer")){let currentPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan){let phaseString=extractCurrentPhaseFromPlan(plan);currentPhase=extractPhaseNumber2(phaseString)}}catch(error49){log("[Guardrails] loadPlan failed during reviewer tracking",{error:error49 instanceof Error?error49.message:String(error49)})}let count=session.reviewerCallCount.get(currentPhase)??0;session.reviewerCallCount.set(currentPhase,count+1)}if(delegation.isDelegation&&delegation.targetAgent==="coder"){let exactGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:input.sessionID,coderCallID:input.callID}),completedTaskId=exactGeneration?.taskId??session.lastCoderDelegationTaskId;if(completedTaskId){session.currentTaskId=completedTaskId;let exactGenerationFiles=exactGeneration?.modifiedFiles??session.modifiedFilesThisCoderTask;if(!session.revisionLimitHit){if(session.coderRevisions++,session.coderRevisions>1&&session.qaSkipCount===0){let conflictPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan)conflictPhase=extractPhaseNumber2(extractCurrentPhaseFromPlan(plan))}catch{}resolveAgentConflict({sessionID:input.sessionID,phase:conflictPhase,taskId:session.currentTaskId??void 0,sourceAgent:"reviewer",targetAgent:"coder",conflictType:"feedback_rejection",rejectionCount:session.coderRevisions-1,summary:`Coder revision ${session.coderRevisions} for task ${session.currentTaskId??"unknown"}`}),session.lastDelegationReason="review_rejected"}let maxRevisions=cfg.max_coder_revisions??5;if(session.coderRevisions>=maxRevisions)session.revisionLimitHit=!0,telemetry.revisionLimitHit(input.sessionID,session.agentName),pushAdvisory(session,`CODER REVISION LIMIT: Agent has been revised ${session.coderRevisions} times (max: ${maxRevisions}) for task ${session.currentTaskId??"unknown"}. Escalate to user or consider a fundamentally different approach.`),swarmState.pendingEvents++}if(session.partialGateWarningsIssuedForTask?.delete(session.currentTaskId),session.declaredCoderScope!==null){let undeclaredFiles=exactGenerationFiles.map((f)=>f.replace(/[\r\n\t]/g,"_")).filter((f)=>!isInDeclaredScope(f,session.declaredCoderScope,directory));if(undeclaredFiles.length>=1){let safeTaskId=String(session.currentTaskId??"").replace(/[\r\n\t]/g,"_");session.lastScopeViolation=`Scope violation for task ${safeTaskId}: ${undeclaredFiles.length} undeclared files modified: `+undeclaredFiles.join(", "),session.scopeViolationDetected=!0,telemetry.scopeViolation(input.sessionID,session.agentName,session.currentTaskId??"unknown","undeclared files modified")}}session.modifiedFilesThisCoderTask=[]}}}await recordExecutionStallToolAfter({sessionID:input.sessionID,tool:input.tool,callID:input.callID,args:input.args??getStoredInputArgs(input.callID),output:safeOutput,directory:effectiveDirectory,options:executionStallOptions});let sessionId=input.sessionID,normalizedToolName=normalizeToolName(input.tool),isSubagentDispatch=new Set(["dispatch_lanes","dispatch_lanes_async"]).has(normalizedToolName)||isAgentDelegation(input.tool,input.args??getStoredInputArgs(input.callID)).isDelegation;if(isWriteTool2(normalizedToolName)||isSubagentDispatch)touchNoOpSession(sessionId,0),noOpWarningIssued.delete(sessionId),noOpStrongWarningIssued.delete(sessionId);else{let count=(toolCallsSinceLastWrite.get(sessionId)??0)+1;touchNoOpSession(sessionId,count);let threshold=cfg.no_op_warning_threshold??15,strongThreshold=threshold*2;if(count>=threshold&&!noOpWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`WARNING: Agent has made ${count} tool calls with no file modifications and no subagent dispatches. If you are stuck, state what is blocking you and report BLOCKED rather than continuing to probe.`);if(count>=strongThreshold&&!noOpStrongWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpStrongWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`CRITICAL: Agent has made ${count} tool calls with no file modifications and no subagent dispatches — twice the point at which you were first warned. STOP investigating; report BLOCKED to the user now with what you tried.`),telemetry.noOpStrongWarning(sessionId,session.agentName,count,strongThreshold)}let outcome=malformedOutput?{kind:"unknown",signal:""}:classifyToolOutcome(input,safeOutput,correlatedExecution),circuitArgs=correlatedExecution&&typeof input.args==="object"&&input.args!==null&&!Array.isArray(input.args)?{...input.args,command:correlatedExecution.originalCommand}:input.args;if(pendingReviewerScopeWrite&&classifyTaskResult(safeOutput)==="success"){let sessionCaptureRoot=resolveSessionWorkspaceDirectory(input.sessionID,effectiveDirectory),sessionRootIdentity=canonicalWorkspaceIdentity(sessionCaptureRoot),batchDeadline=Date.now()+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let pendingWrite of pendingReviewerScopeWrite){let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID});if(generation&&sessionRootIdentity&&generation.workspaceIdentity!==sessionRootIdentity){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:"workspace_mismatch",retryable:!1});let mismatchSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(mismatchSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} was written from workspace ${sessionRootIdentity} but the coder generation is bound to ${generation.workspaceIdentity} (code workspace_mismatch, retryable=false, responsible: architect). ACTION[architect]: verify the coder dispatch lane/scope binding, then redispatch`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`});continue}let captureRoot=generation?.captureDirectory?.trim()||sessionCaptureRoot,lastFailure=null,attempts=0;while(attempts<REVIEWER_SCOPE_CAPTURE_ATTEMPTS){attempts+=1;let captured=captureReviewerScopeFileFingerprint(captureRoot,pendingWrite.file,{deadlineAt:batchDeadline});if(captured.kind!=="capture_failed"){let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,fingerprint:fingerprint2});lastFailure=null;break}if(lastFailure={code:captured.code,retryable:captured.retryable},!captured.retryable)break}if(lastFailure){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:lastFailure.code,retryable:lastFailure.retryable});let captureSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(captureSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} could not be fingerprinted exactly (code ${lastFailure.code}, retryable=${lastFailure.retryable}, attempts=${attempts}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${lastFailure.retryable?"retry the coder write or re-dispatch the coder so capture re-runs":`resolve the ${lastFailure.code} condition for the file, then retry or route explicit manual review`}`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`})}}}if(outcome.kind==="fatal")recordNonTransientFailure(input.sessionID,outcome.category,outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});else if(outcome.kind==="success"||outcome.kind==="neutral")clearNonTransientCircuit(input.sessionID,{tool:input.tool,args:circuitArgs});else if(outcome.kind==="failure")recordNonTransientFailure(input.sessionID,"general_permanent",outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});let window2=getActiveWindow(input.sessionID);if(!window2)return;if(outcome.kind==="fatal"){window2.consecutiveErrors++;return}if(outcome.kind==="failure")window2.consecutiveErrors++;else if(window2.consecutiveErrors=0,window2.transientRetryCount=0,window2.lastSuccessTimeMs=Date.now(),session){if(session.model_fallback_index>0)session.model_fallback_index=0,session.modelFallbackExhausted=!1}},messagesTransform}}var MAX_PENDING_GATE_RECEIPTS_PER_SESSION=256,MAX_PENDING_GATE_RECEIPT_SESSIONS=500,_internals75,DURABLE_ATTRIBUTION_ADVISORY_COOLDOWN_MS=60000,MAX_DURABLE_ATTRIBUTION_ADVISORY_SESSIONS=500,durableAttributionAdvisoryBySession,STAGE_A_ATTRIBUTION_MISS_CODES,SPEC_DRIFT_BLOCKED_TOOLS,MAX_TRACKED_NO_OP_SESSIONS=200,toolCallsSinceLastWrite,noOpWarningIssued,noOpStrongWarningIssued;var init_guardrails=__esm(()=>{init_agents2();init_constants();init_schema();init_gate_evidence();init_manager();init_executor();init_path_identity();init_scope_binding();init_scope_lease_renewal();init_state2();init_telemetry();init_utils();init_logger();init_spec_hash();init_task_id();init_coder_settlement();init_conflict_resolution();init_extractors();init_normalize_tool_name();init_reviewer_scope_file_fingerprint();init_task_result_classifier();init_destructive_command();init_execution_stall();init_file_authority();init_helpers();init_messages_transform();init_nontransient_circuit();init_pre_check_result();init_stored_input_args();init_tool_before();init_helpers();_internals75={extractSwarmIdFromAgentName,getSwarmAgents,getMostRecentAssistantText,getProviderFailureFingerprint,isTransientProviderFailureText,resolveFallbackModel,dcCheckJunctionCreation,extractErrorSignal,getSandboxExecutor:getExecutor,assessSandboxEnforcement,allowUncorrelatedGateReceipts:!1,MAX_PENDING_GATE_RECEIPTS_PER_SESSION,MAX_PENDING_GATE_RECEIPT_SESSIONS,noOpStateSize:()=>toolCallsSinceLastWrite.size,hasNoOpState:(sessionID)=>toolCallsSinceLastWrite.has(sessionID),resolveDurableGateTaskId:(directory,callerFiles)=>resolveDurableGateTaskId(directory,callerFiles)},durableAttributionAdvisoryBySession=new Map;STAGE_A_ATTRIBUTION_MISS_CODES=new Set(["TASK_WORKFLOW_CODER_MUTATION_REQUIRED","TASK_WORKFLOW_STAGE_A_REQUIRED"]);SPEC_DRIFT_BLOCKED_TOOLS=new Set(["save_plan","update_task_status","phase_complete","lean_turbo_run_phase","lean_turbo_acquire_locks"]);toolCallsSinceLastWrite=new Map,noOpWarningIssued=new Set,noOpStrongWarningIssued=new Set});var init_guardrails2=__esm(()=>{init_file_authority();init_guardrails();init_stored_input_args()});var exports_model_preflight={};__export(exports_model_preflight,{splitModelId:()=>splitModelId,runModelPreflight:()=>runModelPreflight,resolveAgainstCatalog:()=>resolveAgainstCatalog,invalidateProviderCatalogCache:()=>invalidateProviderCatalogCache,fetchProviderCatalog:()=>fetchProviderCatalog,collectConfiguredAgentModels:()=>collectConfiguredAgentModels,checkSingleModelResolution:()=>checkSingleModelResolution,_internals:()=>_internals76,PROVIDER_LIST_TIMEOUT_MS:()=>PROVIDER_LIST_TIMEOUT_MS});function splitModelId(model){let separator=model.indexOf("/");if(separator<=0||separator===model.length-1)return null;return{provider:model.slice(0,separator),model:model.slice(separator+1)}}function collectConfiguredAgentModels(config2){let collected=[],overriddenAgents=new Set,overrides2=config2?.agents??{};for(let[agent,override]of Object.entries(overrides2)){if(typeof override?.model==="string"&&override.model.trim())collected.push({agent,model:override.model.trim(),source:"override"}),overriddenAgents.add(agent);for(let fallback of override?.fallback_models??[])if(typeof fallback==="string"&&fallback.trim())collected.push({agent,model:fallback.trim(),source:"fallback"})}for(let[agent,model]of Object.entries(DEFAULT_MODELS)){if(overriddenAgents.has(agent))continue;collected.push({agent,model,source:"default"})}return collected}function invalidateProviderCatalogCache(){catalogCacheByClient=new WeakMap}async function fetchProviderCatalog(client){if(!client)return null;let cached2=catalogCacheByClient.get(client);if(cached2&&Date.now()-cached2.fetchedAt<CATALOG_CACHE_TTL_MS)return cached2.catalog;let response;try{response=await _internals76.providerList(client)}catch{return null}let all=response?.data?.all;if(!Array.isArray(all))return null;let catalog2=new Map;for(let provider of all){if(typeof provider?.id!=="string")continue;let models=new Set;if(provider.models&&typeof provider.models==="object")for(let modelKey of Object.keys(provider.models))models.add(modelKey);catalog2.set(provider.id,models)}return catalogCacheByClient.set(client,{fetchedAt:Date.now(),catalog:catalog2}),catalog2}function resolveAgainstCatalog(models,catalog2){if(catalog2===null)return{catalogAvailable:!1,resolutions:models.map((entry)=>({...entry,status:"unknown",detail:"provider catalog unavailable; model resolution not checked"}))};return{catalogAvailable:!0,resolutions:models.map((entry)=>{let split=splitModelId(entry.model);if(!split)return{...entry,status:"unknown",detail:"model id has no provider prefix; resolution not checked against the catalog"};let providerModels=catalog2.get(split.provider);if(providerModels===void 0)return{...entry,status:"unresolved",detail:`provider "${split.provider}" is not present in the provider catalog`};if(!providerModels.has(split.model))return{...entry,status:"unresolved",detail:`provider "${split.provider}" does not list model "${split.model}"`};return{...entry,status:"ok"}})}}async function runModelPreflight(config2,client){let models=collectConfiguredAgentModels(config2),catalog2=await fetchProviderCatalog(client);return resolveAgainstCatalog(models,catalog2)}async function checkSingleModelResolution(model,client){let catalog2=await fetchProviderCatalog(client);if(catalog2===null)return"unknown";let split=splitModelId(model);if(!split)return"unknown";let providerModels=catalog2.get(split.provider);if(providerModels===void 0||!providerModels.has(split.model))return"unresolved";return"ok"}var PROVIDER_LIST_TIMEOUT_MS=2000,CATALOG_CACHE_TTL_MS=30000,catalogCacheByClient,_internals76;var init_model_preflight=__esm(()=>{init_constants();catalogCacheByClient=new WeakMap;_internals76={providerList:async(client)=>{let timer;try{return await Promise.race([client.provider.list(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("provider list timed out")),PROVIDER_LIST_TIMEOUT_MS)})])}finally{if(timer)clearTimeout(timer)}}}});var exports_task_envelope={};__export(exports_task_envelope,{parseTaskEnvelope:()=>parseTaskEnvelope,extractDispatchIds:()=>extractDispatchIds});function parseTaskEnvelope(text){if(typeof text!=="string"||text.length===0)return null;let match=text.match(TASK_ENVELOPE_RE);if(!match)return null;let sessionId=match[1],rawState=match[2],state=rawState==="canceled"?"cancelled":rawState;if(!sessionId)return null;let summary=extractTagText(text,"summary"),resultRaw=state==="error"||state==="cancelled"?extractTagText(text,"task_error")??extractTagText(text,"task_result"):extractTagText(text,"task_result"),bounded=boundEnvelopeText(resultRaw);return{sessionId,state,...summary!==void 0?{summary}:{},...state==="error"||state==="cancelled"?{...bounded?{errorText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}:{},...state!=="error"&&state!=="cancelled"&&bounded?{resultText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}}function extractTagText(text,tag){let re=new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),match=text.match(re);if(!match)return;return match[1]}function boundEnvelopeText(text){if(text===void 0)return;if(text.length<=20000)return{text,chars:text.length,truncated:!1};let suffix=`
|
|
1183
|
+
(no recorded snapshot to diff against)`;throw Error(message)}}function isPlainObject3(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function readSignalField(source,key2){try{return source[key2]}catch{return}}function pushSignalValue(parts,value){if(typeof value==="string"){parts.push(value);return}if(typeof value==="number"||typeof value==="boolean")parts.push(String(value))}function appendSelectedFields(parts,source,keys){for(let key2 of keys)pushSignalValue(parts,readSignalField(source,key2))}function appendNestedErrorSignal(parts,value){if(typeof value==="string"){parts.push(value);return}if(value instanceof Error){parts.push(value.name,value.message),appendSelectedFields(parts,value,["code","status","statusCode"]);return}if(!isPlainObject3(value))return;appendSelectedFields(parts,value,["code","status","statusCode","message","error_type"])}function extractErrorSignal(errorContent){if(typeof errorContent==="string")return errorContent;if(errorContent==null)return"";let parts=[];try{if(errorContent instanceof Error)return parts.push(errorContent.name,errorContent.message),appendSelectedFields(parts,errorContent,["code","status","statusCode"]),parts.join(" ");if(!isPlainObject3(errorContent))return"";appendSelectedFields(parts,errorContent,["code","status","statusCode","message","error_type"]),appendNestedErrorSignal(parts,readSignalField(errorContent,"error"));let metadata=readSignalField(errorContent,"metadata");if(isPlainObject3(metadata))appendSelectedFields(parts,metadata,["code","status","statusCode","error_type"]);appendNestedErrorSignal(parts,readSignalField(errorContent,"cause"))}catch{return parts.join(" ")}return parts.join(" ")}function touchNoOpSession(sessionID,count){toolCallsSinceLastWrite.delete(sessionID),toolCallsSinceLastWrite.set(sessionID,count),evictNoOpStateIfOverBound()}function evictNoOpStateIfOverBound(){while(toolCallsSinceLastWrite.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=toolCallsSinceLastWrite.keys().next().value;if(stalestKey===void 0)break;toolCallsSinceLastWrite.delete(stalestKey),noOpWarningIssued.delete(stalestKey),noOpStrongWarningIssued.delete(stalestKey)}while(noOpWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpWarningIssued.delete(stalestKey)}while(noOpStrongWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpStrongWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpStrongWarningIssued.delete(stalestKey)}}function extractPhaseNumber2(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function isWriteTool2(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isGateTool(toolName){let normalized=normalizeToolName(toolName);return["diff","syntax_check","placeholder_scan","imports","lint","build_check","pre_check_batch","secretscan","sast_scan","quality_budget"].includes(normalized)}function isAgentDelegation(toolName,args2){if(!isTaskToolId(toolName))return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function createGuardrailsHooks(directory,directoryOrConfig,config2,authorityConfig,worktreeBaseDirOverrides,resolveAgentModel){let guardrailsConfig;if(directory&&typeof directory==="object"&&"enabled"in directory)warn("[guardrails] Legacy call without directory, falling back to process.cwd()"),guardrailsConfig=directory;else if(directoryOrConfig&&typeof directoryOrConfig==="object"&&"enabled"in directoryOrConfig)guardrailsConfig=directoryOrConfig;else guardrailsConfig=config2;let effectiveDirectory=(()=>{if(typeof directory==="string")return directory;let cwd=process.cwd();return warn(`[guardrails] effectiveDirectory resolved to process.cwd() "${cwd}" — `+"pass an explicit directory string to createGuardrailsHooks to avoid .swarm artifacts in wrong locations"),cwd})();if(guardrailsConfig?.enabled===!1)return{toolBefore:async()=>{},toolAfter:async()=>{},messagesTransform:async()=>{}};let precomputedAuthorityRules=buildEffectiveRules(authorityConfig),verifierPaths=authorityConfig?.verifier_config_paths;if(verifierPaths&&verifierPaths.length>0){let existingArchitect=precomputedAuthorityRules.architect??{};precomputedAuthorityRules.architect={...existingArchitect,blockedGlobs:[...existingArchitect.blockedGlobs??[],...verifierPaths]}}let universalDenyPrefixes=authorityConfig?.universal_deny_prefixes??[],cfg=guardrailsConfig,requiredQaGates=cfg.qa_gates?.required_tools??["diff","syntax_check","placeholder_scan","lint","pre_check_batch"],requireReviewerAndTestEngineer=cfg.qa_gates?.require_reviewer_test_engineer??!0,interpreterAllowedAgents=cfg.interpreter_allowed_agents,shellAuditEnabled=cfg.shell_audit_log??!0,consecutiveNoToolTurns=new Map,lastCountedAssistantMsgId=new Map,pendingReviewerScopeWrites=new Map,pendingGateTasksBySession=new Map,takePendingGateTask=(sessionID,callID)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID),pending=sessionTasks?.get(callID);if(sessionTasks){if(sessionTasks.delete(callID),sessionTasks.size===0)pendingGateTasksBySession.delete(sessionID)}return pending},rememberPendingGateTask=(sessionID,callID,taskId,generation)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID);if(!sessionTasks){if(pendingGateTasksBySession.size>=MAX_PENDING_GATE_RECEIPT_SESSIONS)throw Error("GATE_RECEIPT_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionTasks=new Map,pendingGateTasksBySession.set(sessionID,sessionTasks)}if(!sessionTasks.has(callID)&&sessionTasks.size>=MAX_PENDING_GATE_RECEIPTS_PER_SESSION)throw Error("GATE_RECEIPT_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionTasks.set(callID,{sessionID,taskId,generation})},scopeLeaseRenewal=createScopeLeaseRenewalTracker(),rememberReviewerScopeWrite=(input)=>{if(!pendingReviewerScopeWrites.has(input.callID)&&pendingReviewerScopeWrites.size>=256){let oldest=pendingReviewerScopeWrites.keys().next().value;if(oldest!==void 0)pendingReviewerScopeWrites.delete(oldest)}let pending=pendingReviewerScopeWrites.get(input.callID)??[],candidate={parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,file:input.file};if(!pending.some((entry)=>entry.parentSessionID===candidate.parentSessionID&&entry.taskId===candidate.taskId&&entry.coderCallID===candidate.coderCallID&&entry.file===candidate.file)&&pending.length<256)pending.push(candidate);pendingReviewerScopeWrites.set(input.callID,pending)},executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},baseToolBefore=createToolBeforeHandler({effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,rememberReviewerScopeWrite,rememberScopeLeaseCandidate:scopeLeaseRenewal.remember,getSandboxExecutor:_internals75.getSandboxExecutor,assessSandboxEnforcement:_internals75.assessSandboxEnforcement}),toolBefore=async(input,output)=>{if(isGateTool(input.tool)){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId;if(!taskId){let callerFiles=extractGateCallFiles(output.args),fallback=await _internals75.resolveDurableGateTaskId(effectiveDirectory,callerFiles);if(fallback){if("taskId"in fallback)taskId=fallback.taskId;else if("ambiguous"in fallback&&fallback.ambiguous.length>0){let shown=fallback.ambiguous.slice(0,10),more=fallback.ambiguous.length-shown.length;emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00${fallback.ambiguous.join(",")}`,`STAGE A ATTRIBUTION AMBIGUOUS: ${fallback.ambiguous.length} tasks are settled at coder_delegated (${shown.join(", ")}${more>0?`, +${more} more`:""}) but this session has no task correlation after reset-session. Stage A evidence cannot be attributed safely. Run /swarm recover to repair Stage A attribution, then re-run the gate.`)}else if("unbound"in fallback)emitDurableAttributionAdvisory(input.sessionID,`${effectiveDirectory}\x00unbound\x00${fallback.unbound}`,fallback.reason==="truncated"?`STAGE A ATTRIBUTION UNVERIFIABLE: task ${fallback.unbound} looks like the sole durable candidate at coder_delegated, but the settlement scan is truncated (more than 200 historical settlements) so a second candidate cannot be ruled out. Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`:`STAGE A ATTRIBUTION UNBOUND: task ${fallback.unbound} is the sole durable candidate at coder_delegated, but this gate call's scanned files do not match its declared changes (or no file scope was provided). Stage A evidence cannot be safely attributed. Run /swarm recover ${fallback.unbound} if this task is genuinely wedged.`)}}if(taskId){let workflow=isStrictTaskId(taskId)?getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId)):null;rememberPendingGateTask(input.sessionID,input.callID,taskId,workflow?.generation??0)}}try{await baseToolBefore(input,output)}catch(error49){throw takePendingGateTask(input.sessionID,input.callID),error49}},messagesTransform=createMessagesTransformHandler({effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId,resolveAgentModel});return{toolBefore,toolAfter:async(input,output)=>{let pendingGateTask=takePendingGateTask(input.sessionID,input.callID)??(_internals75.allowUncorrelatedGateReceipts?(()=>{let testSession=swarmState.agentSessions.get(input.sessionID);return testSession?{sessionID:input.sessionID,taskId:testSession.currentTaskId??`${input.sessionID}:unknown`,generation:testSession.currentTaskId&&isStrictTaskId(testSession.currentTaskId)?testSession.taskWorkflowCache?.get(testSession.currentTaskId)?.generation??0:0}:void 0})():void 0),pendingReviewerScopeWrite=pendingReviewerScopeWrites.get(input.callID);pendingReviewerScopeWrites.delete(input.callID);let correlatedExecution=takeToolExecution(input.sessionID,input.callID);if(correlatedExecution&&!isToolExecutionCurrent(input.sessionID,correlatedExecution)){await scopeLeaseRenewal.consume({...input,output:null});return}let malformedOutput=!output||typeof output!=="object",safeOutput=malformedOutput?{title:"",output:"",metadata:null}:output;await scopeLeaseRenewal.consume({...input,output:malformedOutput?null:safeOutput});let session=swarmState.agentSessions.get(input.sessionID);if(session){if(isGateTool(input.tool)&&pendingGateTask?.sessionID===input.sessionID){let taskId=pendingGateTask.taskId;if(!session.gateLog.has(taskId))session.gateLog.set(taskId,new Set);session.gateLog.get(taskId)?.add(input.tool);let outputStr=typeof safeOutput.output==="string"?safeOutput.output:"";if(normalizeToolName(input.tool)==="pre_check_batch"){let verdict=decodePreCheckResult(safeOutput.output);if(verdict.kind==="fail"||verdict.kind==="invalid"){if(session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now(),code:verdict.code},verdict.kind==="fail"&&isStrictTaskId(taskId))try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_failed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next)}catch(err){let code=stageAWriteErrorCode(err);if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A failure write failed for task ${taskId}: ${code}. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch failed but the rework transition was rejected. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to persist Stage A failure",{taskId,error:String(err)})}}else if(verdict.kind==="pass"){if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)==="pre_check_batch")session.lastGateFailure=null;if(!isStrictTaskId(taskId))advanceTaskState(session,taskId,"pre_check_passed");try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_passed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next)}catch(err){let code=stageAWriteErrorCode(err);if(code&&STAGE_A_ATTRIBUTION_MISS_CODES.has(code))criticalWarn(`[guardrails] Stage A write failed for task ${taskId}: ${code} — pre_check_batch result was NOT attributed. Run /swarm recover ${taskId}.`),pushAdvisory(session,`STAGE A WRITE FAILED (${code}) for task ${taskId}: pre_check_batch passed but the workflow transition was rejected, so Stage B dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run /swarm recover ${taskId} to repair attribution.`);else warn("Failed to advance task state after pre_check_batch pass",{taskId,error:String(err)})}}}else if(safeOutput.output===null||safeOutput.output===void 0||outputStr.includes("FAIL")||outputStr.includes("error")||outputStr.toLowerCase().includes("gates_passed: false"))session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now()};else if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)===normalizeToolName(input.tool))session.lastGateFailure=null}let inputArgs=input.args??getStoredInputArgs(input.callID),delegation=isAgentDelegation(input.tool,inputArgs);if(delegation.isDelegation&&(delegation.targetAgent==="reviewer"||delegation.targetAgent==="test_engineer")){let currentPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan){let phaseString=extractCurrentPhaseFromPlan(plan);currentPhase=extractPhaseNumber2(phaseString)}}catch(error49){log("[Guardrails] loadPlan failed during reviewer tracking",{error:error49 instanceof Error?error49.message:String(error49)})}let count=session.reviewerCallCount.get(currentPhase)??0;session.reviewerCallCount.set(currentPhase,count+1)}if(delegation.isDelegation&&delegation.targetAgent==="coder"){let exactGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:input.sessionID,coderCallID:input.callID}),completedTaskId=exactGeneration?.taskId??session.lastCoderDelegationTaskId;if(completedTaskId){session.currentTaskId=completedTaskId;let exactGenerationFiles=exactGeneration?.modifiedFiles??session.modifiedFilesThisCoderTask;if(!session.revisionLimitHit){if(session.coderRevisions++,session.coderRevisions>1&&session.qaSkipCount===0){let conflictPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan)conflictPhase=extractPhaseNumber2(extractCurrentPhaseFromPlan(plan))}catch{}resolveAgentConflict({sessionID:input.sessionID,phase:conflictPhase,taskId:session.currentTaskId??void 0,sourceAgent:"reviewer",targetAgent:"coder",conflictType:"feedback_rejection",rejectionCount:session.coderRevisions-1,summary:`Coder revision ${session.coderRevisions} for task ${session.currentTaskId??"unknown"}`}),session.lastDelegationReason="review_rejected"}let maxRevisions=cfg.max_coder_revisions??5;if(session.coderRevisions>=maxRevisions)session.revisionLimitHit=!0,telemetry.revisionLimitHit(input.sessionID,session.agentName),pushAdvisory(session,`CODER REVISION LIMIT: Agent has been revised ${session.coderRevisions} times (max: ${maxRevisions}) for task ${session.currentTaskId??"unknown"}. Escalate to user or consider a fundamentally different approach.`),swarmState.pendingEvents++}if(session.partialGateWarningsIssuedForTask?.delete(session.currentTaskId),session.declaredCoderScope!==null){let undeclaredFiles=exactGenerationFiles.map((f)=>f.replace(/[\r\n\t]/g,"_")).filter((f)=>!isInDeclaredScope(f,session.declaredCoderScope,directory));if(undeclaredFiles.length>=1){let safeTaskId=String(session.currentTaskId??"").replace(/[\r\n\t]/g,"_");session.lastScopeViolation=`Scope violation for task ${safeTaskId}: ${undeclaredFiles.length} undeclared files modified: `+undeclaredFiles.join(", "),session.scopeViolationDetected=!0,telemetry.scopeViolation(input.sessionID,session.agentName,session.currentTaskId??"unknown","undeclared files modified")}}session.modifiedFilesThisCoderTask=[]}}}await recordExecutionStallToolAfter({sessionID:input.sessionID,tool:input.tool,callID:input.callID,args:input.args??getStoredInputArgs(input.callID),output:safeOutput,directory:effectiveDirectory,options:executionStallOptions});let sessionId=input.sessionID,normalizedToolName=normalizeToolName(input.tool),isSubagentDispatch=new Set(["dispatch_lanes","dispatch_lanes_async"]).has(normalizedToolName)||isAgentDelegation(input.tool,input.args??getStoredInputArgs(input.callID)).isDelegation;if(isWriteTool2(normalizedToolName)||isSubagentDispatch)touchNoOpSession(sessionId,0),noOpWarningIssued.delete(sessionId),noOpStrongWarningIssued.delete(sessionId);else{let count=(toolCallsSinceLastWrite.get(sessionId)??0)+1;touchNoOpSession(sessionId,count);let threshold=cfg.no_op_warning_threshold??15,strongThreshold=threshold*2;if(count>=threshold&&!noOpWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`WARNING: Agent has made ${count} tool calls with no file modifications and no subagent dispatches. If you are stuck, state what is blocking you and report BLOCKED rather than continuing to probe.`);if(count>=strongThreshold&&!noOpStrongWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpStrongWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`CRITICAL: Agent has made ${count} tool calls with no file modifications and no subagent dispatches — twice the point at which you were first warned. STOP investigating; report BLOCKED to the user now with what you tried.`),telemetry.noOpStrongWarning(sessionId,session.agentName,count,strongThreshold)}let outcome=malformedOutput?{kind:"unknown",signal:""}:classifyToolOutcome(input,safeOutput,correlatedExecution),circuitArgs=correlatedExecution&&typeof input.args==="object"&&input.args!==null&&!Array.isArray(input.args)?{...input.args,command:correlatedExecution.originalCommand}:input.args;if(pendingReviewerScopeWrite&&classifyTaskResult(safeOutput)==="success"){let sessionCaptureRoot=resolveSessionWorkspaceDirectory(input.sessionID,effectiveDirectory),sessionRootIdentity=canonicalWorkspaceIdentity(sessionCaptureRoot),batchDeadline=Date.now()+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let pendingWrite of pendingReviewerScopeWrite){let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID});if(generation&&sessionRootIdentity&&generation.workspaceIdentity!==sessionRootIdentity){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:"workspace_mismatch",retryable:!1});let mismatchSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(mismatchSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} was written from workspace ${sessionRootIdentity} but the coder generation is bound to ${generation.workspaceIdentity} (code workspace_mismatch, retryable=false, responsible: architect). ACTION[architect]: verify the coder dispatch lane/scope binding, then redispatch`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`});continue}let captureRoot=generation?.captureDirectory?.trim()||sessionCaptureRoot,lastFailure=null,attempts=0;while(attempts<REVIEWER_SCOPE_CAPTURE_ATTEMPTS){attempts+=1;let captured=captureReviewerScopeFileFingerprint(captureRoot,pendingWrite.file,{deadlineAt:batchDeadline});if(captured.kind!=="capture_failed"){let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,fingerprint:fingerprint2});lastFailure=null;break}if(lastFailure={code:captured.code,retryable:captured.retryable},!captured.retryable)break}if(lastFailure){recordReviewerScopeGenerationCaptureFailure({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,file:pendingWrite.file,code:lastFailure.code,retryable:lastFailure.retryable});let captureSession=ensureAgentSession(pendingWrite.parentSessionID);pushAdvisory(captureSession,`REVIEWER_CAPTURE_FAILED: task ${pendingWrite.taskId}: file ${sanitizeDiagnosticText(pendingWrite.file,160)} could not be fingerprinted exactly (code ${lastFailure.code}, retryable=${lastFailure.retryable}, attempts=${attempts}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${lastFailure.retryable?"retry the coder write or re-dispatch the coder so capture re-runs":`resolve the ${lastFailure.code} condition for the file, then retry or route explicit manual review`}`,{dedupeKey:`reviewer-capture-failed:${pendingWrite.taskId}`})}}}if(outcome.kind==="fatal")recordNonTransientFailure(input.sessionID,outcome.category,outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});else if(outcome.kind==="success"||outcome.kind==="neutral")clearNonTransientCircuit(input.sessionID,{tool:input.tool,args:circuitArgs});else if(outcome.kind==="failure")recordNonTransientFailure(input.sessionID,"general_permanent",outcome.signal,{tool:input.tool,args:circuitArgs,armAttempt:correlatedExecution!==void 0});let window2=getActiveWindow(input.sessionID);if(!window2)return;if(outcome.kind==="fatal"){window2.consecutiveErrors++;return}if(outcome.kind==="failure")window2.consecutiveErrors++;else if(window2.consecutiveErrors=0,window2.transientRetryCount=0,window2.lastSuccessTimeMs=Date.now(),session){if(session.model_fallback_index>0)session.model_fallback_index=0,session.modelFallbackExhausted=!1}},messagesTransform}}var MAX_PENDING_GATE_RECEIPTS_PER_SESSION=256,MAX_PENDING_GATE_RECEIPT_SESSIONS=500,_internals75,DURABLE_ATTRIBUTION_ADVISORY_COOLDOWN_MS=60000,MAX_DURABLE_ATTRIBUTION_ADVISORY_SESSIONS=500,durableAttributionAdvisoryBySession,STAGE_A_ATTRIBUTION_MISS_CODES,SPEC_DRIFT_BLOCKED_TOOLS,MAX_TRACKED_NO_OP_SESSIONS=200,toolCallsSinceLastWrite,noOpWarningIssued,noOpStrongWarningIssued;var init_guardrails=__esm(()=>{init_agents2();init_constants();init_schema();init_gate_evidence();init_manager();init_executor();init_path_identity();init_scope_binding();init_scope_lease_renewal();init_state2();init_telemetry();init_utils();init_logger();init_spec_hash();init_task_id();init_coder_settlement();init_conflict_resolution();init_extractors();init_normalize_tool_name();init_reviewer_scope_file_fingerprint();init_task_result_classifier();init_destructive_command();init_execution_stall();init_file_authority();init_helpers();init_messages_transform();init_nontransient_circuit();init_pre_check_result();init_stored_input_args();init_tool_before();init_helpers();_internals75={extractSwarmIdFromAgentName,getSwarmAgents,getMostRecentAssistantText,getProviderFailureFingerprint,isTransientProviderFailureText,resolveFallbackModel,dcCheckJunctionCreation,extractErrorSignal,getSandboxExecutor:getExecutor,assessSandboxEnforcement,allowUncorrelatedGateReceipts:!1,MAX_PENDING_GATE_RECEIPTS_PER_SESSION,MAX_PENDING_GATE_RECEIPT_SESSIONS,noOpStateSize:()=>toolCallsSinceLastWrite.size,hasNoOpState:(sessionID)=>toolCallsSinceLastWrite.has(sessionID),resolveDurableGateTaskId:(directory,callerFiles)=>resolveDurableGateTaskId(directory,callerFiles)},durableAttributionAdvisoryBySession=new Map;STAGE_A_ATTRIBUTION_MISS_CODES=new Set(["TASK_WORKFLOW_CODER_MUTATION_REQUIRED","TASK_WORKFLOW_STAGE_A_REQUIRED"]);SPEC_DRIFT_BLOCKED_TOOLS=new Set(["save_plan","update_task_status","phase_complete","lean_turbo_run_phase","lean_turbo_acquire_locks"]);toolCallsSinceLastWrite=new Map,noOpWarningIssued=new Set,noOpStrongWarningIssued=new Set});var init_guardrails2=__esm(()=>{init_file_authority();init_guardrails();init_stored_input_args()});var exports_model_preflight={};__export(exports_model_preflight,{splitModelId:()=>splitModelId,runModelPreflight:()=>runModelPreflight,resolveAgainstCatalog:()=>resolveAgainstCatalog,invalidateProviderCatalogCache:()=>invalidateProviderCatalogCache,fetchProviderCatalog:()=>fetchProviderCatalog,collectConfiguredAgentModels:()=>collectConfiguredAgentModels,checkSingleModelResolution:()=>checkSingleModelResolution,_internals:()=>_internals76,PROVIDER_LIST_TIMEOUT_MS:()=>PROVIDER_LIST_TIMEOUT_MS});function splitModelId(model){let separator=model.indexOf("/");if(separator<=0||separator===model.length-1)return null;return{provider:model.slice(0,separator),model:model.slice(separator+1)}}function collectConfiguredAgentModels(config2){let collected=[],overriddenAgents=new Set,overrides2=config2?.agents??{};for(let[agent,override]of Object.entries(overrides2)){if(typeof override?.model==="string"&&override.model.trim())collected.push({agent,model:override.model.trim(),source:"override"}),overriddenAgents.add(agent);for(let fallback of override?.fallback_models??[])if(typeof fallback==="string"&&fallback.trim())collected.push({agent,model:fallback.trim(),source:"fallback"})}for(let[agent,model]of Object.entries(DEFAULT_MODELS)){if(overriddenAgents.has(agent))continue;collected.push({agent,model,source:"default"})}return collected}function invalidateProviderCatalogCache(){catalogCacheByClient=new WeakMap}async function fetchProviderCatalog(client){if(!client)return null;let cached2=catalogCacheByClient.get(client);if(cached2&&Date.now()-cached2.fetchedAt<CATALOG_CACHE_TTL_MS)return cached2.catalog;let response;try{response=await _internals76.providerList(client)}catch{return null}let all=response?.data?.all;if(!Array.isArray(all))return null;let catalog2=new Map;for(let provider of all){if(typeof provider?.id!=="string")continue;let models=new Set;if(provider.models&&typeof provider.models==="object")for(let modelKey of Object.keys(provider.models))models.add(modelKey);catalog2.set(provider.id,models)}return catalogCacheByClient.set(client,{fetchedAt:Date.now(),catalog:catalog2}),catalog2}function resolveAgainstCatalog(models,catalog2){if(catalog2===null)return{catalogAvailable:!1,resolutions:models.map((entry)=>({...entry,status:"unknown",detail:"provider catalog unavailable; model resolution not checked"}))};return{catalogAvailable:!0,resolutions:models.map((entry)=>{let split=splitModelId(entry.model);if(!split)return{...entry,status:"unknown",detail:"model id has no provider prefix; resolution not checked against the catalog"};let providerModels=catalog2.get(split.provider);if(providerModels===void 0)return{...entry,status:"unresolved",detail:`provider "${split.provider}" is not present in the provider catalog`};if(!providerModels.has(split.model))return{...entry,status:"unresolved",detail:`provider "${split.provider}" does not list model "${split.model}"`};return{...entry,status:"ok"}})}}async function runModelPreflight(config2,client){let models=collectConfiguredAgentModels(config2),catalog2=await fetchProviderCatalog(client);return resolveAgainstCatalog(models,catalog2)}async function checkSingleModelResolution(model,client){let catalog2=await fetchProviderCatalog(client);if(catalog2===null)return"unknown";let split=splitModelId(model);if(!split)return"unknown";let providerModels=catalog2.get(split.provider);if(providerModels===void 0||!providerModels.has(split.model))return"unresolved";return"ok"}var PROVIDER_LIST_TIMEOUT_MS=2000,CATALOG_CACHE_TTL_MS=30000,catalogCacheByClient,_internals76;var init_model_preflight=__esm(()=>{init_constants();catalogCacheByClient=new WeakMap;_internals76={providerList:async(client)=>{let timer;try{return await Promise.race([client.provider.list(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("provider list timed out")),PROVIDER_LIST_TIMEOUT_MS)})])}finally{if(timer)clearTimeout(timer)}}}});var exports_task_envelope={};__export(exports_task_envelope,{parseTaskEnvelope:()=>parseTaskEnvelope,extractDispatchIds:()=>extractDispatchIds});function parseTaskEnvelope(text){if(typeof text!=="string"||text.length===0)return null;let match=text.match(TASK_ENVELOPE_RE);if(!match)return null;let sessionId=match[1],rawState=match[2],state=rawState==="canceled"?"cancelled":rawState;if(!sessionId)return null;let summary=extractTagText(text,"summary"),resultRaw=state==="error"||state==="cancelled"?extractTagText(text,"task_error")??extractTagText(text,"task_result"):extractTagText(text,"task_result"),bounded=boundEnvelopeText(resultRaw);return{sessionId,state,...summary!==void 0?{summary}:{},...state==="error"||state==="cancelled"?{...bounded?{errorText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}:{},...state!=="error"&&state!=="cancelled"&&bounded?{resultText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}}function extractTagText(text,tag){let re=new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),match=text.match(re);if(!match)return;return match[1]}function boundEnvelopeText(text){if(text===void 0)return;if(text.length<=20000)return{text,chars:text.length,truncated:!1};let suffix=`
|
|
1184
1184
|
[... ${text.length-20000} chars truncated by task-envelope ...]`,maxContent=Math.max(0,20000-suffix.length);return{text:`${text.slice(0,maxContent)}${suffix}`,chars:text.length,truncated:!0}}function extractDispatchIds(output){let subagentSessionId=null,jobId=null;if(typeof output==="object"&&output!==null){let o=output,metadata=o.metadata;if(typeof metadata==="object"&&metadata!==null){let rawJobId=metadata.jobId;if(typeof rawJobId==="string"&&rawJobId.length>0)jobId=rawJobId}let rendered=o.output,envelope=parseTaskEnvelope(typeof rendered==="string"?rendered:void 0);if(envelope&&envelope.state==="running")subagentSessionId=envelope.sessionId}else if(typeof output==="string"){let envelope=parseTaskEnvelope(output);if(envelope&&envelope.state==="running")subagentSessionId=envelope.sessionId}if(!subagentSessionId&&jobId)subagentSessionId=jobId;return{subagentSessionId,jobId}}var TASK_ENVELOPE_RE;var init_task_envelope=__esm(()=>{TASK_ENVELOPE_RE=/<task\s+id="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"\s*>/});import*as fs51 from"node:fs";import*as path85 from"node:path";function exactProvisioningOwnerForBackgroundDescriptor(owner){if(owner?.reservationId===void 0||owner.generation===void 0||owner.branchName===void 0)return;return{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}}function clearPendingCoderScope(){pendingCoderScopeByTaskId.clear()}async function prepareCoderScope(directory,input,args2){let rawTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"";if(isStrictTaskId(rawTaskId)){let resolvedFeedbackScope=await resolvePrFeedbackScopeDeclaration(directory,input.sessionID,rawTaskId);if(resolvedFeedbackScope){let directives2=extractTaskFileDirectives(args2);if(directives2.present&&!directives2.files)throw Error("SCOPE_NOT_DECLARED: FILE: directives are present but empty or ambiguous; provide one complete relative path per FILE: line.");let resolved2=resolveCoderScopeSources({explicitFiles:resolvedFeedbackScope.files,planFiles:null,fileDirectiveFiles:directives2.files});if(!resolved2.ok)throw Error(formatCoderScopeConflict(resolved2));await _internals78.beforePrFeedbackScopeConsume?.();let feedbackScope=await consumePrFeedbackScopeDeclaration(directory,input.sessionID,rawTaskId,input.callID,resolvedFeedbackScope);if(!feedbackScope)throw Error("SCOPE_NOT_DECLARED: PR-feedback scope could not be reserved by this Task invocation (the declaration was replaced, the workflow left PR_FEEDBACK, or its revision changed).");let binding2=createPrFeedbackScopeBinding({directory,taskId:rawTaskId,files:resolved2.files,ownerSessionId:input.sessionID,ownerMessageId:input.callID,dispatchCallId:input.callID,activation:"pending_child",workflowSessionId:input.sessionID,workflowRevisionDigest:feedbackScope.revisionDigest});if(!binding2)throw Error("SCOPE_NOT_DECLARED: PR-feedback scope could not be bound to this Task invocation.");return{kind:"pr_feedback",plan:null,taskId:rawTaskId,declaredFiles:resolved2.files,binding:binding2}}}let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path85.join(directory,".swarm","plan.json");throw Error(`SCOPE_NOT_DECLARED: no valid plan found at ${planPath} (file missing or invalid). Declare a plan via save_plan or run /swarm plan first.`)}let planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases),taskId=resolveDelegatedPlanTaskId(args2,toTaskIdPlanContextOptions(planTaskIdContext));if(!taskId)throw Error(`SCOPE_NOT_DECLARED: ${describeCoderScopeFailure(args2,planTaskIdContext)}`);let declaredFilesForTask=getPlanTaskDeclaredFiles(plan,taskId);if(!declaredFilesForTask){let known=planTaskIdContext.status==="available"?[...planTaskIdContext.taskIds].sort().join(", ")||"(none)":"(omitted: plan task context over limit)";throw Error(`SCOPE_NOT_DECLARED: task_id "${taskId}" does not match any known plan task id. Known: ${known}. Update the dispatch or revise the plan.`)}let directives=extractTaskFileDirectives(args2);if(directives.present&&!directives.files)throw Error("SCOPE_NOT_DECLARED: FILE: directives are present but empty or ambiguous; provide one complete relative path per FILE: line.");let explicitResolution=resolveScopeBindingFromDisk({directory,plan,taskId,ownerSessionId:input.sessionID,requireDeclaration:!0,includeExpired:!0});if(explicitResolution.status==="ambiguous"||explicitResolution.status==="expired"||explicitResolution.status==="overloaded")throw Error(formatScopeResolutionDiagnostic({resolution:explicitResolution,taskId,sessionId:input.sessionID})??"SCOPE_NOT_DECLARED: durable declaration resolution failed.");let explicitBinding=explicitResolution.status==="found"?explicitResolution.binding:null,declaredFiles=declaredFilesForTask,resolved=resolveCoderScopeSources({explicitFiles:explicitBinding?.files,planFiles:declaredFiles,fileDirectiveFiles:directives.files});if(!resolved.ok)throw Error(formatCoderScopeConflict(resolved));let binding=createScopeBinding({directory,plan,taskId,files:resolved.files,ownerSessionId:input.sessionID,ownerMessageId:input.callID,dispatchCallId:input.callID,activation:"pending_child",source:resolved.source});if(!binding)throw Error("SCOPE_NOT_DECLARED: coder scope could not be bound to this Task invocation.");return{kind:"plan",plan,taskId,declaredFiles,binding}}function isBackgroundTrue(value){return value===!0||value==="true"}function outputLooksLikeBackgroundRunning(output){if(typeof output!=="object"||output===null)return!1;let o=output;if(o.state==="running")return!0;let metadata=o.metadata;return typeof metadata==="object"&&metadata!==null&&metadata.background===!0}function isEnvelope(obj){if(typeof obj!=="object"||obj===null)return!1;let e=obj;return typeof e.taskId==="string"&&typeof e.targetAgent==="string"&&typeof e.action==="string"}function parseDelegationEnvelope(content,directory){let validateEnvelopePaths=(envelope2)=>{if(directory)for(let filePath of envelope2.files){try{validateSwarmPath(directory,filePath)}catch{return null}let resolvedPath=path85.resolve(directory,filePath);if(!fs51.existsSync(resolvedPath))return null}return envelope2};try{let parsed=JSON.parse(content);if(isEnvelope(parsed))return validateEnvelopePaths(parsed)}catch{let match=content.match(/\{[\s\S]*\}/);if(match)try{let parsed=JSON.parse(match[0]);if(isEnvelope(parsed))return validateEnvelopePaths(parsed)}catch{}}let lines=content.split(`
|
|
1185
1185
|
`),keyValueMap={};for(let line of lines){let match=line.match(/^([^:]+):\s*(.+)$/);if(match){let key2=match[1].trim().toLowerCase(),value=match[2].trim();keyValueMap[key2]=value}}let keyNormalization={taskid:"taskId",task_id:"taskId",targetagent:"targetAgent",target_agent:"targetAgent",commandtype:"commandType",command_type:"commandType",acceptancecriteria:"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",technicalcontext:"technicalContext",technical_context:"technicalContext",errorstrategy:"errorStrategy",error_strategy:"errorStrategy",platformnotes:"platformNotes",platform_notes:"platformNotes",action:"action",files:"files"},normalizedMap={};for(let[key2,value]of Object.entries(keyValueMap)){let normalized=keyNormalization[key2]||key2;normalizedMap[normalized]=value}if(Object.keys(normalizedMap).length<3)return null;let requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!normalizedMap[field])return null;let parseArrayField=(value)=>{let parts=value.split(",");if(parts.length===1)parts=value.split(";");return parts.map((s)=>s.trim()).filter((s)=>s.length>0)},envelope={taskId:normalizedMap.taskId,targetAgent:normalizedMap.targetAgent,action:normalizedMap.action,commandType:normalizedMap.commandType,files:parseArrayField(normalizedMap.files),acceptanceCriteria:parseArrayField(normalizedMap.acceptanceCriteria),technicalContext:normalizedMap.technicalContext||""};if(normalizedMap.technicalContext)envelope.technicalContext=normalizedMap.technicalContext;if(normalizedMap.errorStrategy)envelope.errorStrategy=normalizedMap.errorStrategy;if(normalizedMap.platformNotes)envelope.platformNotes=normalizedMap.platformNotes;return validateEnvelopePaths(envelope)}function validateDelegationEnvelope(envelope,context){if(typeof envelope!=="object"||envelope===null)return{valid:!1,reason:"envelope_not_object"};let e=envelope,requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!(field in e)||e[field]===void 0||e[field]===null)return{valid:!1,reason:`missing_field_${field}`};if(e.commandType==="slash_command")return{valid:!1,reason:"slash_command_delegation_blocked"};let taskId=e.taskId;if(context.planTasks.length>0&&!context.planTasks.includes(taskId))return{valid:!1,reason:"taskId_not_in_plan"};let rawAgent=e.targetAgent,normalizedAgent=stripKnownSwarmPrefix(rawAgent);if(!context.validAgents.includes(normalizedAgent))return{valid:!1,reason:"invalid_target_agent"};let{action,files}=e;if((action==="implement"||action==="review")&&(!Array.isArray(files)||files.length===0))return{valid:!1,reason:"files_required_for_action"};let acceptanceCriteria=e.acceptanceCriteria;if(!Array.isArray(acceptanceCriteria)||acceptanceCriteria.length===0)return{valid:!1,reason:"acceptanceCriteria_required"};if("specCriteria"in e&&e.specCriteria!==void 0&&e.specCriteria!==null){let spec=e.specCriteria;if(typeof spec!=="object"||Array.isArray(spec))return{valid:!1,reason:"specCriteria_malformed"};let specObj=spec;for(let member of["fr","sc","acceptance"]){let value=specObj[member];if(value===void 0||value===null)continue;if(!Array.isArray(value)||!value.every((entry)=>typeof entry==="string"))return{valid:!1,reason:`specCriteria_${member}_malformed`}}}return{valid:!0}}function appendDelegationEnvelopeAdvisory(session,promptText,context){try{let envelope=parseDelegationEnvelope(promptText);if(!envelope)return null;let result=validateDelegationEnvelope(envelope,context);if(!result.valid)pushAdvisory(session,`DELEGATION ENVELOPE ADVISORY: a parsed delegation envelope failed validation (${result.reason}). `+"This is advisory-only — the delegation was NOT blocked. Review the envelope's structured "+"fields (including the optional specCriteria acceptance/FR/SC arrays) before the next dispatch.");return result}catch{return null}}function validateCoderReviewerAcceptanceField(promptText){let lines=promptText.split(/\r?\n/),headerRe=/^ACCEPTANCE:[ \t]*(.*)$/i,nextFieldRe=/^[A-Z][A-Z0-9_]*:/;for(let i=0;i<lines.length;i++){let match=headerRe.exec(lines[i]);if(!match)continue;if(match[1].trim().length>0)return{valid:!0};for(let j=i+1;j<lines.length;j++){if(nextFieldRe.test(lines[j]))break;if(lines[j].trim().length>0)return{valid:!0}}return{valid:!1,reason:"acceptance_field_empty"}}return{valid:!1,reason:"acceptance_field_missing"}}function extractSpecRequirementBodyById(specText,id){if(!id||id.trim().length===0)return null;let escapedId=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lines=specText.split(/\r?\n/),headerRe=new RegExp(`^\\s*[-*]?\\s*\\*\\*\\s*${escapedId}\\b`),headerIdx=-1;for(let i=0;i<lines.length;i++)if(headerRe.test(lines[i])){headerIdx=i;break}if(headerIdx===-1)return null;let headerLine=lines[headerIdx],openIdx=headerLine.indexOf("**"),closeIdx=openIdx===-1?-1:headerLine.indexOf("**",openIdx+2);if(closeIdx===-1)return null;let body=headerLine.slice(closeIdx+2);for(let i=headerIdx+1;i<lines.length;i++){let line=lines[i];if(line.trim().length===0)break;if(/^#/.test(line))break;if(/^\s*[-*]\s/.test(line))break;if(/^\s*[-*]?\s*\*\*\s*(?:FR|SC)-/.test(line))break;body+=` ${line}`}return body}function normalizeAcceptanceText(s){return s.normalize("NFC").replace(/`/g,"").replace(/\*\*/g,"").replace(/\*/g,"").replace(/^[ \t]*[-*][ \t]+/gm,"").replace(/[‘’]/g,"'").replace(/[“”]/g,'"').replace(/[—–]/g,"-").replace(/-{2,}/g,"-").replace(/Â?§/g," section ").replace(/\s+/g," ").trim().toLowerCase()}function longestCommonSuffixLength(expected,acceptance,maxScan){let len=0,cap=Math.min(expected.length,maxScan);while(len<cap&&acceptance.includes(expected.slice(expected.length-len-1)))len++;return len}function describeCoverageMiss(params){let{normalizedExpected,normalizedAcceptance}=params,divergenceOffset=0,maxScan=Math.min(normalizedExpected.length,COVERAGE_DIAG_MAX_SCAN);while(divergenceOffset<maxScan&&normalizedAcceptance.includes(normalizedExpected.slice(0,divergenceOffset+1)))divergenceOffset++;let raw=`${params.rawExpectedBody}
|
|
1186
1186
|
${params.rawAcceptanceText}`,corruptionHint;if(/�/.test(raw))corruptionHint="the text contains U+FFFD (the Unicode replacement char), a sign spec.md was decoded with the wrong encoding — re-save spec.md as UTF-8";else if(/\?{2,}/.test(raw))corruptionHint="the text contains a '??' run — a non-UTF-8 save can turn characters like § into ?? on disk; open .swarm/spec.md and re-type the affected character, then re-save as UTF-8";else if(/Ã.|â€|Â[^\s]/.test(raw))corruptionHint="the text contains a Latin-1 mojibake byte sequence (e.g. §, é) — re-save spec.md as UTF-8";if(divergenceOffset<COVERAGE_DIAG_MIN_PREFIX){let suffixLen=longestCommonSuffixLength(normalizedExpected,normalizedAcceptance,COVERAGE_DIAG_MAX_SCAN);if(suffixLen<COVERAGE_DIAG_MIN_PREFIX)return{expectedSnippet:normalizedExpected.slice(0,COVERAGE_DIAG_SNIPPET_CAP),foundSnippet:"",divergenceOffset:0,completelyMissing:!0,...corruptionHint?{corruptionHint}:{}};let matchedSuffix=normalizedExpected.slice(normalizedExpected.length-suffixLen),foundIdx2=normalizedAcceptance.indexOf(matchedSuffix),mismatchedHeadLen=Math.max(0,normalizedExpected.length-suffixLen),expectedSnippet2=normalizedExpected.slice(0,Math.min(mismatchedHeadLen,COVERAGE_DIAG_SNIPPET_CAP)),foundSnippet2=foundIdx2>0?normalizedAcceptance.slice(Math.max(0,foundIdx2-COVERAGE_DIAG_SNIPPET_CAP),foundIdx2):normalizedAcceptance.slice(0,Math.min(normalizedAcceptance.length,COVERAGE_DIAG_SNIPPET_CAP));return{expectedSnippet:expectedSnippet2,foundSnippet:foundSnippet2,divergenceOffset:0,...corruptionHint?{corruptionHint}:{}}}let expectedSnippet=normalizedExpected.slice(divergenceOffset,divergenceOffset+COVERAGE_DIAG_SNIPPET_CAP),matchedPrefix=normalizedExpected.slice(0,divergenceOffset),foundIdx=matchedPrefix.length>0?normalizedAcceptance.indexOf(matchedPrefix):-1,foundPos=foundIdx>=0?foundIdx+matchedPrefix.length:0,foundSnippet=normalizedAcceptance.slice(foundPos,foundPos+COVERAGE_DIAG_SNIPPET_CAP);return{expectedSnippet,foundSnippet,divergenceOffset,...corruptionHint?{corruptionHint}:{}}}function buildAcceptanceCoverageMismatchError(params){let{targetAgent,coverageTaskId,coverageResult}=params,diag=coverageResult.diagnostic,diagLines=[];if(diag){if(diag.completelyMissing)diagLines.push(` neither the leading nor the trailing ${COVERAGE_DIAG_MIN_PREFIX} characters of the requirement text were found anywhere in ACCEPTANCE (a shorter or partial match is treated as coincidental)`),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(' ACCEPTANCE has here: "[Requirement text completely missing from prompt]"');else diagLines.push(` first divergence at normalized offset ${diag.divergenceOffset}`+(diag.divergenceOffset===0?" (no aligned prefix found)":"")),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(` ACCEPTANCE has here: "${diag.foundSnippet}"`);if(diag.corruptionHint)diagLines.push(` ENCODING WARNING: ${diag.corruptionHint}`)}let rawExpectedBody=coverageResult.expectedBody??"",truncated=rawExpectedBody.length>ACCEPTANCE_EXPECTED_BODY_CAP,expectedBodyBlock=truncated?`${rawExpectedBody.slice(0,ACCEPTANCE_EXPECTED_BODY_CAP)}
|
|
@@ -1200,7 +1200,7 @@ ${expectedBodyBlock}
|
|
|
1200
1200
|
`).slice(0,3).join(`
|
|
1201
1201
|
`),headingMatch=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/im.exec(nextLines);if(headingMatch)return headingMatch[1].toUpperCase()}let lines=text.split(`
|
|
1202
1202
|
`),tailStart=Math.max(0,lines.length-6),inFence=!1;for(let i=0;i<lines.length;i++){if(/^\s*(?:`{3,})/.test(lines[i]))inFence=!inFence;if(i<tailStart)continue;if(inFence)continue;let line=lines[i];if(line.includes("|"))continue;let bare=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/i.exec(line);if(bare)return bare[1].toUpperCase()}return null}function taskLooksLikePlanCritic(args2){let text=[args2.prompt,args2.task,args2.description,args2.message,args2.input].filter((value)=>typeof value==="string").join(`
|
|
1203
|
-
`).toLowerCase();if(!text)return!1;return PLAN_CRITIC_TASK_SIGNALS.some((signal)=>text.includes(signal))}async function isPlanCriticApproved(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return!1;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)return!1;if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")return!1;if(approved.payloadHash!==computePlanStructureHash(plan))return!1;return!0}catch{return!1}}async function assertPlanCriticApprovedForExecution(directory,plan){if(!plan)return;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)throw Error("PLAN_CRITIC_GATE_VIOLATION: Cannot delegate to coder before plan critic approval. Delegate to critic in MODE: CRITIC-GATE and require VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded "+"(format/signal mismatch — issue #2012), call approve_plan_critic with a reason, "+"or run /swarm approve-plan-critic <reason>, to record a manual approval.");if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")throw Error("PLAN_CRITIC_GATE_VIOLATION: Latest approved-plan snapshot does not contain plan critic VERDICT: APPROVED evidence. Re-run MODE: CRITIC-GATE and wait for explicit approval before coder execution. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic or run /swarm approve-plan-critic.");if(approved.payloadHash!==computePlanStructureHash(plan))throw Error("PLAN_CRITIC_GATE_VIOLATION: Current plan differs from the last critic-approved snapshot. Re-run MODE: CRITIC-GATE after plan changes before delegating to coder. If re-review is not possible, call approve_plan_critic or run /swarm approve-plan-critic to record a fresh manual approval for the current plan.")}function resolvePlanCriticPolicyForExecution(directory,plan,sessionOverrides={}){try{let profile=getProfileForIdentity(directory,{swarm:plan.swarm,title:plan.title});if(!profile)return{required:DEFAULT_QA_GATES.critic_pre_plan,source:"default_missing_profile"};return{required:getEffectiveGates(profile,sessionOverrides).critic_pre_plan,source:sessionOverrides.critic_pre_plan===!0&&profile.gates.critic_pre_plan===!1?"session_ratchet":"persisted_profile"}}catch(error49){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error49 instanceof Error?error49.message:String(error49)}`),{required:!0,source:"corrupt_profile_conservative"}}}async function recordPlanCriticApprovalSnapshotIfApplicable(directory,input,args2,output){if((typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type):null)!=="critic")return;if(!taskLooksLikePlanCritic(args2))return;if(extractPlanCriticVerdict(output)!=="APPROVED")return;let plan=await loadPlanJsonOnly(directory);if(!plan)for(let attempt=0;attempt<2&&!plan;attempt++)await new Promise((resolve45)=>setTimeout(resolve45,150)),plan=await loadPlanJsonOnly(directory);if(!plan){warn("[delegation-gate] plan critic APPROVED verdict could not be recorded: plan.json not readable after retry. The critic_pre_plan gate will block coder delegation until a snapshot exists. Call approve_plan_critic (or /swarm approve-plan-critic) with a reason to record a manual approval if the critic genuinely approved.");return}await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",session_id:input.sessionID,call_id:input.callID,approved_at:new Date().toISOString()},payloadHashOverride:computePlanStructureHash(plan)})}async function forceRecordPlanCriticApproval(directory,sessionID,options={}){let session=ensureAgentSession(sessionID);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("NOT_AUTHORIZED: approve_plan_critic requires an active architect session. The plan-critic gate escape hatch is an architect-only escalation; a coder/reviewer cannot self-unblock. Run /swarm approve-plan-critic from an architect context, or ask the user to run it.");let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path85.join(directory,".swarm","plan.json");if(fs51.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a plan-critic approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a plan-critic "+"approval for a non-existent plan. Save a plan first.")}let planId=derivePlanId(plan),recordedAt=new Date().toISOString(),sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,userConfirmed=options.userConfirmed===!0;await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",method:"manual_override",reason:sanitizedReason,user_confirmed:userConfirmed,session_id:sessionID,approved_at:recordedAt},payloadHashOverride:computePlanStructureHash(plan)});try{appendCoreEventSync(directory,{type:"plan_critic_gate_manual_approval",timestamp:recordedAt,sessionID,plan_id:planId,user_confirmed:userConfirmed,...sanitizedReason?{reason:sanitizedReason}:{}})}catch(err){warn(`[delegation-gate] plan_critic_gate_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{planId,recordedAt,...sanitizedReason?{reason:sanitizedReason}:{},userConfirmed}}function isTaskCompletedForParallelGuidance(task){let status=task.status??"pending";return status==="completed"||status==="closed"}function getPlanTaskDeclaredFiles(plan,taskId){if(!plan||!taskId)return null;for(let phase of plan.phases){let task=phase.tasks.find((candidate)=>candidate.id===taskId);if(task)return[...task.files_touched]}return null}function describeCoderScopeFailure(args2,planTaskIdContext){if(planTaskIdContext.status==="over_limit")return`loaded plan task context exceeds the shared bounded limit (${TASK_ID_RESOLUTION_LIMITS.maxKnownIds} task ids); task-id resolution fails closed instead of guessing. Provide an explicit structured scope declaration or narrow the plan context before delegating.`;let resolution=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(planTaskIdContext)}),knownPlanTaskIds=planTaskIdContext.status==="available"?planTaskIdContext.taskIds:void 0,knownSummary=knownPlanTaskIds?[...knownPlanTaskIds].sort().join(", ")||"(none)":"(none)",rawTaskId=args2.task_id??args2.taskId,explicitFieldShape=typeof rawTaskId==="string"&&rawTaskId.trim().length>0?`"${rawTaskId.trim().slice(0,40)}" (non-plan-shaped; treated as runtime session id and ignored — falling through to text extraction)`:"absent",candidateTextFields=[args2.prompt,args2.description,args2.task,args2.input],taskLineCandidates=new Set,taskLineDetected=!1;for(let field of candidateTextFields){if(typeof field!=="string")continue;let taskLine=extractTaskLine(field);if(!taskLine)continue;taskLineDetected=!0;for(let m of taskLine.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))taskLineCandidates.add(m[1])}let textCandidates=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;for(let m of field.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))textCandidates.add(m[1])}if(resolution.status==="invalid"&&typeof rawTaskId==="string"&&isStrictTaskId(rawTaskId.trim()))return`explicit task_id "${rawTaskId.trim().slice(0,40)}" is plan-shaped but does not resolve safely against the loaded plan, so resolution fails closed before prompt fallback. Known plan task ids: ${knownSummary}.`;if(resolution.status==="over_limit")return`task-id resolution exceeded a bounded input limit (${resolution.input}); provide exactly one concise TASK: <N.M> line or a valid explicit plan task_id. Known plan task ids: ${knownSummary}.`;if(taskLineCandidates.size>1)return`multiple candidate task ids found in TASK: line: [${[...taskLineCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;if(textCandidates.size>1)return`multiple candidate task ids found in prompt text: [${[...textCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;return`no plan task id could be resolved. Include a TASK: <N.M> line or plan-task-shaped task_id arg. Explicit task_id field: ${explicitFieldShape}. TASK: line detected: ${taskLineDetected?"yes":"no"}. Known plan task ids: ${knownSummary}.`}function stripSingleTrailingAnnotationSuffix(value){let suffixMatch=value.match(/(?:\s+\([^()]*\))+$/);if(!suffixMatch)return value;let suffix=suffixMatch[0];if((suffix.match(/\([^()]*\)/g)??[]).length!==1)return null;return value.slice(0,-suffix.length).trimEnd()||null}function normalizeFileDirectiveValue(rawValue){let value=rawValue.trim();if(!value)return null;let quote=value[0];if(quote==='"'||quote==="'"){let closingQuoteIndex=value.indexOf(quote,1);if(closingQuoteIndex===-1)return null;let filePath=value.slice(1,closingQuoteIndex);if(!filePath)return null;let suffix=value.slice(closingQuoteIndex+1);if(suffix.length>0&&!/^\s+\([^()]*\)\s*$/.test(suffix))return null;return filePath}let normalized=stripSingleTrailingAnnotationSuffix(value);if(!normalized||/[,;|]/.test(normalized))return null;return normalized}function extractTaskFileDirectives(args2,mode){let files=new Set,present=!1;for(let field of[args2.prompt,args2.description,args2.task,args2.input]){if(typeof field!=="string")continue;for(let line of field.split(/\r?\n/)){if(!/^\s*FILE\s*:/i.test(line))continue;present=!0;let value=normalizeFileDirectiveValue(line.replace(/^\s*FILE\s*:\s*/i,""));if(!value){if(mode==="observe")continue;return{present:!0,files:null}}files.add(value)}}return{present,files:present&&files.size>0?[...files]:null}}function parsePerTaskVerdicts(outputText2){let verdicts=new Map,errors3=[],reviewedPattern=/^\[REVIEWED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(APPROVED|REJECTED|CONCERNS)\s*\|?/im,testedPattern=/^\[TESTED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(PASS|FAIL|SKIPPED)\s*\|?/im;for(let line of outputText2.split(/\r?\n/)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="REVIEWED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs REVIEWED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"REVIEWED"})}continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="TESTED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs TESTED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"TESTED"})}}}return{verdicts,errors:errors3}}async function findTaskAwaitingCompletion(directory,requestedTaskId){if(!directory)return null;let plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{return null}if(!plan)return null;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),tasks=plan.phases.flatMap((phase)=>phase.tasks),orderedTasks=requestedTaskId?[...tasks.filter((task)=>task.id===requestedTaskId),...tasks.filter((task)=>task.id!==requestedTaskId)]:tasks;for(let task of orderedTasks){let taskId=task.id,evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence),councilEvidence=evidence?.gates.council,awaitsQaCompletion=workflow.authoritative&&workflow.state==="tests_run",awaitsCouncilCompletion=workflow.authoritative&&workflow.state==="pre_check_passed"&&councilEvidence?.verdict==="APPROVE";if(!awaitsQaCompletion&&!awaitsCouncilCompletion)continue;let planStatus=task.status??"pending";if(planStatus==="completed"||planStatus==="closed"||planStatus==="blocked")continue;return taskId}return null}function completionGateViolationMessage(taskAwaitingCompletion){return`TASK_COMPLETION_GATE_VIOLATION: Task ${taskAwaitingCompletion} reached tests_run but is not marked completed in plan.json/plan.md. Call update_task_status with task_id="${taskAwaitingCompletion}" and status="completed". Read-only inspection remains available; a proven-disjoint task may continue; if plan.json is ledger-stale, retry save_plan with reconcile_ledger_projection=true and otherwise-unchanged plan content.`}function readCoderRetryEscalations(directory,taskId,retryEpoch){return getCoderRetryEscalationActions(directory,taskId,retryEpoch)}async function emitCoderRetryEscalation(directory,input){try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:new Date().toISOString(),taskId:input.taskId,generation:input.generation,retryEpoch:input.retryEpoch,rejectionCount:input.rejectionCount,rejectionHistory:input.rejectionHistory,phase:Number(input.taskId.split(".")[0])||0,action:input.action},{dedupeOnAuthorityKey:!0})}catch(error49){if(error49 instanceof Error&&error49.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error49}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error49){if(error49 instanceof Error&&error49.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error49}if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs51.existsSync(path85.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path85.resolve(directory),planPath=path85.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path85.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path85.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs51.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory,options={}){let plan=null,planTaskIdContext;try{if(plan=await loadPlanJsonOnly(directory),plan)planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases)}catch{}if(args2)try{let resolution=resolveTaskId(args2,{policy:"plan",...planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{}});if(resolution.status==="resolved"){if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolution.taskId)))return null;return resolution.taskId}if(resolution.status==="invalid"||resolution.status==="ambiguous"||resolution.status==="over_limit")return null}catch{}if(options.allowSessionFallback===!1)return null;return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function createDelegationGateHook(config2,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED")return;throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files]},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals78.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=async(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:await captureWorkspaceSnapshotAsync(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let normalized=normalizeToolName(input.tool),args2=output.args;if(normalized!=="Task"&&normalized!=="task"||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if((normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if((normalized==="Task"||normalized==="task")&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent);if(preflightAgent.startsWith("critic")){let legacyCriticModel=config2.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config2,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config2,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")throw telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),Error(`PLAN_CRITIC_MODEL_UNRESOLVED: the ${exactPreflightAgent} agent's effective model "${criticModel}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix the effective model configuration for "${exactPreflightAgent}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`)}catch(error49){if(error49 instanceof Error&&error49.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error49}}}}let completionArgs=output.args;if(completionArgs){let completionPlanContext;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanContext=collectPlanTaskIdContextFromPhases(plan2.phases)}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanContext?toTaskIdPlanContextOptions(completionPlanContext):void 0);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(normalized!=="Task"&&normalized!=="task")return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer")try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let activePrReviewBinding=await readPrReviewReentryBindingContext(directory,input.sessionID),reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[];if(changedFiles.length>0){let routing=await routeReviewForChanges(directory,changedFiles);if(shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch{}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
|
|
1203
|
+
`).toLowerCase();if(!text)return!1;return PLAN_CRITIC_TASK_SIGNALS.some((signal)=>text.includes(signal))}async function isPlanCriticApproved(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return!1;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)return!1;if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")return!1;if(approved.payloadHash!==computePlanStructureHash(plan))return!1;return!0}catch{return!1}}async function assertPlanCriticApprovedForExecution(directory,plan){if(!plan)return;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)throw Error("PLAN_CRITIC_GATE_VIOLATION: Cannot delegate to coder before plan critic approval. Delegate to critic in MODE: CRITIC-GATE and require VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded "+"(format/signal mismatch — issue #2012), call approve_plan_critic with a reason, "+"or run /swarm approve-plan-critic <reason>, to record a manual approval.");if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")throw Error("PLAN_CRITIC_GATE_VIOLATION: Latest approved-plan snapshot does not contain plan critic VERDICT: APPROVED evidence. Re-run MODE: CRITIC-GATE and wait for explicit approval before coder execution. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic or run /swarm approve-plan-critic.");if(approved.payloadHash!==computePlanStructureHash(plan))throw Error("PLAN_CRITIC_GATE_VIOLATION: Current plan differs from the last critic-approved snapshot. Re-run MODE: CRITIC-GATE after plan changes before delegating to coder. If re-review is not possible, call approve_plan_critic or run /swarm approve-plan-critic to record a fresh manual approval for the current plan.")}function resolvePlanCriticPolicyForExecution(directory,plan,sessionOverrides={}){try{let profile=getProfileForIdentity(directory,{swarm:plan.swarm,title:plan.title});if(!profile)return{required:DEFAULT_QA_GATES.critic_pre_plan,source:"default_missing_profile"};return{required:getEffectiveGates(profile,sessionOverrides).critic_pre_plan,source:sessionOverrides.critic_pre_plan===!0&&profile.gates.critic_pre_plan===!1?"session_ratchet":"persisted_profile"}}catch(error49){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error49 instanceof Error?error49.message:String(error49)}`),{required:!0,source:"corrupt_profile_conservative"}}}async function recordPlanCriticApprovalSnapshotIfApplicable(directory,input,args2,output){if((typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type):null)!=="critic")return;if(!taskLooksLikePlanCritic(args2))return;if(extractPlanCriticVerdict(output)!=="APPROVED")return;let plan=await loadPlanJsonOnly(directory);if(!plan)for(let attempt=0;attempt<2&&!plan;attempt++)await new Promise((resolve45)=>setTimeout(resolve45,150)),plan=await loadPlanJsonOnly(directory);if(!plan){warn("[delegation-gate] plan critic APPROVED verdict could not be recorded: plan.json not readable after retry. The critic_pre_plan gate will block coder delegation until a snapshot exists. Call approve_plan_critic (or /swarm approve-plan-critic) with a reason to record a manual approval if the critic genuinely approved.");return}await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",session_id:input.sessionID,call_id:input.callID,approved_at:new Date().toISOString()},payloadHashOverride:computePlanStructureHash(plan)})}async function forceRecordPlanCriticApproval(directory,sessionID,options={}){let session=ensureAgentSession(sessionID);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("NOT_AUTHORIZED: approve_plan_critic requires an active architect session. The plan-critic gate escape hatch is an architect-only escalation; a coder/reviewer cannot self-unblock. Run /swarm approve-plan-critic from an architect context, or ask the user to run it.");let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path85.join(directory,".swarm","plan.json");if(fs51.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a plan-critic approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a plan-critic "+"approval for a non-existent plan. Save a plan first.")}let planId=derivePlanId(plan),recordedAt=new Date().toISOString(),sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,userConfirmed=options.userConfirmed===!0;await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",method:"manual_override",reason:sanitizedReason,user_confirmed:userConfirmed,session_id:sessionID,approved_at:recordedAt},payloadHashOverride:computePlanStructureHash(plan)});try{appendCoreEventSync(directory,{type:"plan_critic_gate_manual_approval",timestamp:recordedAt,sessionID,plan_id:planId,user_confirmed:userConfirmed,...sanitizedReason?{reason:sanitizedReason}:{}})}catch(err){warn(`[delegation-gate] plan_critic_gate_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{planId,recordedAt,...sanitizedReason?{reason:sanitizedReason}:{},userConfirmed}}function isTaskCompletedForParallelGuidance(task){let status=task.status??"pending";return status==="completed"||status==="closed"}function getPlanTaskDeclaredFiles(plan,taskId){if(!plan||!taskId)return null;for(let phase of plan.phases){let task=phase.tasks.find((candidate)=>candidate.id===taskId);if(task)return[...task.files_touched]}return null}function describeCoderScopeFailure(args2,planTaskIdContext){if(planTaskIdContext.status==="over_limit")return`loaded plan task context exceeds the shared bounded limit (${TASK_ID_RESOLUTION_LIMITS.maxKnownIds} task ids); task-id resolution fails closed instead of guessing. Provide an explicit structured scope declaration or narrow the plan context before delegating.`;let resolution=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(planTaskIdContext)}),knownPlanTaskIds=planTaskIdContext.status==="available"?planTaskIdContext.taskIds:void 0,knownSummary=knownPlanTaskIds?[...knownPlanTaskIds].sort().join(", ")||"(none)":"(none)",rawTaskId=args2.task_id??args2.taskId,explicitFieldShape=typeof rawTaskId==="string"&&rawTaskId.trim().length>0?`"${rawTaskId.trim().slice(0,40)}" (non-plan-shaped; treated as runtime session id and ignored — falling through to text extraction)`:"absent",candidateTextFields=[args2.prompt,args2.description,args2.task,args2.input],taskLineCandidates=new Set,taskLineDetected=!1;for(let field of candidateTextFields){if(typeof field!=="string")continue;let taskLine=extractTaskLine(field);if(!taskLine)continue;taskLineDetected=!0;for(let m of taskLine.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))taskLineCandidates.add(m[1])}let textCandidates=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;for(let m of field.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(knownPlanTaskIds?.has(m[1]))textCandidates.add(m[1])}if(resolution.status==="invalid"&&typeof rawTaskId==="string"&&isStrictTaskId(rawTaskId.trim()))return`explicit task_id "${rawTaskId.trim().slice(0,40)}" is plan-shaped but does not resolve safely against the loaded plan, so resolution fails closed before prompt fallback. Known plan task ids: ${knownSummary}.`;if(resolution.status==="over_limit")return`task-id resolution exceeded a bounded input limit (${resolution.input}); provide exactly one concise TASK: <N.M> line or a valid explicit plan task_id. Known plan task ids: ${knownSummary}.`;if(taskLineCandidates.size>1)return`multiple candidate task ids found in TASK: line: [${[...taskLineCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;if(textCandidates.size>1)return`multiple candidate task ids found in prompt text: [${[...textCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${knownSummary}.`;return`no plan task id could be resolved. Include a TASK: <N.M> line or plan-task-shaped task_id arg. Explicit task_id field: ${explicitFieldShape}. TASK: line detected: ${taskLineDetected?"yes":"no"}. Known plan task ids: ${knownSummary}.`}function stripSingleTrailingAnnotationSuffix(value){let suffixMatch=value.match(/(?:\s+\([^()]*\))+$/);if(!suffixMatch)return value;let suffix=suffixMatch[0];if((suffix.match(/\([^()]*\)/g)??[]).length!==1)return null;return value.slice(0,-suffix.length).trimEnd()||null}function normalizeFileDirectiveValue(rawValue){let value=rawValue.trim();if(!value)return null;let quote=value[0];if(quote==='"'||quote==="'"){let closingQuoteIndex=value.indexOf(quote,1);if(closingQuoteIndex===-1)return null;let filePath=value.slice(1,closingQuoteIndex);if(!filePath)return null;let suffix=value.slice(closingQuoteIndex+1);if(suffix.length>0&&!/^\s+\([^()]*\)\s*$/.test(suffix))return null;return filePath}let normalized=stripSingleTrailingAnnotationSuffix(value);if(!normalized||/[,;|]/.test(normalized))return null;return normalized}function extractTaskFileDirectives(args2,mode){let files=new Set,present=!1;for(let field of[args2.prompt,args2.description,args2.task,args2.input]){if(typeof field!=="string")continue;for(let line of field.split(/\r?\n/)){if(!/^\s*FILE\s*:/i.test(line))continue;present=!0;let value=normalizeFileDirectiveValue(line.replace(/^\s*FILE\s*:\s*/i,""));if(!value){if(mode==="observe")continue;return{present:!0,files:null}}files.add(value)}}return{present,files:present&&files.size>0?[...files]:null}}function parsePerTaskVerdicts(outputText2){let verdicts=new Map,errors3=[],reviewedPattern=/^\[REVIEWED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(APPROVED|REJECTED|CONCERNS)\s*\|?/im,testedPattern=/^\[TESTED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(PASS|FAIL|SKIPPED)\s*\|?/im;for(let line of outputText2.split(/\r?\n/)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="REVIEWED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs REVIEWED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"REVIEWED"})}continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="TESTED")errors3.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs TESTED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"TESTED"})}}}return{verdicts,errors:errors3}}async function findTaskAwaitingCompletion(directory,requestedTaskId){if(!directory)return null;let plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{return null}if(!plan)return null;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),tasks=plan.phases.flatMap((phase)=>phase.tasks),orderedTasks=requestedTaskId?[...tasks.filter((task)=>task.id===requestedTaskId),...tasks.filter((task)=>task.id!==requestedTaskId)]:tasks;for(let task of orderedTasks){let taskId=task.id,evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence),councilEvidence=evidence?.gates.council,awaitsQaCompletion=workflow.authoritative&&workflow.state==="tests_run",awaitsCouncilCompletion=workflow.authoritative&&workflow.state==="pre_check_passed"&&councilEvidence?.verdict==="APPROVE";if(!awaitsQaCompletion&&!awaitsCouncilCompletion)continue;let planStatus=task.status??"pending";if(planStatus==="completed"||planStatus==="closed"||planStatus==="blocked")continue;return taskId}return null}function completionGateViolationMessage(taskAwaitingCompletion){return`TASK_COMPLETION_GATE_VIOLATION: Task ${taskAwaitingCompletion} reached tests_run but is not marked completed in plan.json/plan.md. Call update_task_status with task_id="${taskAwaitingCompletion}" and status="completed". Read-only inspection remains available; a proven-disjoint task may continue; if plan.json is ledger-stale, retry save_plan with reconcile_ledger_projection=true and otherwise-unchanged plan content.`}function readCoderRetryEscalations(directory,taskId,retryEpoch){return getCoderRetryEscalationActions(directory,taskId,retryEpoch)}async function emitCoderRetryEscalation(directory,input){try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:new Date().toISOString(),taskId:input.taskId,generation:input.generation,retryEpoch:input.retryEpoch,rejectionCount:input.rejectionCount,rejectionHistory:input.rejectionHistory,phase:Number(input.taskId.split(".")[0])||0,action:input.action},{dedupeOnAuthorityKey:!0})}catch(error49){if(error49 instanceof Error&&error49.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error49}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error49){if(error49 instanceof Error&&error49.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error49}if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs51.existsSync(path85.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path85.resolve(directory),planPath=path85.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path85.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path85.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs51.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory,options={}){let plan=null,planTaskIdContext;try{if(plan=await loadPlanJsonOnly(directory),plan)planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases)}catch{}if(args2)try{let resolution=resolveTaskId(args2,{policy:"plan",...planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{}});if(resolution.status==="resolved"){if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolution.taskId)))return null;return resolution.taskId}if(resolution.status==="invalid"||resolution.status==="ambiguous"||resolution.status==="over_limit")return null}catch{}if(options.allowSessionFallback===!1)return null;return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function createDelegationGateHook(config2,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED")return;throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files]},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals78.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=async(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:await captureWorkspaceSnapshotAsync(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let args2=output.args;if(!isTaskToolId(input.tool)||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if(isTaskToolId(input.tool)&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if(isTaskToolId(input.tool)&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent);if(preflightAgent.startsWith("critic")){let legacyCriticModel=config2.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config2,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config2,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")throw telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),Error(`PLAN_CRITIC_MODEL_UNRESOLVED: the ${exactPreflightAgent} agent's effective model "${criticModel}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix the effective model configuration for "${exactPreflightAgent}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`)}catch(error49){if(error49 instanceof Error&&error49.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error49}}}}let completionArgs=output.args;if(completionArgs){let completionPlanContext;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanContext=collectPlanTaskIdContextFromPhases(plan2.phases)}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanContext?toTaskIdPlanContextOptions(completionPlanContext):void 0);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(!isTaskToolId(input.tool))return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer")try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let activePrReviewBinding=await readPrReviewReentryBindingContext(directory,input.sessionID),reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[];if(changedFiles.length>0){let routing=await routeReviewForChanges(directory,changedFiles);if(shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch{}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
|
|
1204
1204
|
`),acceptanceCheck=validateCoderReviewerAcceptanceField(acceptancePromptText);if(!acceptanceCheck.valid){let detail=acceptanceCheck.reason==="acceptance_field_empty"?"its ACCEPTANCE field is present but empty/whitespace-only":"it has no ACCEPTANCE field";throw Error(`ACCEPTANCE_FIELD_REQUIRED: the ${targetAgent} delegation was blocked because ${detail}. `+"Every coder/reviewer dispatch MUST carry a non-empty ACCEPTANCE: line in its prompt — the mapped FR-###/SC-### ids "+"(for a single-task dispatch the delegation gate injects their verbatim requirement text from .swarm/spec.md automatically; phase/final-council multi-task reviewer dispatches are NOT auto-injected and must paste the verbatim text yourself) when the task maps to one or more spec requirements, or a one-line task-derived statement of what DONE looks like otherwise (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt and .swarm/spec.md). Add an ACCEPTANCE: line to the delegation prompt and re-dispatch. Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, "+"~/.cache/opencode) — the fix is in your dispatch content, not in plugin internals. If this same error "+"repeats after 2 fix attempts, STOP and present the blocker to the user.")}let coverageResult,coverageTaskId=null;try{let coveragePlan=await _internals78.loadPlanJsonOnly(directory);if(coveragePlan){let coveragePlanTaskContext=collectPlanTaskIdContextFromPhases(coveragePlan.phases);if(coverageTaskId=resolveDelegatedPlanTaskId(args2,toTaskIdPlanContextOptions(coveragePlanTaskContext)),coverageTaskId){let coverageTask=coveragePlan.phases.flatMap((phase)=>phase.tasks).find((t)=>t.id===coverageTaskId),frRefs=coverageTask?.fr_refs;if(coverageTask&&Array.isArray(frRefs)&&frRefs.length>0){let specText=await fs51.promises.readFile(path85.join(directory,".swarm","spec.md"),"utf8");injectSpecRequirementsIntoAcceptance({args:args2,frRefs,specText});let effectiveAcceptanceText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
|
|
1205
1205
|
`);coverageResult=checkAcceptanceCoversFrRefs({acceptanceText:effectiveAcceptanceText,frRefs,specText})}}}}catch{coverageResult=void 0}if(coverageResult&&coverageResult.covered===!1)throw buildAcceptanceCoverageMismatchError({targetAgent,coverageTaskId,coverageResult})}if(TASK_GATE_AGENTS.has(targetAgent)){let isPrReviewReentryAgent=targetAgent==="reviewer"||targetAgent==="test_engineer";if(isPrReviewReentryAgent&&swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);let stageBSession=ensureAgentSession(input.sessionID),activePrReviewBinding=isPrReviewReentryAgent?await readPrReviewReentryBindingContext(directory,input.sessionID):null,resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan){let knownIds=new Set(dispatchPlan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),dispatchText=[args2.prompt,args2.description,args2.task,args2.input].filter((value)=>typeof value==="string").join(`
|
|
1206
1206
|
`);for(let match of dispatchText.matchAll(/(?:task-)?(\d+\.\d+(?:\.\d+)*)/gi))if(match[1]&&knownIds.has(match[1]))candidateTaskIds.add(match[1])}let generations=new Map,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));if(activePrReviewBinding&&!resolvedTaskId&&isPrReviewReentryAgent){if(stageBSession.taskWorkflowStates.size>0||dispatchPlan)throw Error(`TASK_WORKFLOW_TASK_ID_REQUIRED: cannot dispatch ${targetAgent} for PR-review re-entry without an explicit task_id or task identifier in the prompt while a plan or task workflow state exists. Bind the re-entry to the exact task before dispatching; refusing to guess from session or plan state protects parallel tasks from cross-attribution.`);let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,null),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED",standalonePrReviewReentry:!0});return}if(await readPrReviewReentryBindingContext(directory,input.sessionID))throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} without a task workflow because its one-use PR-review re-entry authorization was already consumed or is unavailable. Issue a fresh authorization immediately before the direct Task dispatch.`)}for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config2.council)){if(!stageBSession.taskCouncilWorkflowGeneration)stageBSession.taskCouncilWorkflowGeneration=new Map;if(!stageBSession.taskCouncilWorkflowGeneration.has(taskId))stageBSession.taskCouncilWorkflowGeneration.set(taskId,workflow.generation)}if(targetAgent!=="reviewer"&&targetAgent!=="test_engineer"){generations.set(taskId,workflow.generation);continue}if(workflow.authoritative&&(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run")){generations.set(taskId,workflow.generation);continue}if(taskId===resolvedTaskId){let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"});return}throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}. Stage B (${targetAgent}) requires the task to be at pre_check_passed (or later) — a state written only by the stage_a_passed transition, which is emitted when pre_check_batch completes with the task correctly attributed. `+`Remediation: run pre_check_batch on the task's changed files first. If pre_check_batch passes but the task remains coder_delegated (typical after /swarm reset-session), run /swarm recover ${taskId} to repair Stage A attribution, then re-dispatch.`+(targetAgent==="reviewer"||targetAgent==="test_engineer"?" For PR-review re-entry outside the task workflow, issue a one-use authorization with authorize_pr_review_reentry immediately before the Task dispatch.":""))}}rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"});return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,readTaskEvidenceState:readTaskEvidenceState2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),requestedScopeTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"",classifiedFeedbackScope=isStrictTaskId(requestedScopeTaskId)?await resolvePrFeedbackScopeDeclaration(directory,input.sessionID,requestedScopeTaskId):null,resolvedPreflightTaskId=classifiedFeedbackScope?null:await resolveEvidenceTaskId(args2,session,directory),preflightPlan=classifiedFeedbackScope?null:await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidenceState=preflightTaskId?await readTaskEvidenceState2(directory,preflightTaskId):null;if(preflightEvidenceState?.kind==="unparseable"){let errorName=preflightEvidenceState.error instanceof Error?preflightEvidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${preflightTaskId} evidence at ${preflightEvidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}let preflightEvidence=preflightEvidenceState?.kind==="ok"?preflightEvidenceState.evidence:null,preflightWorkflow=getTaskWorkflowSnapshot2(preflightEvidence);if(preflightTaskId){if(await enforceCoderRetryEscalation({directory,taskId:preflightTaskId,generation:preflightWorkflow.generation,retryEpoch:preflightWorkflow.retryEpoch,retryCount:preflightWorkflow.retryCount,retryHistory:preflightWorkflow.retryHistory,criticSatisfied:preflightEvidence?.gates.critic_sounding_board!=null}),preflightWorkflow.state==="coder_delegated"){if(!(hasActiveTurboMode(input.sessionID)&&!preflightTaskId.startsWith("3.")))throw Error(`STAGE_A_REQUIRED: Task ${preflightTaskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}}let preparedScope;try{preparedScope=await prepareCoderScope(directory,input,args2)}catch(error49){if(preflightTaskId){let failed=await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId:`coder-preflight:${input.callID}`}),failedWorkflow=getTaskWorkflowSnapshot2(failed);if(failedWorkflow.retryCount>=3)await emitCoderRetryEscalation(directory,{taskId:preflightTaskId,generation:failedWorkflow.generation,retryEpoch:failedWorkflow.retryEpoch,rejectionCount:failedWorkflow.retryCount,rejectionHistory:failedWorkflow.retryHistory,action:"sounding_board_consultation"})}throw error49}let{taskId:incomingCoderTaskId}=preparedScope;if(incomingCoderTaskId)session.lastCoderDelegationTaskId=incomingCoderTaskId;let coderEvidence=incomingCoderTaskId?await readTaskEvidence2(directory,incomingCoderTaskId):null,coderWorkflow=getTaskWorkflowSnapshot2(coderEvidence),coderDispatchGeneration=coderWorkflow.generation;if(incomingCoderTaskId){if(incomingCoderTaskId!==preflightTaskId)await enforceCoderRetryEscalation({directory,taskId:incomingCoderTaskId,generation:coderWorkflow.generation,retryEpoch:coderWorkflow.retryEpoch,retryCount:coderWorkflow.retryCount,retryHistory:coderWorkflow.retryHistory,criticSatisfied:coderEvidence?.gates.critic_sounding_board!=null})}let reserveBackgroundCoderIfNeeded=async(maxConcurrent2)=>{if(!backgroundSubagentsEnabled||!isBackgroundTrue(args2.background))return;try{await _internals78.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error49){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error49 instanceof Error?error49.message:String(error49)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state])=>state==="coder_delegated").map(([taskId])=>taskId),claim=await _internals78.reserveBackgroundCoderSlotForDispatch(directory,{parentSessionId:input.sessionID,planTaskId:incomingCoderTaskId||null,callID:input.callID,maxConcurrent:maxConcurrent2,occupiedTaskIds});if(!claim.ok){let detail=claim.detail?` ${claim.detail}`:"",code=claim.reason==="capacity"?"PARALLEL_SLOTS_EXHAUSTED":claim.reason==="duplicate_task"||claim.reason==="duplicate_call"?"BACKGROUND_CODER_TASK_RESERVED":"BACKGROUND_CODER_RESERVATION_UNCERTAIN";throw Error(`${code}: background coder admission was blocked (${claim.reason}).${detail}`)}backgroundCoderReservationByCallID.set(input.callID,claim.reservation)};if(preparedScope.kind==="pr_feedback"){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}return}let plan=preparedScope.plan,profile=plan.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=scopeVerdictAllowsParallel(directory,plan),standardWorktreeIsolationActive=parallelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),parallelModeActive=standardWorktreeIsolationActive&&scopeAllowsParallel,criticPolicy=resolvePlanCriticPolicyForExecution(directory,plan,session.qaGateSessionOverrides??{});if(log(`[delegation-gate] critic_pre_plan policy task=${incomingCoderTaskId??"unknown"} required=${criticPolicy.required} source=${criticPolicy.source}`),criticPolicy.required)await assertPlanCriticApprovedForExecution(directory,plan);let{declaredFiles:incomingCoderDeclaredFiles,binding:correlatedBinding}=preparedScope;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let taskId=task.id,evidenceState=await readTaskEvidenceState2(directory,taskId);if(evidenceState.kind==="unparseable"){if(incomingCoderTaskId&&taskId===incomingCoderTaskId){let errorName=evidenceState.error instanceof Error?evidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}warn(`[delegation-gate] Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build — treating as idle for this dispatch. Repair it before the task's next delegation.`)}let durableWorkflow=getTaskWorkflowSnapshot2(evidenceState.kind==="ok"?evidenceState.evidence:null),state=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state),updateTaskWorkflowCache(session,taskId,durableWorkflow),state!=="coder_delegated")continue;let freshnessThreshold=session.sessionRehydratedAt>0?session.sessionRehydratedAt:session.lastPhaseCompleteTimestamp??0,hasCurrentSessionCoderDelegation=(swarmState.delegationChains.get(input.sessionID)??[]).some((d)=>stripKnownSwarmPrefix(d.to)==="coder"&&d.timestamp>freshnessThreshold);if(!durableWorkflow.authoritative&&!hasCurrentSessionCoderDelegation){session.taskWorkflowStates.set(taskId,"idle"),warn(`[delegation-gate] Reset stale coder_delegated state for task ${taskId} — `+"no coder delegation found in current session.");continue}if(hasActiveTurboMode(input.sessionID)){if(!taskId.startsWith("3."))continue}if(parallelModeActive&&incomingCoderTaskId&&taskId!==incomingCoderTaskId)continue;throw Error(`STAGE_A_REQUIRED: Task ${taskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}if(parallelModeActive){let coderDelegatedCount=0;for(let s of session.taskWorkflowStates.values())if(s==="coder_delegated")coderDelegatedCount++;if(coderDelegatedCount>=effectiveMaxConcurrent)throw Error(`PARALLEL_SLOTS_EXHAUSTED: ${coderDelegatedCount} coder task(s) are awaiting review (max_concurrent_tasks=${effectiveMaxConcurrent}). Dispatch reviewer/test_engineer for an in-flight coder task before starting another coder.`)}if(standardWorktreeSerializationSessions.has(input.sessionID)){if(checkStandardWorktreeSerializationRelease(input.sessionID,resolveWorktreeIsolationConfig(config2)),standardWorktreeSerializationSessions.has(input.sessionID))throw Error("STANDARD_WORKTREE_ISOLATION_SERIALIZED: prior standard worktree isolation setup failed in this session; wait for the active coder task to finish before dispatching another coder.")}await reserveBackgroundCoderIfNeeded(parallelModeActive?effectiveMaxConcurrent:1);try{if(!parallelModeActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,correlatedBinding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background);return}let resolvedTaskId=incomingCoderTaskId,laneScope=correlatedBinding.files;await precreateStandardWorktreeSession({config:config2,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,reservationId:backgroundCoderReservationByCallID.get(input.callID)?.reservationId??buildBackgroundCoderReservationId({parentSessionId:input.sessionID,planTaskId:resolvedTaskId,callID:input.callID}),generation:coderDispatchGeneration,description:typeof args2.description==="string"?args2.description:void 0,outputArgs:args2,scope:laneScope&&laneScope.length>0&&resolvedTaskId?{taskId:resolvedTaskId,files:laneScope}:void 0});let standardDispatch=standardWorktreeByCallID.get(input.callID);if(standardDispatch){if(resolvedTaskId)try{let childSessionId=typeof args2.task_id==="string"?args2.task_id.trim():"";if(!childSessionId||childSessionId===input.sessionID)throw Error("SCOPE_CHILD_IDENTITY_MISSING: worktree dispatch did not return a distinct child session id");await savePlan(standardDispatch.handle.worktreePath,plan,{preserveCompletedStatuses:!1});let childBinding=deriveChildScopeBinding(correlatedBinding,{childDirectory:standardDispatch.handle.worktreePath,childSessionId,parentCallId:input.callID});await publishScopeBinding(input.callID,standardDispatch.handle.worktreePath,childBinding);let childSession=ensureAgentSession(childSessionId,"coder",standardDispatch.handle.worktreePath);childSession.currentTaskId=childBinding.taskId,childSession.declaredCoderScope=[...childBinding.files]}catch(error49){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config2).worktree_dir),error49}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);let degradation=getStandardWorktreeDegradationReason(input.sessionID);if(degradation)try{appendCoreEventSync(directory,{type:"worktree_isolation_degraded",timestamp:new Date().toISOString(),sessionId:input.sessionID,callId:input.callID,taskId:incomingCoderTaskId,reason:degradation.reason.length>500?`${degradation.reason.slice(0,500)}… (truncated)`:degradation.reason,degradedAt:new Date(degradation.at).toISOString()})}catch(eventError){log(`[delegation-gate] worktree_isolation_degraded event write failed: ${eventError instanceof Error?eventError.message:String(eventError)}`)}await publishScopeBinding(input.callID,directory,correlatedBinding)}await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background,standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:incomingCoderTaskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner)}:void 0)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}},messagesTransform:async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastUserMessageIndex=-1;for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user"){lastUserMessageIndex=i;break}if(lastUserMessageIndex===-1)return;let lastUserMessage=messages[lastUserMessageIndex];if(!lastUserMessage?.parts)return;let agent=lastUserMessage.info?.agent;if(agent==="")return;let strippedAgent=agent?stripKnownSwarmPrefix(agent):void 0;if(strippedAgent&&strippedAgent!=="architect")return;let textPartIndex=lastUserMessage.parts.findIndex((p)=>p?.type==="text"&&p.text!==void 0);if(textPartIndex===-1)return;let textPart=lastUserMessage.parts[textPartIndex],text=textPart.text??"",taskDisclosureSessionID=lastUserMessage.info?.sessionID;if(taskDisclosureSessionID){let currentTaskIdForWindow=ensureAgentSession(taskDisclosureSessionID).currentTaskId;if(currentTaskIdForWindow){let taskLineRegex=/^[ \t]*-[ \t]*(?:\[[ x]\][ \t]+)?(\d+\.\d+(?:\.\d+)*)[:. ].*/gm,taskLines=[];taskLineRegex.lastIndex=0;let regexMatch=taskLineRegex.exec(text);while(regexMatch!==null)taskLines.push({line:regexMatch[0],taskId:regexMatch[1],index:regexMatch.index}),regexMatch=taskLineRegex.exec(text);if(taskLines.length>5){let currentIdx=taskLines.findIndex((t)=>t.taskId===currentTaskIdForWindow),windowStart=Math.max(0,currentIdx-2),windowEnd=Math.min(taskLines.length-1,currentIdx+3),visibleTasks=taskLines.slice(windowStart,windowEnd+1),hiddenBefore=windowStart,hiddenAfter=taskLines.length-1-windowEnd,totalTasks=taskLines.length,visibleCount=visibleTasks.length,firstTaskIndex=taskLines[0].index,lastTask=taskLines[taskLines.length-1],lastTaskEnd=lastTask.index+lastTask.line.length,before=text.slice(0,firstTaskIndex),after=text.slice(lastTaskEnd),visibleLines=visibleTasks.map((t)=>t.line).join(`
|
|
@@ -1212,7 +1212,7 @@ ${trimComment}${after}`}}}let sessionID=lastUserMessage.info?.sessionID,planTask
|
|
|
1212
1212
|
${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else guidance=parallelGuidance??"[NEXT] Begin the first plan task and run gates sequentially.";let carrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),insertIdx=carrierIdx>=0?carrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",guidance,insertIdx)}}let warnings=[];if(text.length>delegationMaxChars)warnings.push(`Delegation exceeds recommended size (${text.length} chars, limit ${delegationMaxChars}). Consider splitting into smaller tasks.`);if(isCoderDelegation){let fileMatches=text.match(/^FILE:/gm);if(fileMatches&&fileMatches.length>1)warnings.push(`Multiple FILE: directives detected (${fileMatches.length}). Each coder task should target ONE file.`)}if(isCoderDelegation){let taskMatches=text.match(/^TASK:/gm);if(taskMatches&&taskMatches.length>1)warnings.push(`Multiple TASK: sections detected (${taskMatches.length}). Send ONE task per coder call.`)}if(isCoderDelegation){let batchingPattern=/\b(?:and also|then also|additionally|as well as|along with|while you'?re at it)[.,]?\b/gi,batchingMatches=text.match(batchingPattern);if(batchingMatches&&batchingMatches.length>0)warnings.push(`Batching language detected (${batchingMatches.join(", ")}). Break compound objectives into separate coder calls.`)}if(isCoderDelegation){let taskLine=extractTaskLine(text);if(taskLine){if(/\s+and\s+(update|add|remove|modify|refactor|implement|create|delete|fix|change|build|deploy|write|test|move|rename|extend|extract|convert|migrate|upgrade|replace)\b/i.test(taskLine))warnings.push('TASK line contains "and" connecting separate actions')}}if(isCoderDelegation&&sessionID){let delegationChain=swarmState.delegationChains.get(sessionID);if(delegationChain&&delegationChain.length>=2){let coderIndices=[];for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){if(coderIndices.unshift(i),coderIndices.length===2)break}if(coderIndices.length===2){let prevCoderIndex=coderIndices[0],betweenCoders=delegationChain.slice(prevCoderIndex+1),hasReviewer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="reviewer"),hasTestEngineer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="test_engineer"),session=ensureAgentSession(sessionID),priorTaskStuckAtCoder=priorCoderTaskId!==null&&getTaskState(session,priorCoderTaskId)==="coder_delegated";if(!hasReviewer||!hasTestEngineer||priorTaskStuckAtCoder){if(session.qaSkipCount>=1){telemetry.qaSkipViolation(_input.sessionID,session.agentName,session.qaSkipCount+1);let skippedTasks=session.qaSkipTaskIds.join(", ");throw Error(`\uD83D\uDED1 QA GATE ENFORCEMENT: ${session.qaSkipCount+1} consecutive coder delegations without reviewer/test_engineer. Skipped tasks: [${skippedTasks}]. DELEGATE to reviewer and test_engineer NOW before any further coder work.`)}session.qaSkipCount++,session.qaSkipTaskIds.push(currentTaskId??"unknown"),warnings.push("⚠️ PROTOCOL VIOLATION: Previous coder task completed, but QA gate was skipped. "+"You MUST delegate to reviewer (code review) and test_engineer (test execution) before starting a new coder task. Review RULES 7-8 in your system prompt.")}}}}if(warnings.length===0)return;let warningText=`⚠️ BATCH DETECTED: Your coder delegation appears to contain multiple tasks.
|
|
1213
1213
|
Rule 3: ONE task per coder call. Split this into separate delegations.
|
|
1214
1214
|
${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
1215
|
-
`)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=normalized==="Task"||normalized==="task";if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(normalized==="Task"||normalized==="task"){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals77.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationId}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwner=findByCorrelationId(directory,subagentSessionId),pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals78.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals78.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals78.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals77.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async()=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge)})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals77.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals77.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals77.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdictEntry=attributionResult.verdicts.get(taskId);if(!(stageBDispatchContextByCallID.get(input.callID)?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`})}catch(err){warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB)try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state]of session.taskWorkflowStates)if(state==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID)=>{let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error49){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals78;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_schema();init_qa_gate_profile();init_core_events();init_policy();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals78={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals77.provisionWorktree},set provisionWorktree(v){_internals77.provisionWorktree=v},get removeWorktree(){return _internals77.removeWorktree},set removeWorktree(v){_internals77.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals77.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals77.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals77.postMergeCleanup},set postMergeCleanup(v){_internals77.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals77.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals77.preserveBackgroundWorktreeOwnershipForCallId=v}}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state||state.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
|
|
1215
|
+
`)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(isTaskTool2){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals77.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationId}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwner=findByCorrelationId(directory,subagentSessionId),pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals78.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals78.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals78.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals77.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async()=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge)})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals77.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals77.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals77.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdictEntry=attributionResult.verdicts.get(taskId);if(!(stageBDispatchContextByCallID.get(input.callID)?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`})}catch(err){warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB)try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state]of session.taskWorkflowStates)if(state==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID)=>{let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error49){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals78;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_schema();init_qa_gate_profile();init_core_events();init_policy();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals78={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals77.provisionWorktree},set provisionWorktree(v){_internals77.provisionWorktree=v},get removeWorktree(){return _internals77.removeWorktree},set removeWorktree(v){_internals77.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals77.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals77.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals77.postMergeCleanup},set postMergeCleanup(v){_internals77.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals77.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals77.preserveBackgroundWorktreeOwnershipForCallId=v}}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state||state.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
|
|
1216
1216
|
`)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function trajectoryStepGeneration(){return stepCounterGeneration}function bumpStepCounterGeneration(){stepCounterGeneration+=1}function evictOldestStepSessionIfNeeded(key2){if(sessionStepCounters.has(key2))return;while(sessionStepCounters.size>=MAX_TRACKED_STEP_SESSIONS){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId,directory){let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let step=(sessionStepCounters.get(key2)??0)+1;return sessionStepCounters.set(key2,step),step}function seedTrajectoryStepCounter(sessionId,directory,step){if(!Number.isFinite(step)||step<=0)return;let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let current=sessionStepCounters.get(key2)??0;if(step>current)sessionStepCounters.set(key2,Math.floor(step))}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0){let suffix=sessionKeySuffix(sessionId),removed=!1;for(let key2 of sessionStepCounters.keys())if(key2.endsWith(suffix))sessionStepCounters.delete(key2),removed=!0;if(removed)bumpStepCounterGeneration()}else if(sessionStepCounters.size>0)sessionStepCounters.clear(),bumpStepCounterGeneration()}var MAX_TRACKED_STEP_SESSIONS=500,sessionStepCounters,stepCounterGeneration=0;var init_trajectory_step_state=__esm(()=>{init_canonical_root();sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key2,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key2);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature){let next={key:key2,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current)return!1;if(expectedGeneration!==void 0&¤t.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function clearScopedModelSelectionsForSession(sessionID){let normalizedSessionID=normalizeText2(sessionID);for(let[key2,entry]of scopedModelOverrides)if(key2.startsWith(`${normalizedSessionID}␟`))scopedModelOverrides.delete(entry.key)}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key2=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key2);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key2),routesByParentCall.set(key2,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key2)}function pruneRoutes(now){for(let[key2,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key2=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key2);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function clearPendingTaskModelRoutesForSession(sessionID){let normalizedSessionID=normalizeText3(sessionID);for(let[key2,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}clearScopedModelSelectionsForSession(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,routesByParentCall,routeKeyByChildSession;var init_task_model_routing=__esm(()=>{init_model_override_state();routesByParentCall=new Map,routeKeyByChildSession=new Map});import{existsSync as existsSync45,mkdirSync as mkdirSync29,readFileSync as readFileSync32,writeFileSync as writeFileSync19}from"node:fs";import*as path86 from"node:path";function recordSessionStart(directory,startMs){try{let swarmDir=path86.join(directory,".swarm"),sessionDir=path86.join(swarmDir,"session"),filePath=path86.join(sessionDir,SESSION_START_FILE),line=JSON.stringify({startMs,ts:Date.now()});mkdirSync29(sessionDir,{recursive:!0}),writeFileSync19(filePath,`${line}
|
|
1217
1217
|
`,{flag:"a"})}catch{}}function readEarliestSessionStart(directory){try{let filePath=path86.join(directory,".swarm","session",SESSION_START_FILE);if(!existsSync45(filePath))return null;let lines=readFileSync32(filePath,"utf-8").split(`
|
|
1218
1218
|
`),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{randomUUID as randomUUID12}from"node:crypto";function parseRecordPayload(payload,label){let parsed=JSON.parse(payload);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`Invalid SQLite snapshot ${label} payload`);return parsed}function claimSnapshotSessionOwnership(sessionId,canTakeOver=!1){let existing=localSessionOwners.get(sessionId);if(existing){if(canTakeOver)existing.canTakeOver=!0;return existing.token}let token=randomUUID12();return localSessionOwners.set(sessionId,{token,canTakeOver}),token}function isSnapshotSessionOwnedLocally(sessionId){return localSessionOwners.has(sessionId)}function releaseSnapshotSessionOwnership(sessionId){localSessionOwners.delete(sessionId)}function clearSnapshotSessionOwnerships(){localSessionOwners.clear()}function nextGeneration(directory,namespace,entityKey){return(getCoordinationState(directory,namespace,entityKey)?.generation??0)+1}function writeSnapshotRows(directory,snapshot,options={}){withCoordinationTransaction(directory,()=>{transitionCoordinationState(directory,{namespace:META_NAMESPACE,entityKey:"project",generation:nextGeneration(directory,META_NAMESPACE,"project"),status:"active",payload:JSON.stringify({version:snapshot.version,writtenAt:snapshot.writtenAt,workflowSchema:snapshot.workflowSchema})});for(let[key2,aggregate]of Object.entries(snapshot.toolAggregates))transitionCoordinationState(directory,{namespace:TOOL_NAMESPACE,entityKey:key2,generation:nextGeneration(directory,TOOL_NAMESPACE,key2),status:"active",payload:JSON.stringify(aggregate)});for(let[sessionId,agentName]of Object.entries(snapshot.activeAgent)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,ACTIVE_AGENT_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:ACTIVE_AGENT_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,ACTIVE_AGENT_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(agentName)})}for(let[sessionId,chain]of Object.entries(snapshot.delegationChains)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,DELEGATION_CHAIN_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:DELEGATION_CHAIN_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,DELEGATION_CHAIN_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(chain)})}for(let[sessionId,session]of Object.entries(snapshot.agentSessions)){let localOwner=localSessionOwners.get(sessionId),ownerToken=localOwner?.token;if(options.onlyLocallyOwnedSessions&&!localOwner)continue;let current=getCoordinationState(directory,SESSION_NAMESPACE,sessionId),currentOwner2,deleted=null;try{if(current?.status==="deleted")deleted=JSON.parse(current.payload);else if(current)currentOwner2=JSON.parse(current.payload).ownerToken}catch{continue}if(options.onlyLocallyOwnedSessions&¤tOwner2&¤tOwner2!==ownerToken&&!localOwner?.canTakeOver)continue;if(deleted&&(!ownerToken||deleted.reason!=="stale"||deleted.ownerToken!==ownerToken))continue;let payload={session,...ownerToken?{ownerToken}:{}};transitionCoordinationState(directory,{namespace:SESSION_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,SESSION_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(payload)})}})}function importSnapshotRowsOnce(directory,snapshot,sourceDigest,source="session/state.json"){return importCoordinationOnce(directory,{source,sourceDigest,rowCount:Object.keys(snapshot.agentSessions).length,emptyNamespace:META_NAMESPACE},()=>writeSnapshotRows(directory,snapshot))}function readSnapshotRows(directory){if(!projectDbExists(directory))return null;return withCoordinationTransaction(directory,()=>{let meta3=listCoordinationStates(directory,META_NAMESPACE,1)[0];if(!meta3)return null;_snapshotStoreInternals.afterSnapshotMetaRead();let parsedMeta=parseRecordPayload(meta3.payload,"metadata");if(parsedMeta.version!==1&&parsedMeta.version!==2&&parsedMeta.version!==3)throw Error("Unsupported SQLite snapshot version");if(!Number.isFinite(parsedMeta.writtenAt))throw Error("Invalid SQLite snapshot metadata writtenAt");if(parsedMeta.workflowSchema!==void 0&&typeof parsedMeta.workflowSchema!=="string")throw Error("Invalid SQLite snapshot metadata workflowSchema");let snapshot={version:parsedMeta.version,writtenAt:parsedMeta.writtenAt,...parsedMeta.workflowSchema!==void 0&&{workflowSchema:parsedMeta.workflowSchema},toolAggregates:{},activeAgent:{},delegationChains:{},agentSessions:{}};for(let row of listCoordinationStates(directory,TOOL_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS))snapshot.toolAggregates[row.entityKey]=parseRecordPayload(row.payload,"tool aggregate");for(let row of listCoordinationStates(directory,ACTIVE_AGENT_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let agentName=JSON.parse(row.payload);if(typeof agentName!=="string")throw Error("Invalid SQLite snapshot active-agent payload");snapshot.activeAgent[row.entityKey]=agentName}for(let row of listCoordinationStates(directory,DELEGATION_CHAIN_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let chain=JSON.parse(row.payload);if(!Array.isArray(chain))throw Error("Invalid SQLite snapshot delegation-chain payload");snapshot.delegationChains[row.entityKey]=chain}for(let row of listCoordinationStates(directory,SESSION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let payload=parseRecordPayload(row.payload,"agent-session");if(!payload.session||typeof payload.session!=="object"||Array.isArray(payload.session)||payload.ownerToken!==void 0&&typeof payload.ownerToken!=="string")throw Error("Invalid SQLite snapshot agent-session payload");snapshot.agentSessions[row.entityKey]=payload.session}return snapshot})}function isSnapshotSessionAuthoritativelyStale(directory,sessionId,staleDurationMs,now=Date.now()){try{if(!projectDbExists(directory)||!sessionId)return!1;let row=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(!row||row.status==="deleted")return!0;let lastToolCallTime=parseRecordPayload(row.payload,"agent-session").session?.lastToolCallTime;if(typeof lastToolCallTime!=="number"||!Number.isFinite(lastToolCallTime))return!1;return now-lastToolCallTime>staleDurationMs}catch{return!1}}function clearSnapshotRows(directory){if(!projectDbExists(directory))return 0;let removed=0;return withCoordinationTransaction(directory,()=>{for(let namespace of SNAPSHOT_NAMESPACES)for(let row of listCoordinationStates(directory,namespace,MAX_COORDINATION_STATE_LIST_ROWS))if(deleteCoordinationState(directory,namespace,row.entityKey,row.revision))removed+=1;deleteCoordinationImports(directory,["session/state.json",SNAPSHOT_PROJECTION_SOURCE])}),removed}function deleteSnapshotSessionRows(directory,sessionId,reason="ended"){if(!projectDbExists(directory)||!sessionId)return 0;let removed=0;return withCoordinationTransaction(directory,()=>{let ownerToken=localSessionOwners.get(sessionId)?.token,sessionRow=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(reason==="stale"&&!ownerToken)return;if(sessionRow&&sessionRow.status!=="deleted")try{let persistedOwner=JSON.parse(sessionRow.payload).ownerToken;if(persistedOwner&&persistedOwner!==ownerToken)return}catch{return}for(let namespace of[SESSION_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE]){let row=getCoordinationState(directory,namespace,sessionId);if(!row||row.status==="deleted")continue;if(transitionCoordinationState(directory,{namespace,entityKey:sessionId,expectedRevision:row.revision,generation:row.generation+1,status:"deleted",payload:JSON.stringify({reason,...ownerToken?{ownerToken}:{}})}).outcome==="applied")removed+=1}}),removed}var META_NAMESPACE="session.snapshot.meta",SESSION_NAMESPACE="session.snapshot.agent",TOOL_NAMESPACE="session.snapshot.tool",ACTIVE_AGENT_NAMESPACE="session.snapshot.active-agent",DELEGATION_CHAIN_NAMESPACE="session.snapshot.delegation-chain",SNAPSHOT_PROJECTION_SOURCE="session/state.sqlite-projection.json",SNAPSHOT_NAMESPACES,_snapshotStoreInternals,localSessionOwners;var init_snapshot_store=__esm(()=>{init_coordination_store();init_project_db();SNAPSHOT_NAMESPACES=[META_NAMESPACE,SESSION_NAMESPACE,TOOL_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE],_snapshotStoreInternals={afterSnapshotMetaRead:()=>{}},localSessionOwners=new Map});import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}async function countWorktrees(directory){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return 0}return new Promise((resolve45)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS2,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve45(0);return}let count=0;for(let line of stdout.split(`
|
|
@@ -3340,8 +3340,8 @@ Flags:
|
|
|
3340
3340
|
--resume resume the existing loop run from durable state in
|
|
3341
3341
|
.swarm/loop/ instead of starting a new objective`;var init_loop=__esm(()=>{DEPTHS2=new Set(["standard","exhaustive"]),AUTONOMY_LEVELS=new Set(["checkpoint","auto"]);_internals151={readLatestLoopState}});import{createHash as createHash72}from"node:crypto";import*as fs99 from"node:fs/promises";import*as path186 from"node:path";function validateHeldoutRecallCorpusManifest(value){if(!value||typeof value!=="object")throw Error("held-out corpus manifest must be an object");let manifest=value;if(typeof manifest.corpus_id!=="string"||!manifest.corpus_id.trim())throw Error("held-out corpus manifest requires corpus_id");if(manifest.split!=="heldout")throw Error("held-out corpus manifest requires heldout split");if(manifest.version!==void 0&&(typeof manifest.version!=="string"||!manifest.version.trim()))throw Error("held-out corpus manifest has invalid version");if(manifest.thresholds!==void 0){if(!manifest.thresholds||typeof manifest.thresholds!=="object"||Array.isArray(manifest.thresholds)||Object.keys(manifest.thresholds).length===0)throw Error("held-out corpus manifest has invalid thresholds");for(let[name,threshold]of Object.entries(manifest.thresholds))if(!name.trim()||typeof threshold!=="number"||!Number.isFinite(threshold))throw Error("held-out corpus manifest has invalid thresholds")}if(!Array.isArray(manifest.cases)||manifest.cases.length===0||manifest.cases.length>MAX_CORPUS_CASES)throw Error("held-out corpus manifest has invalid cases");let sourcePaths=new Set,caseIds=new Set;for(let[index,entry]of manifest.cases.entries()){if(!entry||typeof entry!=="object")throw Error(`held-out corpus case ${index} must be an object`);let item=entry;for(let key2 of["language","paraphrase"])if(typeof item[key2]!=="string"||!item[key2].trim())throw Error(`held-out corpus case ${index} has invalid ${key2}`);for(let key2 of["expected_symbols","known_misses"])if(!Array.isArray(item[key2])||item[key2].length===0||item[key2].some((element)=>typeof element!=="string"||!element.trim()))throw Error(`held-out corpus case ${index} has invalid ${key2}`);for(let key2 of["expected_edges","spurious_edges"])if(!Array.isArray(item[key2])||item[key2].length===0||item[key2].some((edge)=>!isValidEdge(edge)))throw Error(`held-out corpus case ${index} has invalid ${key2}`);for(let key2 of["id","analyzer_id"])if(item[key2]!==void 0&&(typeof item[key2]!=="string"||!item[key2].trim()))throw Error(`held-out corpus case ${index} has invalid ${key2}`);let scenarioId=typeof item.id==="string"?item.id:`${item.language}-${index+1}`;if(caseIds.has(scenarioId))throw Error(`held-out corpus case ${index} duplicates id`);if(caseIds.add(scenarioId),item.source_path!==void 0&&(typeof item.source_path!=="string"||!item.source_path.trim()))throw Error(`held-out corpus case ${index} has invalid source_path`);if(item.content_hash!==void 0&&(typeof item.content_hash!=="string"||!/^[a-f0-9]{64}$/i.test(item.content_hash)))throw Error(`held-out corpus case ${index} has invalid content_hash`);if(typeof item.source_path==="string"){if(sourcePaths.has(item.source_path))throw Error(`held-out corpus case ${index} duplicates source_path`);sourcePaths.add(item.source_path)}}}function isValidEdge(value){if(typeof value==="string")return Boolean(value.trim());if(!value||typeof value!=="object"||Array.isArray(value))return!1;let edge=value;return typeof edge.from==="string"&&Boolean(edge.from.trim())&&typeof edge.to==="string"&&Boolean(edge.to.trim())}function computeCanonicalSourceHash(source){return createHash72("sha256").update(source.toString("utf8").replace(/\r\n?|\n/g,`
|
|
3342
3342
|
`)).digest("hex")}async function loadHeldoutRecallEvaluationScenarios(corpusDirectory){let root=await fs99.realpath(path186.resolve(corpusDirectory)),manifestPath2=await fs99.realpath(path186.join(root,"manifest.json")),manifestRelative=path186.relative(root,manifestPath2);if(manifestRelative.startsWith("..")||path186.isAbsolute(manifestRelative))throw Error("held-out corpus manifest path escapes corpus root");let stat19=await fs99.stat(manifestPath2);if(!stat19.isFile())throw Error("held-out corpus manifest must be a regular file");if(stat19.size>MAX_HELDOUT_MANIFEST_BYTES)throw Error("held-out corpus manifest exceeds byte limit");let manifest=JSON.parse(await fs99.readFile(manifestPath2,"utf8"));validateHeldoutRecallCorpusManifest(manifest);let totalSourceBytes=0,scenarios=[];for(let[index,entry]of manifest.cases.entries()){if(!entry.source_path||!entry.content_hash)throw Error("held-out corpus source cases require source_path and content_hash");let sourceCandidate=path186.resolve(root,entry.source_path),candidateRelative=path186.relative(root,sourceCandidate);if(candidateRelative.startsWith("..")||path186.isAbsolute(candidateRelative))throw Error("held-out corpus source path escapes corpus root");let sourcePath=await fs99.realpath(sourceCandidate),relative41=path186.relative(root,sourcePath);if(relative41.startsWith("..")||path186.isAbsolute(relative41))throw Error("held-out corpus source path escapes corpus root");let sourceStat=await fs99.stat(sourcePath);if(!sourceStat.isFile())throw Error("held-out corpus source must be a regular file");if(sourceStat.size>MAX_SOURCE_BYTES2)throw Error("held-out corpus source exceeds byte limit");if(totalSourceBytes+=sourceStat.size,totalSourceBytes>MAX_TOTAL_SOURCE_BYTES)throw Error("held-out corpus sources exceed aggregate byte limit");let source=await fs99.readFile(sourcePath),sourceHash=computeCanonicalSourceHash(source);if(entry.content_hash&&sourceHash!==entry.content_hash.toLowerCase())throw Error(`held-out corpus source hash mismatch: ${entry.source_path}`);scenarios.push({...entry,id:entry.id??`${entry.language}-${index+1}`,source_text:source.toString("utf8"),source_hash:sourceHash,source_provenance:"direct-source"})}return{manifest,scenarios}}var MAX_CORPUS_CASES=256,MAX_HELDOUT_MANIFEST_BYTES=1048576,MAX_SOURCE_BYTES2=1048576,MAX_TOTAL_SOURCE_BYTES=4194304;var init_heldout_evaluation_corpus=()=>{};import{createHash as createHash73}from"node:crypto";import*as fs100 from"node:fs/promises";import*as os27 from"node:os";import*as path187 from"node:path";async function evaluateMemoryRecallFixtures(options){let fixtureDirectory=path187.resolve(options.fixtureDirectory),providers=options.providers??DEFAULT_PROVIDERS,modes=options.modes??DEFAULT_MODES,profiles=options.profiles,resourceCaps={candidate_count:Math.max(1,Math.trunc(options.resourceCaps?.candidate_count??20)),token_budget:Math.max(1,Math.trunc(options.resourceCaps?.token_budget??1000))},generatedAt=new Date().toISOString(),heldout=options.heldoutCorpusDirectory?await loadHeldoutRecallEvaluationScenarios(options.heldoutCorpusDirectory):void 0,fixtures=heldout?(()=>{let candidateRecords=materializeHeldoutCandidateRecords(heldout.scenarios);return heldout.scenarios.map((scenario)=>materializeHeldoutScenario(scenario,candidateRecords))})():await loadRecallEvaluationFixtures(fixtureDirectory),runs=[];for(let fixture of fixtures){let materialized=materializeFixture(fixture);for(let providerName of providers){let runProfiles=profiles??[void 0];for(let profile of runProfiles){let tempRoot=await fs100.realpath(await fs100.mkdtemp(path187.join(os27.tmpdir(),"swarm-memory-eval-"))),provider=createEvaluationProvider(providerName,tempRoot,profile,options.dependencies);try{await provider.initialize?.();for(let record3 of materialized.records)await provider.upsert(record3);for(let mode of modes){let request=buildRecallRequest(fixture,mode,profile?resourceCaps:void 0);if(profile)request.quality={profile,candidateCap:resourceCaps.candidate_count};let started=Date.now(),recallResult=provider.recallWithDiagnostics?await provider.recallWithDiagnostics(request):{items:await provider.recall(request)},retrievedIds=recallResult.items.map((item)=>item.record.id),trace=recallResult.qualityTrace,run=buildRun({fixture,provider:providerName,mode,k:fixture.k??request.maxItems,retrievedIds,materialized,profile,resourceCaps,trace,latencyMs:Math.max(0,Date.now()-started),identity:createRunIdentity({fixture,provider:providerName,profile,dependencies:options.dependencies,resourceCaps})});runs.push(run)}}finally{if(await provider.close?.(),!options.keepTempRoots)evictAndClose(tempRoot),await rmTempRoot(tempRoot)}}}}return{schema_version:1,generated_at:generatedAt,fixture_directory:fixtureDirectory,providers,modes,summary:summarizeRuns(fixtures.length,runs),runs,manifest:createRecallEvaluationManifest({fixtureDirectory,providers,profiles,fixtures,dependencies:options.dependencies,resourceCaps,heldoutCorpusId:heldout?.manifest.corpus_id,minimumProfileThreshold:heldout?.manifest.thresholds?.precision_at_k}),comparisons:buildProfileComparisons(runs)}}async function rmTempRoot(tempRoot){for(let attempt=0;attempt<10;attempt++)try{await fs100.rm(tempRoot,{recursive:!0,force:!0});return}catch(err){if(attempt===9)throw err;await new Promise((resolve75)=>setTimeout(resolve75,50))}}async function loadRecallEvaluationFixtures(fixtureDirectory){let files=(await fs100.readdir(fixtureDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map((entry)=>entry.name).sort((a,b)=>a.localeCompare(b)),fixtures=[];for(let file3 of files){let raw=await fs100.readFile(path187.join(fixtureDirectory,file3),"utf-8");fixtures.push(validateFixture(JSON.parse(raw),file3))}return fixtures}function materializeHeldoutScenario(scenario,candidateRecords){let scope={type:"repository",repoId:"heldout-retrieval-corpus"},label=`heldout:${scenario.id}`;return{name:label,query:scenario.paraphrase,task:scenario.paraphrase,scopes:[scope],kinds:["code_pattern"],k:1,maxItems:1,tokenBudget:512,expectedLabels:[label],records:[...candidateRecords],sourceHash:scenario.source_hash,scenario:{id:scenario.id,language:scenario.language,analyzer_id:scenario.analyzer_id,source_provenance:scenario.source_provenance,index_state:"not-measured",graph_measurement:{status:"unmeasured",reason:"held-out memory evaluation uses direct source retrieval; graph extraction/index controls require the repo-graph evaluator"},expected_symbols:scenario.expected_symbols,expected_edges:scenario.expected_edges,known_misses:scenario.known_misses,spurious_edges:scenario.spurious_edges}}}function materializeHeldoutCandidateRecords(candidateCorpus){let scope={type:"repository",repoId:"heldout-retrieval-corpus"};return candidateCorpus.map((candidate)=>({label:`heldout:${candidate.id}`,scope,kind:"code_pattern",text:candidate.source_text,tags:[candidate.language,candidate.analyzer_id??"direct-source"],confidence:1,source:{type:"file",filePath:candidate.source_path},metadata:{sourceHash:candidate.source_hash}}))}function createEvaluationProvider(provider,root,profile,dependencies){let config3={...DEFAULT_MEMORY_CONFIG,enabled:!0,provider,embeddings:{...DEFAULT_MEMORY_CONFIG.embeddings,enabled:profile==="hybrid"||profile==="hybrid+rerank"},retrieval:{...DEFAULT_MEMORY_CONFIG.retrieval,rerank:{...DEFAULT_MEMORY_CONFIG.retrieval.rerank,enabled:profile==="hybrid+rerank"}}};if(provider==="sqlite"&&profile)return new SQLiteMemoryProvider(root,config3,void 0,dependencies);return createConfiguredMemoryProvider(root,config3)}function buildRecallRequest(fixture,mode,resourceCaps){let maxItems=Math.min(resourceCaps?.candidate_count??5,fixture.maxItems??fixture.k??5);return{query:fixture.query,task:fixture.task,agentRole:mode==="curator"?"curator":fixture.agentRole,mode,scopes:fixture.scopes,kinds:fixture.kinds,maxItems,tokenBudget:Math.min(resourceCaps?.token_budget??1000,fixture.tokenBudget??1000),minScore:mode==="injection"?0.25:0,requireQuerySignal:mode==="injection"}}function materializeFixture(fixture){let idsByLabel=new Map,labelsById=new Map,baseRecords=fixture.records.map((record3)=>{let base={scope:record3.scope,kind:record3.kind,text:record3.text},id=createMemoryId(base);return idsByLabel.set(record3.label,id),labelsById.set(id,record3.label),{input:record3,id,base}}),expectedIds=new Set(fixture.expectedLabels.map((label)=>{let id=idsByLabel.get(label);if(!id)throw Error(`fixture ${fixture.name} expected unknown label ${label}`);return id})),allowedScopeKeys=new Set(fixture.scopes.map(stableScopeKey)),staleIds=new Set,crossScopeIds=new Set,sameScopeNoiseIds=new Set;return{records:baseRecords.map(({input,id,base})=>{let supersededBy=input.state?.supersededByLabel?idsByLabel.get(input.state.supersededByLabel):void 0;if(input.state?.supersededByLabel&&!supersededBy)throw Error(`fixture ${fixture.name} record ${input.label} supersedes unknown label ${input.state.supersededByLabel}`);let metadata={...input.metadata??{},fixture:fixture.name,fixtureLabel:input.label,...input.state?.deleted?{deleted:!0}:{}},record3={id,...base,tags:input.tags??[],confidence:input.confidence??0.8,stability:input.stability??"durable",source:input.source??{type:"manual",ref:fixture.name},createdAt:DEFAULT_TIMESTAMP,updatedAt:DEFAULT_TIMESTAMP,expiresAt:input.state?.expiresAt,supersededBy,contentHash:computeMemoryContentHash(base),metadata};if(record3.metadata.deleted===!0||record3.supersededBy||record3.expiresAt&&Date.parse(record3.expiresAt)<=Date.now())staleIds.add(record3.id);if(!allowedScopeKeys.has(stableScopeKey(record3.scope)))crossScopeIds.add(record3.id);else if(!expectedIds.has(record3.id)&&!staleIds.has(record3.id))sameScopeNoiseIds.add(record3.id);return validateMemoryRecordRules(record3,{rejectDurableSecrets:!0})}),idsByLabel,labelsById,expectedIds,staleIds,crossScopeIds,sameScopeNoiseIds}}function buildRun(args2){let{fixture,provider,mode,k,retrievedIds,materialized,profile,resourceCaps,trace,latencyMs,identity}=args2,relevantAtK=retrievedIds.slice(0,k).filter((id)=>materialized.expectedIds.has(id)).length,crossScopeLeakCount=retrievedIds.filter((id)=>materialized.crossScopeIds.has(id)).length,staleMemoryCount=retrievedIds.filter((id)=>materialized.staleIds.has(id)).length,noisyInjectionCount=mode==="injection"?retrievedIds.filter((id)=>materialized.sameScopeNoiseIds.has(id)).length:0,sameScopeNoiseCount=retrievedIds.filter((id)=>materialized.sameScopeNoiseIds.has(id)).length,metrics={"precision@k":relevantAtK/Math.max(k,1),"recall@k":relevantAtK/Math.max(materialized.expectedIds.size,1),injection_count:mode==="injection"?retrievedIds.length:0,noisy_injection_count:noisyInjectionCount,same_scope_noise_count:sameScopeNoiseCount,cross_scope_leak_count:crossScopeLeakCount,stale_memory_count:staleMemoryCount},base={fixture:fixture.name,provider,mode,k,query:fixture.query,expected_labels:fixture.expectedLabels,expected_ids:fixture.expectedLabels.map((label)=>materialized.idsByLabel.get(label)??label),retrieved_labels:retrievedIds.map((id)=>materialized.labelsById.get(id)??id),retrieved_ids:retrievedIds,metrics,passed:metrics["recall@k"]>=1&&metrics.noisy_injection_count===0&&metrics.cross_scope_leak_count===0&&metrics.stale_memory_count===0};if(!profile)return base;let status=provider!=="sqlite"&&profile!=="lexical"?"skipped":trace?.status??(profile==="lexical"?"complete":"degraded");return{...base,profile,status,...status==="complete"?{}:{degradation_reason:trace?.degradationReason??(provider!=="sqlite"?"profile requires sqlite provider":"retrieval component unavailable")},provenance:trace?.provenance??(profile==="lexical"?"lexical":"unavailable"),resource_cap:resourceCaps,resource_usage:normalizeResourceUsage(trace?.resourceUsage),latency_ms:Number.isFinite(trace?.latencyMs)?trace?.latencyMs??latencyMs:latencyMs,cost_provenance:"offline-deterministic-unavailable",cost:{provenance:"offline-deterministic-unavailable",amount:null},identity,...fixture.scenario?{scenario:fixture.scenario}:{}}}function normalizeResourceUsage(usage){if(!usage)return;let candidate=usage,bounded=(value)=>Number.isFinite(value)?Math.max(0,value):0;return{lexical_candidate_count:bounded(candidate.lexical_candidate_count),dense_candidate_count:bounded(candidate.dense_candidate_count),rerank_candidate_count:bounded(candidate.rerank_candidate_count),returned_count:bounded(candidate.returned_count),query_embedding_invocation_count:bounded(candidate.query_embedding_invocation_count),returned_token_estimate:bounded(candidate.returned_token_estimate)}}function createRecallEvaluationManifest(args2){let corpusHash=createHash73("sha256").update(stableStringify2(args2.fixtures)).digest("hex"),configHash=createHash73("sha256").update(stableStringify2({providers:args2.providers,profiles:args2.profiles??["legacy"],resourceCaps:args2.resourceCaps,embeddingModel:args2.dependencies?.embeddingProvider?.modelVersion??"disabled",rerankerModel:args2.dependencies?.reranker?.modelVersion??"disabled"})).digest("hex");return{version:"1.0.0",source_id:args2.heldoutCorpusId?`heldout:${args2.heldoutCorpusId}`:`fixtures:${corpusHash}`,model_id:args2.profiles?.includes("hybrid")||args2.profiles?.includes("hybrid+rerank")?args2.dependencies?.embeddingProvider?.modelVersion??"configured-embedding":"none",provider_id:`providers:${args2.providers.join(",")}`,config_hash:configHash,corpus_hash:corpusHash,profile_thresholds:Object.fromEntries((args2.profiles??["lexical"]).map((profile)=>[profile,typeof args2.minimumProfileThreshold==="number"&&Number.isFinite(args2.minimumProfileThreshold)&&args2.minimumProfileThreshold>0?args2.minimumProfileThreshold:0.01])),sample_counts:{total:args2.fixtures.length},metric_definitions:{precision:"precision@k",recall:"recall@k"},uncertainty:{method:"deterministic-fixture",confidence:0.95,sample_count:args2.fixtures.length},variants:Object.fromEntries((args2.profiles??["lexical"]).map((profile)=>[profile,{source_id:args2.heldoutCorpusId?`heldout:${args2.heldoutCorpusId}`:`fixtures:${corpusHash}`,model_id:profile==="lexical"?"none":args2.dependencies?.embeddingProvider?.modelVersion??"configured-embedding",provider_id:`profiles:${profile};providers:${args2.providers.join(",")}`,config_hash:createHash73("sha256").update(stableStringify2({profile,resourceCaps:args2.resourceCaps})).digest("hex")}]))}}function createRunIdentity(args2){let profile=args2.profile??"legacy";return{source_id:args2.fixture.scenario?`source:${args2.fixture.scenario.id}:${args2.fixture.sourceHash}`:`fixture:${args2.fixture.name}:${createHash73("sha256").update(args2.fixture.query).digest("hex")}`,model_id:profile==="lexical"?"none":args2.dependencies?.embeddingProvider?.modelVersion??"configured-embedding",provider_id:args2.provider,config_hash:createHash73("sha256").update(stableStringify2({profile,resourceCaps:args2.resourceCaps,model:args2.dependencies?.embeddingProvider?.modelVersion??"configured",reranker:args2.dependencies?.reranker?.modelVersion??"disabled"})).digest("hex")}}function buildProfileComparisons(runs){let groups=new Map;for(let run of runs){if(!run.profile)continue;let key2=`${run.fixture}\x00${run.provider}\x00${run.mode}`,group=groups.get(key2)??[];group.push(run),groups.set(key2,group)}let comparisons=[];for(let group of groups.values()){let baseline=group.find((run)=>run.profile==="lexical");if(!baseline)continue;for(let variant of group){if(variant===baseline||!variant.profile)continue;comparisons.push({fixture:baseline.fixture,provider:baseline.provider,mode:baseline.mode,baseline_profile:"lexical",variant_profile:variant.profile,precision_at_k_delta:variant.metrics["precision@k"]-baseline.metrics["precision@k"],recall_at_k_delta:variant.metrics["recall@k"]-baseline.metrics["recall@k"],latency_ms_delta:(variant.latency_ms??0)-(baseline.latency_ms??0),cost_delta:null,cost_comparison:"unavailable"})}}return comparisons.sort((a,b)=>`${a.fixture}:${a.variant_profile}`.localeCompare(`${b.fixture}:${b.variant_profile}`))}function stableStringify2(value){if(Array.isArray(value))return`[${value.map(stableStringify2).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key2,item])=>`${JSON.stringify(key2)}:${stableStringify2(item)}`).join(",")}}`;return JSON.stringify(value)}function summarizeRuns(fixtureCount,runs){let total=runs.reduce((acc,run)=>{if(acc["precision@k"]+=run.metrics["precision@k"],acc["recall@k"]+=run.metrics["recall@k"],acc.injection_count+=run.metrics.injection_count,acc.noisy_injection_count+=run.metrics.noisy_injection_count,acc.same_scope_noise_count+=run.metrics.same_scope_noise_count,acc.cross_scope_leak_count+=run.metrics.cross_scope_leak_count,acc.stale_memory_count+=run.metrics.stale_memory_count,run.passed)acc.passed_run_count++;return acc},{"precision@k":0,"recall@k":0,injection_count:0,noisy_injection_count:0,same_scope_noise_count:0,cross_scope_leak_count:0,stale_memory_count:0,passed_run_count:0}),denominator=Math.max(runs.length,1);return{fixture_count:fixtureCount,run_count:runs.length,passed_run_count:total.passed_run_count,"precision@k":total["precision@k"]/denominator,"recall@k":total["recall@k"]/denominator,injection_count:total.injection_count,noisy_injection_count:total.noisy_injection_count,same_scope_noise_count:total.same_scope_noise_count,cross_scope_leak_count:total.cross_scope_leak_count,stale_memory_count:total.stale_memory_count}}function validateFixture(value,file3){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} must be an object`);let fixture=value;if(typeof fixture.name!=="string"||!fixture.name)throw Error(`memory recall fixture ${file3} is missing name`);if(typeof fixture.query!=="string"||fixture.query.length<3)throw Error(`memory recall fixture ${file3} has invalid query`);if(!Array.isArray(fixture.scopes)||fixture.scopes.length===0)throw Error(`memory recall fixture ${file3} must define scopes`);let scopes=fixture.scopes.map((scope,index)=>validateScope(scope,file3,`scope #${index+1}`));if(!Array.isArray(fixture.expectedLabels)||fixture.expectedLabels.length===0)throw Error(`memory recall fixture ${file3} must define expectedLabels`);let expectedLabels=fixture.expectedLabels.map((label,index)=>{if(typeof label!=="string"||!label)throw Error(`memory recall fixture ${file3} expectedLabels #${index+1} must be a non-empty string`);return label});if(!Array.isArray(fixture.records)||fixture.records.length===0)throw Error(`memory recall fixture ${file3} must define records`);let records=fixture.records.map((record3,index)=>validateFixtureRecord(record3,file3,index));return{...fixture,name:fixture.name,query:fixture.query,scopes,expectedLabels,records}}function validateFixtureRecord(value,file3,index){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} record #${index+1} must be an object`);let record3=value,labelForError=typeof record3.label==="string"&&record3.label?record3.label:`#${index+1}`;if(typeof record3.label!=="string"||!record3.label)throw Error(`memory recall fixture ${file3} record ${labelForError} is missing label`);let scope=validateScope(record3.scope,file3,`record ${record3.label}`);if(!("kind"in record3)||record3.kind==="")throw Error(`memory recall fixture ${file3} record ${record3.label} is missing kind`);if(typeof record3.kind!=="string")throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid kind`);let parsedKind=MemoryKindSchema.safeParse(record3.kind);if(!parsedKind.success)throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid kind`);if(!("text"in record3)||record3.text==="")throw Error(`memory recall fixture ${file3} record ${record3.label} is missing text`);if(typeof record3.text!=="string")throw Error(`memory recall fixture ${file3} record ${record3.label} has invalid text`);return{...record3,label:record3.label,scope,kind:parsedKind.data,text:record3.text}}function validateScope(value,file3,descriptor){if(!value||typeof value!=="object")throw Error(`memory recall fixture ${file3} ${descriptor} is missing scope`);let scope=value;if(typeof scope.type!=="string")throw Error(`memory recall fixture ${file3} ${descriptor} has invalid scope type`);let parsed=MemoryScopeRefSchema.safeParse(scope);if(!parsed.success)throw Error(`memory recall fixture ${file3} ${descriptor} has invalid scope`);return parsed.data}var DEFAULT_PROVIDERS,DEFAULT_MODES,DEFAULT_TIMESTAMP="2026-05-26T12:00:00.000Z";var init_evaluation=__esm(()=>{init_config2();init_gateway();init_heldout_evaluation_corpus();init_provider_pool();init_schema2();init_sqlite_provider();DEFAULT_PROVIDERS=["local-jsonl","sqlite"],DEFAULT_MODES=["manual","injection","curator"]});function extractMemoryProposalsFromAgentOutput(outputText2){let candidates=candidateJsonBlocks(outputText2);for(let candidate of candidates){let parsedJson=parseJsonObject(candidate);if(parsedJson===null)continue;let parsed=AgentOutputMemorySchema.safeParse(parsedJson);if(!parsed.success)return{proposals:[],error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")};if(parsed.data.memoryProposals)return{proposals:parsed.data.memoryProposals}}return{proposals:[]}}function extractCuratorMemoryDecisionsFromAgentOutput(outputText2){let candidates=candidateJsonBlocks(outputText2);for(let candidate of candidates){let parsedJson=parseJsonObject(candidate);if(parsedJson===null)continue;let parsed=CuratorOutputMemoryDecisionSchema.safeParse(parsedJson);if(!parsed.success)return{decisions:[],error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")};if(parsed.data.curatorMemoryDecisions)return{decisions:parsed.data.curatorMemoryDecisions}}return{decisions:[]}}function extractReviewFindingsFromAgentOutput(outputText2){let error93,validReviews=[];for(let candidate of candidateJsonBlocks(outputText2)){let parsedJson=parseJsonObject(candidate);if(parsedJson===null||!("findings"in parsedJson))continue;let parsed=ReviewFindingsSchema.safeParse(parsedJson);if(!parsed.success){error93??=formatSchemaError(parsed.error);continue}validReviews.push(parsed.data)}if(validReviews.length!==1)return{findings:[],error:validReviews.length===0?error93??"expected exactly one valid structured findings block, found 0":`expected exactly one valid structured findings block, found ${validReviews.length}`};return{findings:validReviews[0].findings,review:validReviews[0]}}function extractFindingValidationsFromAgentOutput(outputText2){let error93,validValidations=[];for(let candidate of candidateJsonBlocks(outputText2)){let parsedJson=parseJsonObject(candidate);if(parsedJson===null||!("validations"in parsedJson))continue;let parsed=FindingValidationsSchema.safeParse(parsedJson);if(!parsed.success){error93??=formatSchemaError(parsed.error);continue}validValidations.push(parsed.data)}if(validValidations.length!==1)return{validations:[],error:validValidations.length===0?error93??"expected exactly one valid structured validation block, found 0":`expected exactly one valid structured validation block, found ${validValidations.length}`};return{validations:validValidations[0].validations}}function candidateJsonBlocks(outputText2){if(typeof outputText2!=="string"||outputText2.length===0)return[];let boundedOutput=outputText2.slice(0,MAX_AGENT_OUTPUT_CHARS),trimmed=boundedOutput.trim(),candidates=[];if(trimmed.length<=MAX_JSON_CANDIDATE_CHARS&&trimmed.startsWith("{")&&trimmed.endsWith("}"))candidates.push(trimmed);let fencePattern=/```(?:json)?\s*([\s\S]*?)```/gi;for(let match of boundedOutput.matchAll(fencePattern)){let block=match[1]?.trim();if(block&&block.length<=MAX_JSON_CANDIDATE_CHARS&&block.startsWith("{")&&block.endsWith("}")){if(candidates.push(block),candidates.length>=MAX_JSON_CANDIDATES)break}}return candidates}function formatSchemaError(error93){return error93.issues.slice(0,20).map((issue3)=>`${issue3.path.join(".")||"<root>"}: ${issue3.message}`).join("; ").slice(0,2000)}function parseJsonObject(candidate){try{let parsed=JSON.parse(candidate);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{return null}}var AgentMemoryProposalSchema,AgentOutputMemorySchema,CuratorOutputMemoryDecisionSchema,ReviewFindingSchema,ReviewFindingsSchema,FindingValidationSchema,FindingValidationsSchema,MAX_JSON_CANDIDATES=20,MAX_JSON_CANDIDATE_CHARS=262144,MAX_AGENT_OUTPUT_CHARS=1048576;var init_agent_output_schema=__esm(()=>{init_zod();init_schema2();AgentMemoryProposalSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:MemoryKindSchema.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()}).strict(),AgentOutputMemorySchema=exports_external.object({memoryProposals:exports_external.array(AgentMemoryProposalSchema).max(20).optional()}).passthrough(),CuratorOutputMemoryDecisionSchema=exports_external.object({curatorMemoryDecisions:exports_external.array(CuratorMemoryDecisionSchema).max(20).optional()}).passthrough(),ReviewFindingSchema=exports_external.object({title:exports_external.string().trim().min(1).max(200),body:exports_external.string().trim().min(1).max(2000),severity:exports_external.enum(["critical","high","medium","low","info"]),confidence:exports_external.number().finite().min(0).max(1),file:exports_external.string().trim().min(1).max(500),line_start:exports_external.number().int().min(1).max(1e7),line_end:exports_external.number().int().min(1).max(1e7)}).strict().superRefine((finding,ctx)=>{if(finding.line_end<finding.line_start)ctx.addIssue({code:exports_external.ZodIssueCode.custom,path:["line_end"],message:"line_end must be greater than or equal to line_start"})}),ReviewFindingsSchema=exports_external.object({findings:exports_external.array(ReviewFindingSchema).max(50),verdict:exports_external.enum(["APPROVED","REJECTED"]),overall_confidence:exports_external.number().finite().min(0).max(1)}).strict(),FindingValidationSchema=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),disposition:exports_external.enum(["CONFIRMED","DISPROVED","UNVERIFIED"]),confidence:exports_external.number().finite().min(0).max(1),evidence:exports_external.string().trim().min(1).max(2000)}).strict(),FindingValidationsSchema=exports_external.object({validations:exports_external.array(FindingValidationSchema).max(50)}).strict()});function buildMemoryRecallPlan(input,options={}){let profile=options.profile??resolveMemoryRecallProfile(input.agentRole),scopes=options.scopes??[];return{query:buildRecallQuery(input),scopes,kinds:[...profile.kinds],maxItems:profile.maxItems,tokenBudget:profile.tokenBudget}}function buildRecallQuery(input){let lines=[`${input.agentRole} task: ${input.agentTask}`,`user goal: ${input.userGoal}`],repoProject=[input.projectId,input.repoId,input.repoRoot].filter((value)=>Boolean(value?.trim())).join(" ");if(repoProject)lines.push(`repo/project: ${repoProject}`);if(input.touchedFiles&&input.touchedFiles.length>0)lines.push(`touched files: ${input.touchedFiles.join(", ")}`);if(input.currentPlanSummary?.trim())lines.push(`current plan: ${input.currentPlanSummary.trim()}`);return lines.join(`
|
|
3343
|
-
`)}var init_recall_planner=__esm(()=>{init_role_profiles()});import*as path188 from"node:path";async function appendMemoryRunLog(directory,runId,event){let safeRunId=sanitizeRunId(runId),relativePath2=path188.join("runs",safeRunId,"memory.jsonl"),filePath=validateSwarmPath(directory,relativePath2);await appendCappedJsonl(filePath,JSON.stringify({...event,runId:safeRunId,timestamp:event.timestamp??new Date().toISOString()}),{maxEntries:resolveRetentionCap("MAX_RUN_LOG_ENTRIES",MAX_RUN_LOG_ENTRIES)})}function sanitizeRunId(runId){return(runId?.trim()||"unknown").replace(/[^A-Za-z0-9._-]/g,"_").slice(0,80)||"unknown"}var MAX_RUN_LOG_ENTRIES=2000;var init_run_log=__esm(()=>{init_utils2();init_caps();init_jsonl_cap()});import*as path189 from"node:path";function createMemoryLifecycleHooks(options){let internals={createGateway:options.createGateway??createMemoryGateway,appendRunLog:options.appendRunLog??appendMemoryRunLog};return{messagesTransform:async(input,output)=>{await injectIntoMessages(input,output,options,internals)},toolAfter:async(input,output)=>{await captureTaskOutputProposals(input,output,options,internals)}}}async function injectIntoMessages(input,output,options,internals){let messages=output?.messages;if(!Array.isArray(messages)||messages.length===0)return;if(messagesContainRecall(messages))return;let sessionID=getSessionID(input,messages),agentRole=resolveMessageAgent(messages,options,sessionID),latestUserText=latestTextForRole(messages,"user");if(!latestUserText)return;let agentTask=extractTaskToolPrompt(messages)??latestUserText,unitId=options.getActiveTaskId?.(sessionID),localTokenBudget=resolveMemoryConfig(options.config).recall.injection.tokenBudget,claim=claimTurnBudget(sessionID??"","memory-recall",localTokenBudget,{localMaxTokens:localTokenBudget,surface:"messages"}),grantedTokenBudget=claim.granted;if(!claim.ledgerPresent)log("memory-injector: no injection ledger this turn — failing open to recall.injection.tokenBudget; unified hard ceiling unavailable");let result=await recallForAgent({directory:options.directory,config:options.config,sessionID,agentRole,agentId:agentRole,userGoal:latestUserText,agentTask,unitId,tokenBudgetOverride:grantedTokenBudget,createGateway:internals.createGateway,appendRunLog:internals.appendRunLog});if(result)await maybeWriteUnitIdProbe({directory:options.directory,sessionID,agentRole,unitId,agentTask,bundleId:result.bundle.id});if(!result||result.bundle.items.length===0)return;let insertAt=recallMessageInsertIndex(messages),recallMessage=insertGuidanceCarrier(messages,"memory-recall",result.bundle.promptBlock,insertAt,{agent:agentRole,sessionID});if(!deliveredGuidanceDelta(recallMessage,result.bundle.promptBlock)){log("memory-injector: recall block not delivered (empty text or non-renderable carrier) — emission and run-log skipped");return}recordProducerEmission(sessionID??"","memory-recall",result.bundle.tokenEstimate,Math.max(0,grantedTokenBudget-result.bundle.tokenEstimate),"messages"),await internals.appendRunLog(options.directory,sessionID,{event:"prompt_injected",runId:sessionID??"unknown",agentRole,agentId:agentRole,bundleId:result.bundle.id,memoryIds:result.bundle.items.map((item)=>item.record.id),tokenEstimate:result.bundle.tokenEstimate,metadata:{surface:"chat_messages"}})}async function captureTaskOutputProposals(input,output,options,internals){let task=parseTaskToolInput(input);if(!task)return;let outputText2=output?.output;if(typeof outputText2!=="string"||!outputText2.includes("memoryProposals")&&!outputText2.includes("curatorMemoryDecisions"))return;let extracted=outputText2.includes("memoryProposals")?extractMemoryProposalsFromAgentOutput(outputText2):{proposals:[]};if(extracted.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:extracted.error});return}let decisionExtraction=outputText2.includes("curatorMemoryDecisions")?extractCuratorMemoryDecisionsFromAgentOutput(outputText2):{decisions:[]};if(decisionExtraction.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:decisionExtraction.error});return}if(extracted.proposals.length===0&&decisionExtraction.decisions.length===0)return;let gateway=internals.createGateway({directory:options.directory,sessionID:task.sessionID,agentRole:task.agentRole,agentId:task.agentRole,runId:task.sessionID},{config:options.config});if(!gateway.isEnabled()){await gateway.dispose?.();return}try{for(let proposalInput of extracted.proposals)try{let proposal=await gateway.propose(proposalInput);await internals.appendRunLog(options.directory,task.sessionID,{event:proposal.status==="pending"?"proposal_created":"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:proposal.id,rejectionReason:proposal.rejectionReason})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:err instanceof Error?err.message:String(err)})}if(decisionExtraction.decisions.length>0&&!isCuratorAgent(task.agentRole)){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"only curator agents may emit curatorMemoryDecisions"});return}if(decisionExtraction.decisions.length>0){let applyCuratorDecisionMethod=gateway.applyCuratorDecision;if(!applyCuratorDecisionMethod){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"memory gateway does not support curator decisions"});return}let applyCuratorDecision=applyCuratorDecisionMethod.bind(gateway);for(let decision of decisionExtraction.decisions)try{let change=await applyCuratorDecision(decision);await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_applied",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:change.proposalId,memoryIds:[change.memoryId,change.targetMemoryId,change.oldMemoryId,change.replacementMemoryId].filter((id)=>Boolean(id)),rejectionReason:change.reason,metadata:{action:change.action,proposalStatus:change.proposalStatus,eventId:change.eventId}})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:decision.proposalId,rejectionReason:err instanceof Error?err.message:String(err),metadata:{action:decision.action}})}}}finally{await gateway.dispose?.()}}async function recallForAgent(input){let gateway=input.createGateway({directory:input.directory,sessionID:input.sessionID,agentRole:input.agentRole,agentId:input.agentId,runId:input.sessionID,unitId:input.unitId},{config:input.config});try{let resolvedConfig=resolveMemoryConfig(input.config);if(!gateway.isEnabled())return await logInjectionSkipped(input,"disabled"),null;if(!resolvedConfig.recall.injection.enabled)return await logInjectionSkipped(input,"disabled"),null;let scopes=gateway.deriveAllowedScopes(),planInput={userGoal:compactText(input.userGoal),runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,agentTask:compactText(input.agentTask),touchedFiles:extractTouchedFiles(input.agentTask)},plan=buildMemoryRecallPlan(planInput,{scopes});plan.maxItems=resolvedConfig.recall.injection.maxItems,plan.tokenBudget=input.tokenBudgetOverride??resolvedConfig.recall.injection.tokenBudget,await input.appendRunLog(input.directory,input.sessionID,{event:"recall_requested",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,metadata:{kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,scopeTypes:plan.scopes.map((scope)=>scope.type)}});let recallInput={query:plan.query,task:planInput.agentTask,mode:"injection",scopes:plan.scopes,kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,minScore:resolvedConfig.recall.injection.minScore,requireQuerySignal:resolvedConfig.recall.injection.requireQuerySignal},bundle=await gateway.recall(recallInput);if(await input.appendRunLog(input.directory,input.sessionID,{event:"recall_returned",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle.id,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate}),bundle.items.length===0)await logInjectionSkipped(input,bundle.diagnostics?.injectionSkipReason??"no_results",bundle);return{bundle,scopes}}finally{await gateway.dispose?.()}}async function logInjectionSkipped(input,reason,bundle){await input.appendRunLog(input.directory,input.sessionID,{event:"prompt_injection_skipped",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle?.id,memoryIds:bundle?.items.map((item)=>item.record.id),scores:bundle?.items.map((item)=>item.score),tokenEstimate:bundle?.tokenEstimate,rejectionReason:reason,metadata:{reason,candidateCount:bundle?.diagnostics?.candidateCount,preScoredFilteredCount:bundle?.diagnostics?.preScoredFilteredCount,noSignalCount:bundle?.diagnostics?.noSignalCount,belowThresholdCount:bundle?.diagnostics?.belowThresholdCount}})}async function maybeWriteUnitIdProbe(input){if(process.env.OPENCODE_SWARM_MEMORY_UNITID_PROBE!=="1")return;try{let match=input.agentTask.match(UNITID_PROBE_TASK_ID_PATTERN),record3={sessionID:input.sessionID,agentRole:input.agentRole,resolvedUnitId:input.unitId??null,promptTaskIdCandidate:match?match[1]:null,agentTaskSnippet:input.agentTask.slice(0,160),bundleId:input.bundleId,timestamp:new Date().toISOString()},filePath=validateSwarmPath(input.directory,path189.join("memory","unitid-probe.jsonl"));await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNITID_PROBE_ENTRIES",MAX_UNITID_PROBE_ENTRIES)})}catch{}}function parseTaskToolInput(input){let record3=input,rawTool=typeof record3.tool==="string"?record3.tool:void 0,toolName=rawTool?normalizeToolName(rawTool)??rawTool:void 0;if(toolName!=="Task"&&toolName!=="task")return null;if(!record3.args||typeof record3.args!=="object")return null;let args2=record3.args,prompt=args2.prompt;if(typeof prompt!=="string"||prompt.trim().length===0)return null;let target=typeof args2.subagent_type==="string"?args2.subagent_type:typeof args2.agent==="string"?args2.agent:typeof record3.agent==="string"?record3.agent:"architect";return{sessionID:typeof record3.sessionID==="string"?record3.sessionID:void 0,agentRole:stripKnownSwarmPrefix(target),prompt}}function isCuratorAgent(agentRole){return agentRole==="curator"||agentRole==="curator_init"||agentRole==="curator_phase"||agentRole==="curator_postmortem"}function messagesContainRecall(messages){return messages.some((message)=>message?.parts?.some((part)=>{let text=part?.text;if(typeof text!=="string")return!1;return RECALL_BUNDLE_MARKER_RE.test(text)||text.includes(MEMORY_SENTINEL)}))}function getSessionID(input,messages){let inputSession=input?.sessionID;if(typeof inputSession==="string")return inputSession;for(let message of messages){let sessionID=message?.info?.sessionID;if(typeof sessionID==="string")return sessionID}return}function resolveMessageAgent(messages,options,sessionID){let configured=options.getActiveAgentName?.(sessionID);if(configured)return stripKnownSwarmPrefix(configured);for(let message of messages){let agent=message?.info?.agent;if(typeof agent==="string")return stripKnownSwarmPrefix(agent)}return"architect"}function latestTextForRole(messages,role){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.info?.role!==role||!Array.isArray(message.parts))continue;let text=message.parts.map((part)=>part?.text).filter((partText)=>typeof partText==="string").join(`
|
|
3344
|
-
`).trim();if(text)return text}return null}function extractTaskToolPrompt(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if((msg.role??msg.info?.role)!=="assistant")continue;let content=Array.isArray(msg.content)?msg.content:Array.isArray(msg.parts)?msg.parts:[];for(let j=content.length-1;j>=0;j--){let block=content[j];if(block&&typeof block==="object"){let b=block;if(b.type==="tool_use"&&b.name==="
|
|
3343
|
+
`)}var init_recall_planner=__esm(()=>{init_role_profiles()});import*as path188 from"node:path";async function appendMemoryRunLog(directory,runId,event){let safeRunId=sanitizeRunId(runId),relativePath2=path188.join("runs",safeRunId,"memory.jsonl"),filePath=validateSwarmPath(directory,relativePath2);await appendCappedJsonl(filePath,JSON.stringify({...event,runId:safeRunId,timestamp:event.timestamp??new Date().toISOString()}),{maxEntries:resolveRetentionCap("MAX_RUN_LOG_ENTRIES",MAX_RUN_LOG_ENTRIES)})}function sanitizeRunId(runId){return(runId?.trim()||"unknown").replace(/[^A-Za-z0-9._-]/g,"_").slice(0,80)||"unknown"}var MAX_RUN_LOG_ENTRIES=2000;var init_run_log=__esm(()=>{init_utils2();init_caps();init_jsonl_cap()});import*as path189 from"node:path";function createMemoryLifecycleHooks(options){let internals={createGateway:options.createGateway??createMemoryGateway,appendRunLog:options.appendRunLog??appendMemoryRunLog};return{messagesTransform:async(input,output)=>{await injectIntoMessages(input,output,options,internals)},toolAfter:async(input,output)=>{await captureTaskOutputProposals(input,output,options,internals)}}}async function injectIntoMessages(input,output,options,internals){let messages=output?.messages;if(!Array.isArray(messages)||messages.length===0)return;if(messagesContainRecall(messages))return;let sessionID=getSessionID(input,messages),agentRole=resolveMessageAgent(messages,options,sessionID),latestUserText=latestTextForRole(messages,"user");if(!latestUserText)return;let agentTask=extractTaskToolPrompt(messages)??latestUserText,unitId=options.getActiveTaskId?.(sessionID),localTokenBudget=resolveMemoryConfig(options.config).recall.injection.tokenBudget,claim=claimTurnBudget(sessionID??"","memory-recall",localTokenBudget,{localMaxTokens:localTokenBudget,surface:"messages"}),grantedTokenBudget=claim.granted;if(!claim.ledgerPresent)log("memory-injector: no injection ledger this turn — failing open to recall.injection.tokenBudget; unified hard ceiling unavailable");let result=await recallForAgent({directory:options.directory,config:options.config,sessionID,agentRole,agentId:agentRole,userGoal:latestUserText,agentTask,unitId,tokenBudgetOverride:grantedTokenBudget,createGateway:internals.createGateway,appendRunLog:internals.appendRunLog});if(result)await maybeWriteUnitIdProbe({directory:options.directory,sessionID,agentRole,unitId,agentTask,bundleId:result.bundle.id});if(!result||result.bundle.items.length===0)return;let insertAt=recallMessageInsertIndex(messages),recallMessage=insertGuidanceCarrier(messages,"memory-recall",result.bundle.promptBlock,insertAt,{agent:agentRole,sessionID});if(!deliveredGuidanceDelta(recallMessage,result.bundle.promptBlock)){log("memory-injector: recall block not delivered (empty text or non-renderable carrier) — emission and run-log skipped");return}recordProducerEmission(sessionID??"","memory-recall",result.bundle.tokenEstimate,Math.max(0,grantedTokenBudget-result.bundle.tokenEstimate),"messages"),await internals.appendRunLog(options.directory,sessionID,{event:"prompt_injected",runId:sessionID??"unknown",agentRole,agentId:agentRole,bundleId:result.bundle.id,memoryIds:result.bundle.items.map((item)=>item.record.id),tokenEstimate:result.bundle.tokenEstimate,metadata:{surface:"chat_messages"}})}async function captureTaskOutputProposals(input,output,options,internals){let task=parseTaskToolInput(input);if(!task)return;let outputText2=output?.output;if(typeof outputText2!=="string"||!outputText2.includes("memoryProposals")&&!outputText2.includes("curatorMemoryDecisions"))return;let extracted=outputText2.includes("memoryProposals")?extractMemoryProposalsFromAgentOutput(outputText2):{proposals:[]};if(extracted.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:extracted.error});return}let decisionExtraction=outputText2.includes("curatorMemoryDecisions")?extractCuratorMemoryDecisionsFromAgentOutput(outputText2):{decisions:[]};if(decisionExtraction.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:decisionExtraction.error});return}if(extracted.proposals.length===0&&decisionExtraction.decisions.length===0)return;let gateway=internals.createGateway({directory:options.directory,sessionID:task.sessionID,agentRole:task.agentRole,agentId:task.agentRole,runId:task.sessionID},{config:options.config});if(!gateway.isEnabled()){await gateway.dispose?.();return}try{for(let proposalInput of extracted.proposals)try{let proposal=await gateway.propose(proposalInput);await internals.appendRunLog(options.directory,task.sessionID,{event:proposal.status==="pending"?"proposal_created":"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:proposal.id,rejectionReason:proposal.rejectionReason})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:err instanceof Error?err.message:String(err)})}if(decisionExtraction.decisions.length>0&&!isCuratorAgent(task.agentRole)){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"only curator agents may emit curatorMemoryDecisions"});return}if(decisionExtraction.decisions.length>0){let applyCuratorDecisionMethod=gateway.applyCuratorDecision;if(!applyCuratorDecisionMethod){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"memory gateway does not support curator decisions"});return}let applyCuratorDecision=applyCuratorDecisionMethod.bind(gateway);for(let decision of decisionExtraction.decisions)try{let change=await applyCuratorDecision(decision);await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_applied",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:change.proposalId,memoryIds:[change.memoryId,change.targetMemoryId,change.oldMemoryId,change.replacementMemoryId].filter((id)=>Boolean(id)),rejectionReason:change.reason,metadata:{action:change.action,proposalStatus:change.proposalStatus,eventId:change.eventId}})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:decision.proposalId,rejectionReason:err instanceof Error?err.message:String(err),metadata:{action:decision.action}})}}}finally{await gateway.dispose?.()}}async function recallForAgent(input){let gateway=input.createGateway({directory:input.directory,sessionID:input.sessionID,agentRole:input.agentRole,agentId:input.agentId,runId:input.sessionID,unitId:input.unitId},{config:input.config});try{let resolvedConfig=resolveMemoryConfig(input.config);if(!gateway.isEnabled())return await logInjectionSkipped(input,"disabled"),null;if(!resolvedConfig.recall.injection.enabled)return await logInjectionSkipped(input,"disabled"),null;let scopes=gateway.deriveAllowedScopes(),planInput={userGoal:compactText(input.userGoal),runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,agentTask:compactText(input.agentTask),touchedFiles:extractTouchedFiles(input.agentTask)},plan=buildMemoryRecallPlan(planInput,{scopes});plan.maxItems=resolvedConfig.recall.injection.maxItems,plan.tokenBudget=input.tokenBudgetOverride??resolvedConfig.recall.injection.tokenBudget,await input.appendRunLog(input.directory,input.sessionID,{event:"recall_requested",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,metadata:{kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,scopeTypes:plan.scopes.map((scope)=>scope.type)}});let recallInput={query:plan.query,task:planInput.agentTask,mode:"injection",scopes:plan.scopes,kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,minScore:resolvedConfig.recall.injection.minScore,requireQuerySignal:resolvedConfig.recall.injection.requireQuerySignal},bundle=await gateway.recall(recallInput);if(await input.appendRunLog(input.directory,input.sessionID,{event:"recall_returned",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle.id,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate}),bundle.items.length===0)await logInjectionSkipped(input,bundle.diagnostics?.injectionSkipReason??"no_results",bundle);return{bundle,scopes}}finally{await gateway.dispose?.()}}async function logInjectionSkipped(input,reason,bundle){await input.appendRunLog(input.directory,input.sessionID,{event:"prompt_injection_skipped",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle?.id,memoryIds:bundle?.items.map((item)=>item.record.id),scores:bundle?.items.map((item)=>item.score),tokenEstimate:bundle?.tokenEstimate,rejectionReason:reason,metadata:{reason,candidateCount:bundle?.diagnostics?.candidateCount,preScoredFilteredCount:bundle?.diagnostics?.preScoredFilteredCount,noSignalCount:bundle?.diagnostics?.noSignalCount,belowThresholdCount:bundle?.diagnostics?.belowThresholdCount}})}async function maybeWriteUnitIdProbe(input){if(process.env.OPENCODE_SWARM_MEMORY_UNITID_PROBE!=="1")return;try{let match=input.agentTask.match(UNITID_PROBE_TASK_ID_PATTERN),record3={sessionID:input.sessionID,agentRole:input.agentRole,resolvedUnitId:input.unitId??null,promptTaskIdCandidate:match?match[1]:null,agentTaskSnippet:input.agentTask.slice(0,160),bundleId:input.bundleId,timestamp:new Date().toISOString()},filePath=validateSwarmPath(input.directory,path189.join("memory","unitid-probe.jsonl"));await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNITID_PROBE_ENTRIES",MAX_UNITID_PROBE_ENTRIES)})}catch{}}function parseTaskToolInput(input){let record3=input,rawTool=typeof record3.tool==="string"?record3.tool:void 0;if(!isTaskToolId(rawTool))return null;if(!record3.args||typeof record3.args!=="object")return null;let args2=record3.args,prompt=args2.prompt;if(typeof prompt!=="string"||prompt.trim().length===0)return null;let target=typeof args2.subagent_type==="string"?args2.subagent_type:typeof args2.agent==="string"?args2.agent:typeof record3.agent==="string"?record3.agent:"architect";return{sessionID:typeof record3.sessionID==="string"?record3.sessionID:void 0,agentRole:stripKnownSwarmPrefix(target),prompt}}function isCuratorAgent(agentRole){return agentRole==="curator"||agentRole==="curator_init"||agentRole==="curator_phase"||agentRole==="curator_postmortem"}function messagesContainRecall(messages){return messages.some((message)=>message?.parts?.some((part)=>{let text=part?.text;if(typeof text!=="string")return!1;return RECALL_BUNDLE_MARKER_RE.test(text)||text.includes(MEMORY_SENTINEL)}))}function getSessionID(input,messages){let inputSession=input?.sessionID;if(typeof inputSession==="string")return inputSession;for(let message of messages){let sessionID=message?.info?.sessionID;if(typeof sessionID==="string")return sessionID}return}function resolveMessageAgent(messages,options,sessionID){let configured=options.getActiveAgentName?.(sessionID);if(configured)return stripKnownSwarmPrefix(configured);for(let message of messages){let agent=message?.info?.agent;if(typeof agent==="string")return stripKnownSwarmPrefix(agent)}return"architect"}function latestTextForRole(messages,role){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.info?.role!==role||!Array.isArray(message.parts))continue;let text=message.parts.map((part)=>part?.text).filter((partText)=>typeof partText==="string").join(`
|
|
3344
|
+
`).trim();if(text)return text}return null}function extractTaskToolPrompt(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if((msg.role??msg.info?.role)!=="assistant")continue;let content=Array.isArray(msg.content)?msg.content:Array.isArray(msg.parts)?msg.parts:[];for(let j=content.length-1;j>=0;j--){let block=content[j];if(block&&typeof block==="object"){let b=block;if(b.type==="tool_use"&&isTaskToolId(typeof b.name==="string"?b.name:void 0)){let prompt=b.input?.prompt;if(typeof prompt==="string"&&prompt.length>0)return prompt}if(b.type==="tool"&&isTaskToolId(b.tool)){let prompt=b.state?.input?.prompt;if(typeof prompt==="string"&&prompt.length>0)return prompt}}}}return null}function recallMessageInsertIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user")return i;return messages.length}function extractTouchedFiles(text){let matches=text.match(/\b(?:src|tests|test|docs|scripts|packages)\/[A-Za-z0-9._/@+-]+/g);return Array.from(new Set(matches??[])).slice(0,20)}function compactText(text){let compacted=text.replace(/\s+/g," ").trim();if(compacted.length<=2000)return compacted;return Array.from(compacted).slice(0,2000).join("")}var MEMORY_SENTINEL,UNITID_PROBE_TASK_ID_PATTERN,MAX_UNITID_PROBE_ENTRIES=2000;var init_injector=__esm(()=>{init_agent_output_schema();init_schema();init_normalize_tool_name();init_utils2();init_caps();init_jsonl_cap();init_injection_budget();init_logger();init_config2();init_gateway();init_recall_planner();init_run_log();init_sentinel();MEMORY_SENTINEL=MEMORY_RECALL_SENTINEL;UNITID_PROBE_TASK_ID_PATTERN=/\bTASK:\s*(\d+(?:\.\d+)+)\b/});function containerScopedDefaultVisibility(grammarId,containerType){if(containerType==="interface_declaration")return"public";switch(grammarId){case"kotlin":return"public";case"java":return"package";case"swift":return"internal";case"cpp":return containerType==="struct_specifier"||containerType==="union_specifier"?"public":"private";default:return containerType===void 0?"internal":"private"}}function collectCommonJsExports(source){let sanitized=maskCommentsAndStrings(source),exportsByLocal=new Map,add2=(localName,exportedName,sourceIndex)=>{if(!isIdentifier(localName)||!isIdentifier(exportedName))return;let existing=exportsByLocal.get(localName);if(existing&&existing.sourceIndex<=sourceIndex)return;exportsByLocal.set(localName,{localName,exportedName,exportedReason:"explicit_export",sourceIndex})};for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[1],match[1],match.index??0);for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*\{([^}]*)\}/g)){let body=match[1],baseIndex=match.index??0;for(let part of body.split(",")){let entry=part.trim();if(!entry)continue;let alias=entry.match(/^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)$/);if(alias){add2(alias[2],alias[1],baseIndex+match[0].indexOf(part));continue}let shorthand=entry.match(/^([A-Za-z_$][\w$]*)$/);if(shorthand)add2(shorthand[1],shorthand[1],baseIndex+match[0].indexOf(part))}}for(let match of sanitized.matchAll(/\b(?:module\s*\.\s*exports|exports)\s*\.\s*([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[2],match[1],match.index??0);return exportsByLocal}function collectPythonAllNames(source){let match=source.match(/__all__\s*=\s*([[({])([\s\S]*?)[\])}]/);if(!match)return null;let body=match[2].trim();if(!body)return new Set;let names=new Set;for(let part of body.split(",")){let trimmed=part.trim();if(!trimmed)continue;let stringMatch=trimmed.match(/^['"]([^'"]+)['"]$/);if(!stringMatch)return null;names.add(stringMatch[1])}return names}function getSymbolVisibilityInfo(ctx){if(hasPrivateContainer(ctx.defNode,ctx.grammarId))return{...PRIVATE_INFO};if(ctx.explicitExported||ctx.commonJsExport)return{exported:!0,visibility:"public",exportedReason:"explicit_export",apiSurfaceKind:"export"};let ownVisibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(ctx.kind==="method"){if(ctx.grammarId==="go")return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};if(ctx.grammarId==="python"&&ctx.pythonParentClassExported){let isPrivate=ctx.localName.startsWith("_"),isInit=ctx.localName==="__init__";if(isPrivate||isInit)return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"modifier",apiSurfaceKind:"public"}}if(ownVisibility==="unknown"&&CONTAINER_SCOPED_GRAMMARS.has(ctx.grammarId)){let implicit=containerScopedDefaultVisibility(ctx.grammarId,ctx.parentContainerType);return{exported:!1,visibility:implicit,exportedReason:"module_public",apiSurfaceKind:implicit==="private"?"private":"public"}}return{exported:!1,visibility:ownVisibility,exportedReason:ownVisibility==="unknown"?"unknown":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel&&isMemberLikeNode(ctx.defNode))return{exported:!1,visibility:ownVisibility==="unknown"?"public":ownVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"};if(!ctx.isTopLevel&&CONTAINER_SCOPED_GRAMMARS.has(ctx.grammarId)&&TYPE_DECLARATION_NODE_TYPES.has(ctx.defNode.type)){let nestedVisibility=ownVisibility==="unknown"?containerScopedDefaultVisibility(ctx.grammarId,ctx.parentContainerType):ownVisibility;return{exported:!1,visibility:nestedVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:nestedVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel)return{...PRIVATE_INFO};switch(ctx.grammarId){case"typescript":case"javascript":case"tsx":return{...PRIVATE_INFO};case"python":return pythonVisibility(ctx);case"rust":return rustVisibility(ctx);case"go":return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};case"java":case"kotlin":case"csharp":case"swift":case"php":return modifierLanguageVisibility(ctx);case"cpp":return cppVisibility(ctx);case"dart":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"};case"ruby":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"module_public"};default:return{exported:!1,visibility:"unknown",exportedReason:"unknown",apiSurfaceKind:"unknown"}}}function pythonVisibility(ctx){if(ctx.pythonAllNames)return ctx.pythonAllNames.has(ctx.localName)?{exported:!0,visibility:"public",exportedReason:"module_public",apiSurfaceKind:"public"}:{...PRIVATE_INFO};return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"}}function rustVisibility(ctx){let text=ctx.defNode.text.trimStart();if(!/^pub\b|^pub\s*\(/.test(text))return{...PRIVATE_INFO};return{exported:!0,visibility:/^pub\s*\(\s*(crate|super|in\b)/.test(text)?"internal":"public",exportedReason:"modifier",apiSurfaceKind:"public"}}function modifierLanguageVisibility(ctx){if(ctx.grammarId==="php"&&ctx.localName.startsWith("_"))return{...PRIVATE_INFO};let visibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(visibility==="private")return{...PRIVATE_INFO};if(visibility==="unknown")return{exported:!0,visibility:ctx.grammarId==="java"?"package":defaultModuleVisibility(ctx.grammarId),exportedReason:"module_public",apiSurfaceKind:"public"};return{exported:!0,visibility,exportedReason:"modifier",apiSurfaceKind:"public"}}function cppVisibility(ctx){if(isInsideAnonymousNamespace(ctx.defNode))return{...PRIVATE_INFO};let text=ctx.defNode.text.trimStart();if(/^static\b/.test(text)||ctx.localName.startsWith("_"))return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"namespace_public",apiSurfaceKind:"public"}}function isInsideAnonymousNamespace(node){let current=node.parent;while(current){if(current.type==="namespace_definition"){if(!current.children.some((child)=>child!==null&&child.type==="namespace_identifier"))return!0}current=current.parent}return!1}function visibilityFromText(grammarId,text){let normalized=declarationPrefix(grammarId,text).trimStart();if(/\b(private|fileprivate)\b/.test(normalized))return"private";if(/\bprotected\b/.test(normalized))return"protected";if(/\binternal\b/.test(normalized))return"internal";if(/\b(public|open)\b/.test(normalized))return"public";if(grammarId==="rust"&&/^pub\s*\(\s*(crate|super|in\b)/.test(normalized))return"internal";if(grammarId==="rust"&&/^pub\b|^pub\s*\(/.test(normalized))return"public";return"unknown"}function endOfStringLiteral(text,quote){let q=text[quote],verbatim=q==='"'&&text[quote-1]==="@",i=quote+1;while(i<text.length){if(verbatim){if(text[i]===q){if(text[i+1]===q){i+=2;continue}return i}i++;continue}if(text[i]==="\\"){i+=2;continue}if(text[i]===q)return i;i++}return text.length}function skipBalanced(text,open7,ignoreQuotes=!1){let openCh=text[open7],closeCh=openCh==="("?")":"]",depth=0;for(let i=open7;i<text.length;i++){let ch=text[i];if(!ignoreQuotes&&(ch==='"'||ch==="'")){i=endOfStringLiteral(text,i);continue}if(ch===openCh)depth++;else if(ch===closeCh){if(depth--,depth===0)return i+1}}return-1}function skipBalancedResilient(text,open7){let strict=skipBalanced(text,open7);if(strict!==-1)return strict;return skipBalanced(text,open7,!0)}function stripLeadingAnnotations(text){let i=0;for(;;){while(i<text.length&&/\s/.test(text[i]))i++;let ch=text[i];if(ch==="/"&&text[i+1]==="*"){let end=text.indexOf("*/",i+2);if(end===-1)return"";i=end+2;continue}if(ch==="/"&&text[i+1]==="/"){let end=text.indexOf(`
|
|
3345
3345
|
`,i+2);if(end===-1)return"";i=end+1;continue}if(ch==="@"){let j=i+1;while(j<text.length&&/[\w.:]/.test(text[j]))j++;let k=j;while(k<text.length&&/\s/.test(text[k]))k++;if(text[k]==="("){let end=skipBalancedResilient(text,k);if(end===-1)return text.slice(i);i=end}else if(j===i+1)i=j;else i=j;continue}if(ch==="["){let end=skipBalancedResilient(text,i);if(end===-1)return text.slice(i);i=end;continue}return text.slice(i)}}function maskStringLiterals(text){let out="";for(let i=0;i<text.length;i++){let ch=text[i];if(ch!=='"'&&ch!=="'"){out+=ch;continue}let end=endOfStringLiteral(text,i);if(out+=ch,out+=" ".repeat(Math.max(0,Math.min(end,text.length)-i-1)),end<text.length)out+=text[end];i=end}return out}function declarationPrefix(grammarId,text){if(!ANNOTATED_DECLARATION_GRAMMARS.has(grammarId)){let bodyStart2=text.search(/[{\n]/);return bodyStart2===-1?text:text.slice(0,bodyStart2)}let stripped=stripLeadingAnnotations(text),window2=stripped.length>HEADER_SCAN_LIMIT?stripped.slice(0,HEADER_SCAN_LIMIT):stripped,scanned=maskStringLiterals(window2),bodyStart=scanned.search(/[{\n]/);return bodyStart===-1?scanned:scanned.slice(0,bodyStart)}function defaultModuleVisibility(grammarId){switch(grammarId){case"swift":case"csharp":return"internal";case"kotlin":return"public";case"php":return"public";default:return"public"}}function hasPrivateContainer(node,grammarId){let current=node.parent;while(current){if(isContainerNode(current)&&visibilityFromText(grammarId,current.text)==="private")return!0;current=current.parent}return!1}function isContainerNode(node){return/(?:class|struct|interface|object|protocol|namespace|module)/.test(node.type)||/^(?:enum|record)_declaration$/.test(node.type)}function isMemberLikeNode(node){return/(?:method|function)_declaration|function_definition/.test(node.type)}function isUppercasePublic(name){return/^[A-Z]/.test(name)}function isIdentifier(value){return/^[A-Za-z_$][\w$]*$/.test(value)}function maskCommentsAndStrings(source){let chars=[...source],i=0;while(i<chars.length){let ch=chars[i],next=chars[i+1];if(ch==="/"&&next==="/"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length&&chars[i]!==`
|
|
3346
3346
|
`)chars[i++]=" ";continue}if(ch==="/"&&next==="*"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length){let end=chars[i]==="*"&&chars[i+1]==="/";if(chars[i++]=" ",end){chars[i++]=" ";break}}continue}if(ch==='"'||ch==="'"||ch==="`"){let quote=ch;chars[i++]=" ";while(i<chars.length){if(chars[i]==="\\"){if(chars[i++]=" ",i<chars.length)chars[i++]=" ";continue}let done=chars[i]===quote;if(chars[i++]=" ",done)break}continue}i++}return chars.join("")}var PUBLIC_INFO,PRIVATE_INFO,CONTAINER_SCOPED_GRAMMARS,TYPE_DECLARATION_NODE_TYPES,ANNOTATED_DECLARATION_GRAMMARS,HEADER_SCAN_LIMIT=4096;var init_symbol_visibility=__esm(()=>{PUBLIC_INFO={exported:!0,visibility:"public",exportedReason:"top_level_public",apiSurfaceKind:"public"},PRIVATE_INFO={exported:!1,visibility:"private",exportedReason:"unknown",apiSurfaceKind:"private"},CONTAINER_SCOPED_GRAMMARS=new Set(["java","kotlin","csharp","swift","cpp"]),TYPE_DECLARATION_NODE_TYPES=new Set(["class_declaration","interface_declaration","enum_declaration","record_declaration","struct_declaration","object_declaration"]);ANNOTATED_DECLARATION_GRAMMARS=new Set(["java","kotlin","csharp","swift"])});async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES2[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS3)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),originalDefNode=asTs(defCap.node),defNode=originalDefNode,kind=Object.hasOwn(CAPTURE_KIND,kindKey)?CAPTURE_KIND[kindKey]:"function";if(grammarId==="python"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"class_definition"))kind="method";if(grammarId==="rust"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"impl_item"))kind="method";let parentContainerType;if(JVM_GRAMMARS.has(grammarId)){if(parentContainerType=nearestAncestorType(originalDefNode,JVM_CONTAINER_TYPES),parentContainerType!==void 0&&(kindKey==="func"||kindKey==="ctor"))kind="method"}if(grammarId==="cpp"||grammarId==="swift"){if(parentContainerType=nearestAncestorType(originalDefNode,NATIVE_CONTAINER_TYPES),parentContainerType!==void 0&&kindKey==="func")kind="method"}let explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isDefaultExportStatement(en)&&isOwnExportDeclaration(en,defNode));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}if(grammarId==="python"&&defNode.parent?.type==="decorated_definition")defNode=asTs(defNode.parent);let pythonParentClassExported=!1;if(grammarId==="python"&&kind==="method"){let current=originalDefNode.parent;while(current){if(current.type==="class_definition"){let classNameNode=current.children?.find((c)=>c!=null&&c.type==="identifier");if(classNameNode){let className=classNameNode.text;pythonParentClassExported=pythonAllNames?pythonAllNames.has(className):!className.startsWith("_")}break}current=current.parent}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames,pythonParentClassExported,parentContainerType});if(grammarId==="swift"&&kindKey==="extension")visibilityInfo={...visibilityInfo,exported:!1};let exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}augmentNativeDynamicDefs(grammarId,root.text,defs);let importsWithIndex=[],addImport=(entry,node)=>{if(!entry)return;for(let item of Array.isArray(entry)?entry:[entry]){let pythonExportedBindings=grammarId==="python"&&pythonAllNames&&item.bindings.length>0?item.bindings.filter((binding)=>pythonAllNames.has(binding.local)).map((binding)=>({imported:binding.imported,exported:binding.local})):[],normalizedItem=pythonExportedBindings.length>0?{...item,reExport:!0,exportedBindings:pythonExportedBindings}:item;importsWithIndex.push({index:node.startIndex,entry:normalizedItem.reExport?{...normalizedItem,startLine:node.startPosition.row+1,endLine:node.endPosition.row+1}:normalizedItem})}};for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let importNode=asTs(importCap.node),rawText=importNode.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let seenGoSpecifiers=new Set,specListNode=importNode.children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImportHardened(spec.text.trim());if(parsed)seenGoSpecifiers.add(parsed.specifier);addImport(parsed,asTs(spec))}}for(let parsed of parseGoBlockImports(rawText)){if(seenGoSpecifiers.has(parsed.specifier))continue;addImport(parsed,importNode)}}else{let parsed=parseImport(grammarId,rawText);addImport(parsed,importNode)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);addImport(parsed,asTs(callNode??reqSpec.node))}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");addImport({specifier:specText,importType:"commonjs",bindings:[]},asTs(reqName.node))}}}}if(isEsMGrammar(grammarId)||grammarId==="dart")for(let exportNode of exportNodes)addImport(parseImport(grammarId,exportNode.text.trim()),exportNode);for(let fallback of fallbackImportsForSource(grammarId,root.text))importsWithIndex.push(fallback);let seenImports=new Set,imports=importsWithIndex.sort((a,b)=>a.index-b.index).map((item)=>item.entry).filter((entry)=>{let key2=JSON.stringify([entry.specifier,entry.importType,entry.bindings,entry.reExport??!1,entry.exportedBindings??[]]);if(seenImports.has(key2))return!1;return seenImports.add(key2),!0}),topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[],refParamTypes=grammarId==="swift"?SWIFT_REF_PARAM_TYPES:PARAM_TYPES;for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,refParamTypes))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}if(isEsMGrammar(grammarId))for(let en of exportNodes){if(!isDefaultExportStatement(en))continue;let owner=en.childForFieldName?.("declaration")??en.childForFieldName?.("value");if(!owner)continue;if(defs.some((d)=>d.startLine===owner.startPosition.row+1&&d.name==="default"))continue;let kind=owner.type.includes("class")?"class":"function";defs.push({name:"default",kind,exported:!0,startLine:owner.startPosition.row+1,endLine:owner.endPosition.row+1})}return{defs:defs.map((def)=>({...def,endLine:Math.max(def.endLine,def.startLine)})),imports,refs}}function augmentNativeDynamicDefs(grammarId,source,defs){switch(grammarId){case"dart":augmentDartDefs(source,defs);return;case"ruby":augmentRubyDefs(source,defs);return;case"php":augmentPhpDefs(source,defs);return}}function upsertAugmentedDef(defs,def){let existing=defs.find((item)=>item.name===def.name&&item.startLine===def.startLine);if(existing){existing.kind=def.kind,existing.exported=def.exported,existing.visibilityInfo=def.visibilityInfo,existing.endLine=Math.max(existing.endLine,def.endLine);return}defs.push(def)}function symbolVisibilityInfo(visibility,exported,exportedReason){return{exported,visibility,exportedReason,apiSurfaceKind:exported?"public":"private"}}function addRegexDef(defs,source,name,kind,start,end,visibility,exported,exportedReason){upsertAugmentedDef(defs,{name,kind,exported,visibilityInfo:symbolVisibilityInfo(visibility,exported,exportedReason),startLine:lineNumberAt(source,start),endLine:lineNumberAt(source,end)})}function findMatchingBrace(source,openIndex){if(source[openIndex]!=="{")return null;let depth=0;for(let i=openIndex;i<source.length;i++){let ch=source[i];if(ch==="{")depth++;else if(ch==="}"){if(depth--,depth===0)return i}}return null}function lineNumberAt(text,index){let line=1;for(let i=0;i<index&&i<text.length;i++)if(text[i]===`
|
|
3347
3347
|
`)line++;return line}function advanceLineOffset(source,offset,lineLength){let after=offset+lineLength;if(source[after]==="\r"&&source[after+1]===`
|
|
@@ -3752,13 +3752,13 @@ Actionability (direct text only; required unless knowledge.promotion_require_act
|
|
|
3752
3752
|
`)}var init_recover=__esm(()=>{init_path_identity();init_snapshot_coordination_init();init_coder_settlement();init_stage_a_repair()});class CircuitBreaker{state="closed";failureCount=0;successCount=0;lastFailureTime;config;name;onStateChange;constructor(name,config3,onStateChange){this.name=name,this.config={failureThreshold:config3?.failureThreshold??5,resetTimeoutMs:config3?.resetTimeoutMs??30000,successThreshold:config3?.successThreshold??3,callTimeoutMs:config3?.callTimeoutMs??1e4},this.onStateChange=onStateChange}getState(){if(this.state==="open"&&this.lastFailureTime){if(Date.now()-this.lastFailureTime>=this.config.resetTimeoutMs)this.transitionTo("half-open")}return this.state}async execute(fn2){if(this.getState()==="open")throw Error(`Circuit breaker '${this.name}' is open`);let startTime=Date.now();try{let result=await this.executeWithTimeout(fn2),duration5=Date.now()-startTime;return this.recordSuccess(duration5),result}catch(error93){let duration5=Date.now()-startTime;throw this.recordFailure(error93,duration5),error93}}async executeWithTimeout(fn2){if(this.config.callTimeoutMs<=0)return fn2();return new Promise((resolve88,reject)=>{let timeout=setTimeout(()=>{reject(Error(`Call timeout after ${this.config.callTimeoutMs}ms`))},this.config.callTimeoutMs);fn2().then((result)=>{clearTimeout(timeout),resolve88(result)}).catch((error93)=>{clearTimeout(timeout),reject(error93)})})}recordSuccess(duration5){if(this.failureCount=0,this.state==="half-open"){if(this.successCount++,this.successCount>=this.config.successThreshold)this.transitionTo("closed")}this.onStateChange?.("callSuccess",{duration:duration5})}recordFailure(error93,duration5){if(this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half-open")this.transitionTo("open");else if(this.state==="closed"&&this.failureCount>=this.config.failureThreshold)this.transitionTo("open");this.onStateChange?.("callFailure",{error:error93,duration:duration5})}transitionTo(newState2){let oldState=this.state;if(this.state=newState2,newState2==="closed")this.failureCount=0,this.successCount=0,this.onStateChange?.("closed",{timestamp:Date.now(),successCount:0,oldState});else if(newState2==="open")this.successCount=0,this.onStateChange?.("opened",{timestamp:Date.now(),failureCount:this.failureCount,oldState});else if(newState2==="half-open")this.successCount=0,this.onStateChange?.("half-open",{timestamp:Date.now(),oldState})}reset(){this.transitionTo("closed")}getStats(){return{state:this.getState(),failureCount:this.failureCount,successCount:this.successCount,lastFailureTime:this.lastFailureTime}}}class LoopProtection{records=new Map;config;onLoopDetected;constructor(config3,onLoopDetected){this.config=config3,this.onLoopDetected=onLoopDetected}recordAttempt(key2){let operationKey=key2??this.config.operationKey,now2=Date.now(),record3=this.records.get(operationKey);if(record3&&now2-record3.firstAttempt>this.config.timeWindowMs)record3=void 0;if(!record3)return this.records.set(operationKey,{count:1,firstAttempt:now2,lastAttempt:now2}),!0;if(record3.count++,record3.lastAttempt=now2,record3.count>this.config.maxIterations)return this.onLoopDetected?.(operationKey,record3.count),!1;return!0}canProceed(key2){let operationKey=key2??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return!0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return!0;return record3.count<=this.config.maxIterations}getRemainingIterations(key2){let operationKey=key2??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return this.config.maxIterations;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return this.config.maxIterations;return Math.max(0,this.config.maxIterations-record3.count)}reset(key2){let operationKey=key2??this.config.operationKey;this.records.delete(operationKey)}resetAll(){this.records.clear()}getIterationCount(key2){let operationKey=key2??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return 0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return 0;return record3.count}getTrackedOperations(){return Array.from(this.records.keys())}}function comparePriority(a,b){let priorityOrder={critical:0,high:1,normal:2,low:3},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.createdAt-b.createdAt}class AutomationQueue{items=[];inflight=new Map;terminalIds=new Map;maxSize;defaultMaxRetries;defaultBackoffMs;maxBackoffMs;eventBus;overflowStrategy;itemCounter=0;constructor(config3){this.maxSize=config3?.maxSize??1000,this.defaultMaxRetries=config3?.defaultMaxRetries??3,this.defaultBackoffMs=config3?.defaultBackoffMs??1000,this.maxBackoffMs=config3?.maxBackoffMs??60000,this.overflowStrategy=config3?.overflowStrategy??"throw",this.eventBus=getGlobalEventBus()}generateId(){return`queue-${Date.now()}-${++this.itemCounter}`}enqueue(payload,priority="normal",metadata){if(this.items.length>=this.maxSize)if(this.overflowStrategy==="evict-oldest"){let oldestIdx=0;for(let i=1;i<this.items.length;i++)if(this.items[i].createdAt<this.items[oldestIdx].createdAt)oldestIdx=i;let[evicted]=this.items.splice(oldestIdx,1);if(evicted)this.eventBus.publish("queue.item.evicted",{itemId:evicted.id})}else throw Error(`Queue is full (max ${this.maxSize} items)`);let item={id:this.generateId(),priority,payload,createdAt:Date.now(),metadata,retry:{attempts:0,maxAttempts:this.defaultMaxRetries,backoffMs:this.defaultBackoffMs,maxBackoffMs:this.maxBackoffMs}};return this.items.push(item),this.items.sort(comparePriority),this.eventBus.publish("queue.item.enqueued",{itemId:item.id,priority}),item.id}dequeue(){if(this.inflight.size>=this.maxSize)return;let now2=Date.now(),index=this.items.findIndex((item2)=>item2.retry?.nextAttemptAt===void 0||item2.retry.nextAttemptAt<=now2);if(index===-1)return;let[item]=this.items.splice(index,1);if(!item)return;return this.inflight.set(item.id,item),this.eventBus.publish("queue.item.dequeued",{itemId:item.id}),item}peek(){return this.items[0]}get(id){return this.items.find((item)=>item.id===id)??this.inflight.get(id)}inflightSize(){return this.inflight.size}removeQueuedOrInflight(id){let queuedIndex=this.items.findIndex((item)=>item.id===id);if(queuedIndex!==-1){let[removed]=this.items.splice(queuedIndex,1);return removed}let inflightItem=this.inflight.get(id);if(inflightItem)this.inflight.delete(id);return inflightItem}markTerminal(id,at){if(this.terminalIds.set(id,at),this.terminalIds.size>MAX_TERMINAL_IDS){let oldest=this.terminalIds.keys().next().value;if(oldest!==void 0)this.terminalIds.delete(oldest)}}remove(id){if(this.terminalIds.has(id))return!1;return this.removeQueuedOrInflight(id)!==void 0}complete(id){if(this.terminalIds.has(id))return!1;if(!this.removeQueuedOrInflight(id))return!1;return this.markTerminal(id,Date.now()),this.eventBus.publish("queue.item.completed",{itemId:id}),!0}retry(id,_error){if(this.terminalIds.has(id))return!1;let item=this.get(id);if(!item||!item.retry)return!1;if(item.retry.attempts++,item.retry.lastAttempt=Date.now(),item.retry.attempts>=item.retry.maxAttempts)return this.removeQueuedOrInflight(id),this.markTerminal(id,Date.now()),this.eventBus.publish("queue.item.failed",{itemId:id,attempts:item.retry.attempts}),!1;let backoff=Math.min(item.retry.backoffMs*2**(item.retry.attempts-1),item.retry.maxBackoffMs);if(item.retry.nextAttemptAt=Date.now()+backoff,this.inflight.delete(id),!this.items.some((queued)=>queued.id===id))this.items.push(item),this.items.sort(comparePriority);return this.eventBus.publish("queue.item.retry scheduled",{itemId:id,attempt:item.retry.attempts,nextAttemptAt:item.retry.nextAttemptAt,backoffMs:backoff}),!0}getRetryableItems(){let now2=Date.now();return this.items.filter((item)=>item.retry?.nextAttemptAt&&item.retry.nextAttemptAt<=now2)}size(){return this.items.length}isEmpty(){return this.items.length===0}isFull(){return this.items.length>=this.maxSize}clear(){for(let item of this.items)this.eventBus.publish("queue.item.evicted",{itemId:item.id});this.items=[];for(let item of this.inflight.values())this.eventBus.publish("queue.item.evicted",{itemId:item.id});this.inflight.clear()}getAll(){return[...this.items]}getByPriority(priority){return this.items.filter((item)=>item.priority===priority)}getStats(){return{size:this.items.length,maxSize:this.maxSize,byPriority:{critical:this.items.filter((i)=>i.priority==="critical").length,high:this.items.filter((i)=>i.priority==="high").length,normal:this.items.filter((i)=>i.priority==="normal").length,low:this.items.filter((i)=>i.priority==="low").length},retryable:this.getRetryableItems().length,inflight:this.inflight.size}}}var MAX_TERMINAL_IDS=2048;var init_queue=__esm(()=>{init_event_bus()});function sleep4(ms){return new Promise((resolve88)=>setTimeout(resolve88,ms))}class WorkerManager{workers=new Map;eventBus;constructor(){this.eventBus=getGlobalEventBus()}register(registration){if(this.workers.has(registration.name))throw Error(`Worker '${registration.name}' is already registered`);let worker={name:registration.name,handler:registration.handler,queue:registration.queue,concurrency:registration.concurrency??1,status:"idle",activeCount:0,processedCount:0,errorCount:0};if(this.workers.set(registration.name,worker),this.eventBus.publish("worker.started",{workerName:registration.name,concurrency:worker.concurrency}),registration.autoStart)this.start(registration.name)}unregister(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status==="running")this.stop(name);return this.workers.delete(name),!0}start(name){let worker=this.workers.get(name);if(!worker)throw Error(`Worker '${name}' is not registered`);if(worker.status==="running")return!1;return worker.status="running",this.startProcessingLoop(worker),this.eventBus.publish("worker.started",{workerName:name,concurrency:worker.concurrency}),!0}startProcessingLoop(worker){(async()=>{while(worker.status==="running"){if(worker.activeCount>=worker.concurrency){await sleep4(50);continue}let item=worker.queue.dequeue();if(!item){await sleep4(100);continue}worker.activeCount++,this.handleItem(worker,item).finally(()=>{worker.activeCount--})}})().catch((error93)=>{this.eventBus.publish("worker.error",{workerName:worker.name,itemId:"loop",error:error93})})}async handleItem(worker,item){try{let result=await worker.handler(item);if(result.success)worker.processedCount++,worker.queue.complete(item.id);else worker.errorCount++,worker.lastError=result.error,worker.queue.retry(item.id,result.error)}catch(error93){worker.errorCount++,worker.lastError=error93,this.eventBus.publish("worker.error",{workerName:worker.name,itemId:item.id,error:error93}),worker.queue.retry(item.id,error93)}}stop(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status!=="running")return!1;return worker.status="stopping",this.eventBus.publish("worker.stopped",{workerName:name,processedCount:worker.processedCount,errorCount:worker.errorCount}),worker.status="stopped",!0}startAll(){for(let[name,worker]of this.workers)if(worker.status==="idle"||worker.status==="stopped")this.start(name)}stopAll(){for(let name of this.workers.keys())this.stop(name)}getStatus(name){return this.workers.get(name)?.status}getStats(name){let worker=this.workers.get(name);if(!worker)return;return{status:worker.status,activeCount:worker.activeCount,processedCount:worker.processedCount,errorCount:worker.errorCount,lastError:worker.lastError,queueSize:worker.queue.size(),queueInflight:worker.queue.inflightSize()}}getWorkerNames(){return Array.from(this.workers.keys())}isAnyRunning(){for(let worker of this.workers.values())if(worker.status==="running")return!0;return!1}getTotalStats(){let stats2={};for(let name of this.workers.keys())stats2[name]=this.getStats(name);return stats2}}var init_worker=__esm(()=>{init_event_bus()});class BackgroundAutomationManager{config;eventBus;workerManager;queues=new Map;circuitBreakers=new Map;loopProtections=new Map;isInitialized=!1;isRunning=!1;constructor(config3){this.config={enabled:config3.enabled,maxQueueSize:config3.maxQueueSize??1000,maxRetries:config3.maxRetries??3,circuitBreaker:config3.circuitBreaker,loopProtection:config3.loopProtection},this.eventBus=getGlobalEventBus(),this.workerManager=new WorkerManager}initialize(){if(!this.config.enabled){log("[Automation] Framework disabled, skipping initialization");return}if(this.isInitialized){log("[Automation] Already initialized");return}log("[Automation] Initializing framework..."),this.isInitialized=!0,this.eventBus.publish("automation.started",{config:this.config})}start(){if(!this.config.enabled||!this.isInitialized)return;if(this.isRunning)return;log("[Automation] Starting framework..."),this.isRunning=!0,this.eventBus.publish("automation.started",{timestamp:Date.now()})}stop(){if(!this.isRunning)return;log("[Automation] Stopping framework..."),this.workerManager.stopAll(),this.isRunning=!1,this.eventBus.publish("automation.stopped",{timestamp:Date.now()})}isEnabled(){return this.config.enabled}isActive(){return this.isRunning}getOrCreateQueue(name){if(!this.queues.has(name)){let queue=new AutomationQueue({maxSize:this.config.maxQueueSize,defaultMaxRetries:this.config.maxRetries});this.queues.set(name,queue)}return this.queues.get(name)}registerWorker(registration){if(!this.config.enabled)throw Error("Cannot register worker: automation framework is disabled");this.workerManager.register(registration)}startWorker(name){if(!this.config.enabled)return!1;return this.workerManager.start(name)}stopWorker(name){if(!this.config.enabled)return!1;return this.workerManager.stop(name)}getOrCreateCircuitBreaker(name){if(!this.circuitBreakers.has(name)){let cb=new CircuitBreaker(name,this.config.circuitBreaker,(eventType,event)=>{log(`[CircuitBreaker] ${name}: ${eventType}`,event),this.eventBus.publish("circuit.breaker.opened",{breakerName:name,eventType,event})});this.circuitBreakers.set(name,cb)}return this.circuitBreakers.get(name)}getOrCreateLoopProtection(operationKey){if(!this.loopProtections.has(operationKey)){let config3={maxIterations:this.config.loopProtection?.maxIterations??10,timeWindowMs:this.config.loopProtection?.timeWindowMs??60000,operationKey},lp=new LoopProtection(config3,(key2,count)=>{log(`[LoopProtection] ${key2}: Detected potential loop (${count} iterations)`),this.eventBus.publish("loop.protection.triggered",{operationKey:key2,count,timestamp:Date.now()})});this.loopProtections.set(operationKey,lp)}return this.loopProtections.get(operationKey)}subscribe(type,listener){return this.eventBus.subscribe(type,listener)}async publish(type,payload,source){await this.eventBus.publish(type,payload,source)}getStats(){return{enabled:this.config.enabled,initialized:this.isInitialized,running:this.isRunning,queues:Object.fromEntries(Array.from(this.queues.entries()).map(([name,queue])=>[name,queue.getStats()])),workers:this.workerManager.getTotalStats(),circuitBreakers:Object.fromEntries(Array.from(this.circuitBreakers.entries()).map(([name,cb])=>[name,cb.getStats()])),loopProtections:Array.from(this.loopProtections.keys())}}reset(){this.stop(),this.workerManager.stopAll(),this.queues.clear(),this.circuitBreakers.clear(),this.loopProtections.clear(),this.isInitialized=!1}}function createAutomationManager(automationConfig){let config3={enabled:automationConfig?.mode!=="manual",maxQueueSize:500,maxRetries:3,circuitBreaker:{failureThreshold:5,resetTimeoutMs:30000,successThreshold:2,callTimeoutMs:15000},loopProtection:{maxIterations:10,timeWindowMs:60000}},manager=new BackgroundAutomationManager(config3);return manager.initialize(),manager}function resetAutomationManager(){if(managerInstance)managerInstance.reset(),managerInstance=null}var managerInstance=null;var init_manager4=__esm(()=>{init_utils();init_event_bus();init_queue();init_worker()});import*as fs118 from"node:fs";import*as path216 from"node:path";function backupSwarmStateBeforeReset(directory,kind,relEntries){let warnings=[],copied=[],swarmDir=path216.join(directory,".swarm");try{let stat21=fs118.lstatSync(swarmDir);if(stat21.isSymbolicLink()||!stat21.isDirectory())return{backupDir:null,copied,warnings}}catch{return{backupDir:null,copied,warnings}}let timestamp=new Date().toISOString().replace(/[:.]/g,"-"),backupsRoot=path216.join(swarmDir,"reset-backups"),backupDir=path216.join(backupsRoot,`${kind}-${timestamp}`),backupDirCreated=!1,ensureBackupDir=()=>{if(!backupDirCreated)fs118.mkdirSync(backupDir,{recursive:!0}),backupDirCreated=!0};for(let rel of relEntries){let src;try{src=validateSwarmPath(directory,rel)}catch{warnings.push(`skipped backup of ${rel} (path validation failed)`);continue}if(!fs118.existsSync(src))continue;try{ensureBackupDir();let dest=path216.join(backupDir,rel);fs118.mkdirSync(path216.dirname(dest),{recursive:!0}),fs118.cpSync(src,dest,{recursive:!0}),copied.push(rel)}catch(err){warnings.push(`failed to back up ${rel}: ${err instanceof Error?err.message:String(err)}`)}}if(copied.length===0){if(backupDirCreated)try{fs118.rmSync(backupDir,{recursive:!0,force:!0})}catch{}return{backupDir:null,copied,warnings}}return pruneOldResetBackups(backupsRoot,warnings),{backupDir,copied,warnings}}function pruneOldResetBackups(backupsRoot,warnings){try{let entries2=fs118.readdirSync(backupsRoot,{withFileTypes:!0}).filter((e)=>e.isDirectory()).map((e)=>e.name).sort().reverse();for(let stale of entries2.slice(RESET_BACKUP_RETENTION))try{fs118.rmSync(path216.join(backupsRoot,stale),{recursive:!0,force:!0})}catch(err){warnings.push(`failed to prune old backup ${stale}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){warnings.push(`failed to prune old reset backups: ${err instanceof Error?err.message:String(err)}`)}}var RESET_BACKUP_RETENTION=5;var init_reset_backup=__esm(()=>{init_utils2()});import*as fs119 from"node:fs";import*as path217 from"node:path";async function handleResetCommand(directory,args2){if(!args2.includes("--confirm"))return["## Swarm Reset","","⚠️ This will delete all swarm state from .swarm/ (plan, context, checkpoints, SWARM_PLAN artifacts including .swarm/plan-export/)","","A timestamped backup of the deleted state is saved to `.swarm/reset-backups/` automatically (restore by copying files back). Run `/swarm export` first if you also want a portable JSON snapshot.","","To confirm, run: `/swarm reset --confirm`"].join(`
|
|
3753
3753
|
`);let filesToReset=["plan.md","plan.json","context.md","spec.md","spec-staleness.json","spec-snapshot.md","SWARM_PLAN.md","SWARM_PLAN.json","plan-export/SWARM_PLAN.md","plan-export/SWARM_PLAN.json","checkpoints.json","events.jsonl","events-authority-index.json","run-memory.jsonl","reproduction.json","issue-publication.json","recurrence-sweep.json","implementation-review.json"],results=[];try{let backup=_internals175.backupSwarmStateBeforeReset(directory,"reset",["plan-ledger.jsonl",...filesToReset,"summaries"]);if(backup.backupDir&&backup.copied.length>0){let rel=path217.relative(directory,backup.backupDir);results.push(`- \uD83D\uDCE6 Backed up ${backup.copied.length} item(s) to ${rel}/ (restore by copying files back into .swarm/)`)}for(let w of backup.warnings)results.push(`- ⚠️ Backup warning: ${w}`)}catch(err){results.push(`- ⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}try{await _internals175.withPlanLifecycleLock(directory,"reset-plan-lifecycle",async()=>{let criticalProjectionNames=new Set(["plan.md","plan.json"]),criticalProjectionBytes=new Map;for(let filename of criticalProjectionNames){let resolvedPath=validateSwarmPath(directory,filename);if(_internals175.existsSync(resolvedPath))criticalProjectionBytes.set(filename,_internals175.readFileSync(resolvedPath))}try{for(let filename of criticalProjectionNames){let resolvedPath=validateSwarmPath(directory,filename);if(_internals175.existsSync(resolvedPath))_internals175.unlinkSync(resolvedPath)}await _internals175.clearPlanLedgerForReset(directory)}catch(error93){let compensationFailures=[];for(let[filename,bytes]of criticalProjectionBytes)try{_internals175.writeFileSync(validateSwarmPath(directory,filename),bytes)}catch(restoreError){compensationFailures.push(`${filename}: ${restoreError instanceof Error?restoreError.message:String(restoreError)}`)}if(compensationFailures.length>0)results.push(`- ❌ Compensation failed: ${compensationFailures.join("; ")}`);throw error93}results.push("- ✅ Cleared authoritative plan ledger");for(let filename of criticalProjectionNames)results.push(criticalProjectionBytes.has(filename)?`- ✅ Deleted ${filename}`:`- ⏭️ ${filename} not found (skipped)`);for(let filename of filesToReset){if(criticalProjectionNames.has(filename))continue;try{let resolvedPath=validateSwarmPath(directory,filename);if(_internals175.existsSync(resolvedPath))_internals175.unlinkSync(resolvedPath),results.push(`- ✅ Deleted ${filename}`);else results.push(`- ⏭️ ${filename} not found (skipped)`)}catch{results.push(`- ❌ Failed to delete ${filename}`)}}})}catch(err){return results.push(`- ❌ Failed to clear authoritative plan ledger: ${err instanceof Error?err.message:String(err)}`),["## Swarm Reset Aborted","",...results,"","The reset could not complete safely. Any deleted critical projections were restored best-effort and the authoritative ledger was preserved whenever projection cleanup failed. Resolve the reported filesystem or ledger error and retry /swarm reset --confirm."].join(`
|
|
3754
3754
|
`)}for(let filename of["SWARM_PLAN.md","SWARM_PLAN.json"])try{let rootPath=path217.join(directory,filename);if(_internals175.existsSync(rootPath))_internals175.unlinkSync(rootPath),results.push(`- ✅ Deleted ${filename} (root)`)}catch(err){results.push(`- ❌ Failed to delete ${filename}: ${err instanceof Error?err.message:String(err)}`)}try{resetAutomationManager(),results.push("- ✅ Stopped background automation (in-memory queues cleared)")}catch{results.push("- ⏭️ Background automation not running (skipped)")}try{let summariesPath=validateSwarmPath(directory,"summaries");if(_internals175.existsSync(summariesPath))_internals175.rmSync(summariesPath,{recursive:!0,force:!0}),results.push("- ✅ Deleted summaries/ directory");else results.push("- ⏭️ summaries/ not found (skipped)")}catch{results.push("- ❌ Failed to delete summaries/")}return["## Swarm Reset Complete","",...results,"","Swarm state has been cleared. Start fresh with a new plan."].join(`
|
|
3755
|
-
`)}var _internals175;var init_reset=__esm(()=>{init_manager4();init_utils2();init_ledger();init_manager();init_reset_backup();_internals175={backupSwarmStateBeforeReset,clearPlanLedgerForReset,withPlanLifecycleLock,existsSync:fs119.existsSync,readFileSync:fs119.readFileSync,unlinkSync:fs119.unlinkSync,writeFileSync:fs119.writeFileSync,rmSync:fs119.rmSync}});import*as fs120 from"node:fs";import*as path218 from"node:path";function resolveWorktreeRepoOwnership(worktreePath,expectedProjectRoot){let io={failed:!1},gitDir=readLinkedWorktreeGitDir(worktreePath,io);if(io.failed||!gitDir)return{owned:!1,uncertain:io.failed};let mainWorktree=resolveMainWorktree(gitDir,io);if(io.failed||!mainWorktree)return{owned:!1,uncertain:!0};let cmp=process.platform==="win32"?(a,b)=>a.toLowerCase()===b.toLowerCase():(a,b)=>a===b,canonical=(p)=>{try{return fs120.realpathSync(p)}catch{return p}},mainReal=path218.resolve(canonical(mainWorktree)),rootReal=path218.resolve(canonical(expectedProjectRoot)),mainLex=path218.resolve(mainWorktree),rootLex=path218.resolve(expectedProjectRoot);if(cmp(mainReal,rootReal)||cmp(mainLex,rootLex)||cmp(mainReal,rootLex)||cmp(mainLex,rootReal))return{owned:!0,mainWorktree,uncertain:!1};let statOf=(p)=>{try{let st=fs120.statSync(p,{bigint:!0});return{dev:st.dev,ino:st.ino}}catch{return}},mainStat=statOf(mainWorktree),rootStat=statOf(expectedProjectRoot);return{owned:mainStat!==void 0&&rootStat!==void 0&&mainStat.dev>0n&&mainStat.ino>0n&&mainStat.dev===rootStat.dev&&mainStat.ino===rootStat.ino,mainWorktree,uncertain:!1}}function sleepSync4(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{}}function remember(key2,displayPath,value,io){if(!io.failed)return cache5(key2,value);try{_internals176.addDeferredWarning(`[swarm] Could not read git metadata for ${displayPath} after ${MAX_DETECTION_ATTEMPTS} attempts; worktree-lane permission scoping was skipped for it. If this directory IS a swarm lane, external-directory prompts raised there cannot be answered and the lane may hang. Check filesystem permissions and open-file limits, then restart the session.`)}catch{}return null}function cache5(key2,value){if(laneContextCache.size>=MAX_CACHED_DIRECTORIES){let oldest=laneContextCache.keys().next();if(!oldest.done)laneContextCache.delete(oldest.value)}return laneContextCache.set(key2,value),value}function isSwarmOwnedBranch(gitDir,io){let head2;try{head2=_internals176.readFileSync(path218.join(gitDir,"HEAD"),"utf-8")}catch(err){if(err?.code!=="ENOENT")io.failed=!0;return!1}let branch=/^\s*ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head2)?.[1];if(!branch)return!1;return matchSwarmLaneBranch(branch)!==void 0}function readLinkedWorktreeGitDir(directory,io){let dotGit=path218.join(directory,".git"),stat21;try{stat21=_internals176.statSync(dotGit)}catch(err){if(err?.code!=="ENOENT")io.failed=!0;return}if(!stat21.isFile())return;let contents;try{contents=_internals176.readFileSync(dotGit,"utf-8")}catch(err){if(err?.code!=="ENOENT")io.failed=!0;return}let pointer=/^\s*gitdir:\s*(.+?)\s*$/m.exec(contents)?.[1];if(!pointer)return;return path218.resolve(directory,pointer)}function resolveMainWorktree(gitDir,io){let commonDir;try{let trimmed=_internals176.readFileSync(path218.join(gitDir,"commondir"),"utf-8").trim();if(trimmed)commonDir=path218.resolve(gitDir,trimmed)}catch(err){if(err?.code!=="ENOENT")io.failed=!0}if(commonDir){let parent2=path218.dirname(commonDir);return parent2&&parent2!==commonDir?parent2:void 0}let worktreesDir=path218.dirname(gitDir);if(path218.basename(worktreesDir)!=="worktrees")return;let sharedGitDir=path218.dirname(worktreesDir);if(path218.basename(sharedGitDir)!==".git")return;let parent=path218.dirname(sharedGitDir);return parent&&parent!==sharedGitDir?parent:void 0}function resolveLaneContext(directory){if(typeof directory!=="string"||directory.trim()==="")return null;let resolved;try{resolved=path218.resolve(directory)}catch{return null}let key2=canonicalRootKeyFresh(resolved),cached3=laneContextCache.get(key2);if(cached3!==void 0)return cached3;let io={failed:!1},result=null;for(let attempt=1;attempt<=MAX_DETECTION_ATTEMPTS;attempt+=1){if(io={failed:!1},result=attemptDetection(resolved,io),result!==null||!io.failed)break;if(attempt<MAX_DETECTION_ATTEMPTS)sleepSync4(DETECTION_RETRY_BACKOFF_MS)}if(result!==null)return cache5(key2,result);return remember(key2,resolved,null,io)}function attemptDetection(resolved,io){try{let laneRoot,gitDir,current=resolved;for(let depth=0;depth<MAX_ANCESTOR_WALK_DEPTH;depth+=1){let candidate=readLinkedWorktreeGitDir(current,io);if(candidate){laneRoot=current,gitDir=candidate;break}let parent=path218.dirname(current);if(parent===current)break;current=parent}if(!laneRoot||!gitDir)return null;if(!(isSwarmOwnedBranch(gitDir,io)||matchSwarmLanePath(laneRoot)!==void 0))return null;let parentProjectPath=resolveMainWorktree(gitDir,io);if(!parentProjectPath)return null;if(sameProjectRoot(parentProjectPath,laneRoot))return null;return{lanePath:laneRoot,parentProjectPath:path218.resolve(parentProjectPath)}}catch{return io.failed=!0,null}}var MAX_CACHED_DIRECTORIES=256,laneContextCache,_internals176,MAX_ANCESTOR_WALK_DEPTH=40,MAX_DETECTION_ATTEMPTS=3,DETECTION_RETRY_BACKOFF_MS=5;var init_lane_context=__esm(()=>{init_warning_buffer();init_canonical_root();init_swarm_branch();laneContextCache=new Map;_internals176={readFileSync:fs120.readFileSync,statSync:fs120.statSync,addDeferredWarning,clearCache:()=>{laneContextCache.clear()}}});import*as fs121 from"node:fs";import*as path219 from"node:path";function listLegacyLanes(legacyBase){let lanes=[],sessions;try{sessions=_internals177.readdirSync(legacyBase,{withFileTypes:!0})}catch{return lanes}for(let session of sessions){if(!session.isDirectory())continue;let laneEntries;try{laneEntries=_internals177.readdirSync(path219.join(legacyBase,session.name),{withFileTypes:!0})}catch{continue}for(let lane of laneEntries){if(!lane.isDirectory())continue;lanes.push({lanePath:path219.join(legacyBase,session.name,lane.name),sessionId:session.name})}}return lanes}async function gitWorktreeMove(projectRoot,from,to){let proc;try{proc=_internals177.bunSpawn([_internals177.resolveGitExecutable(),"-C",projectRoot,"worktree","move",from,to],{cwd:projectRoot,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:GIT_MOVE_TIMEOUT_MS,killProcessTree:!0});let code=await proc.exited;if(code===0)return;return(proc.stderr?await proc.stderr.text().catch(()=>""):"").trim()||`git worktree move exited ${code}`}catch(error93){return error93 instanceof Error?error93.message:String(error93)}finally{try{proc?.kill?.()}catch{}}}function isLive(entry,liveOwners){let canonical=canonicalRootKeyFresh(entry.lanePath);return liveOwners.some((owner)=>owner.lanePath===entry.lanePath||canonicalRootKeyFresh(owner.lanePath)===canonical)}async function migrateLegacyWorktreeBase(directory,liveOwners){let result={attempted:!1,legacyBaseExists:!1,moved:[],retained:[],legacyBaseRemoved:!1},legacyBase=path219.resolve(path219.dirname(directory),SWARM_WORKTREE_DIR_NAME);if(result.legacyBaseExists=_internals177.existsSync(legacyBase),!result.legacyBaseExists)return result;result.attempted=!0;let newBase=resolveWorktreeBaseDir(directory),lanes=listLegacyLanes(legacyBase),movedCount=0;for(let lane of lanes){let dotGit=path219.join(lane.lanePath,".git");if(!_internals177.existsSync(dotGit)){result.retained.push({lanePath:lane.lanePath,reason:"gitless legacy remnant (ownership unprovable)"});continue}let ownership=_internals177.resolveWorktreeRepoOwnership(lane.lanePath,directory);if(!ownership.owned||ownership.uncertain){result.retained.push({lanePath:lane.lanePath,reason:ownership.uncertain?"ownership uncertain":"owned by a different repository"});continue}if(isLive(lane,liveOwners)){result.retained.push({lanePath:lane.lanePath,reason:"live lane (owner process running) — migrates after its dispatch ends"});continue}if(movedCount>=MAX_MIGRATIONS_PER_PASS){result.retained.push({lanePath:lane.lanePath,reason:"per-pass migration cap reached — next start continues"});continue}let target=path219.join(newBase,lane.sessionId,path219.basename(lane.lanePath));try{_internals177.mkdirSync(path219.dirname(target),{recursive:!0})}catch(error93){result.retained.push({lanePath:lane.lanePath,reason:`target mkdir failed: ${error93 instanceof Error?error93.message:String(error93)}`});continue}let moveError=await gitWorktreeMove(directory,lane.lanePath,target);if(moveError){result.retained.push({lanePath:lane.lanePath,reason:moveError});continue}try{_internals177.rmdirSync(path219.dirname(lane.lanePath))}catch{}result.moved.push(target),movedCount++}try{_internals177.rmdirSync(legacyBase),result.legacyBaseRemoved=!0}catch{}if(result.retained.length>0)log(`[base-migration] ${result.retained.length} legacy-base entr${result.retained.length===1?"y":"ies"} left for their owning checkouts (${result.retained[0]?.reason})`);return result}var GIT_MOVE_TIMEOUT_MS=1e4,MAX_MIGRATIONS_PER_PASS=16,_internals177;var init_base_migration=__esm(()=>{init_constants();init_lane_context();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();_internals177={resolveWorktreeRepoOwnership,bunSpawn,resolveGitExecutable,readdirSync:fs121.readdirSync.bind(fs121),existsSync:fs121.existsSync.bind(fs121),mkdirSync:fs121.mkdirSync.bind(fs121),rmdirSync:fs121.rmdirSync.bind(fs121),realpathSync:fs121.realpathSync.bind(fs121)}});import*as fs122 from"node:fs";import*as path220 from"node:path";function probeGitMarker(dotGitPath){try{return _internals178.statSync(dotGitPath),"present"}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return"gitless";return"uncertain"}}async function removeOwnedWorktreeDir(worktreePath,projectRoot){let marker=probeGitMarker(path220.join(worktreePath,".git"));if(marker==="uncertain")return{status:"skipped",reason:"ownership uncertain (unreadable .git marker)"};if(marker==="gitless"){if(!_internals178.isPathUnderSwarmWorktreeBase(worktreePath,projectRoot))return{status:"skipped",reason:"gitless directory outside the project worktree base (ownership unprovable)"};try{return _internals178.rmSync(worktreePath,{recursive:!0,force:!0}),{status:"removed"}}catch(error93){return{status:"skipped",reason:`gitless internal remnant removal failed: ${error93 instanceof Error?error93.message:String(error93)}`}}}let ownership=_internals178.resolveWorktreeRepoOwnership(worktreePath,projectRoot);if(!ownership.owned||ownership.uncertain)return{status:"skipped",reason:ownership.uncertain?"ownership uncertain (unreadable .git pointer)":"owned by a different repository"};let result=await _internals178.removeWorktree(worktreePath,projectRoot);if("error"in result)return{status:"refused",reason:result.error};return{status:"removed"}}var _internals178;var init_ownership=__esm(()=>{init_lane_context();init_core3();_internals178={resolveWorktreeRepoOwnership,isPathUnderSwarmWorktreeBase,removeWorktree,rmSync:fs122.rmSync.bind(fs122),statSync:fs122.statSync.bind(fs122)}});import*as fs123 from"node:fs";import*as fsPromises9 from"node:fs/promises";import*as path221 from"node:path";async function listOwnershipTagSessionIds(directory){let scan=await scanBackgroundWorktreeOwnershipTagsForRecovery(directory);if(scan.status==="uncertain")return scan;return{status:"ok",sessionIds:[...new Set(scan.owners.map((owner)=>owner.sessionId))]}}async function writeAdvisoryFile(directory,cleanupResult,warnings,attempted,removedWorktrees=[]){let advisoryPath=path221.join(directory,".swarm","advisories","init-orphan-recovery.json"),advisory={initTimestamp:new Date().toISOString(),warnings,errors:cleanupResult.errors,reclaimed:{removedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:attempted},...cleanupResult.skippedRecoveryBranches&&cleanupResult.skippedRecoveryBranches.length>0?{preservedRecoveryBranches:cleanupResult.skippedRecoveryBranches}:{},...cleanupResult.recoveryReadError?{recoveryReadError:!0,note:"skipped all lane-branch deletions this pass because .swarm/recovery/ was unreadable (fail-safe)"}:{}};try{await fsPromises9.mkdir(path221.dirname(advisoryPath),{recursive:!0}),await fsPromises9.writeFile(advisoryPath,JSON.stringify(advisory,null,2),"utf-8")}catch{log("initOrphanRecovery advisory file write failed (non-fatal)")}}function resolveWorktreeEnumerationBases(directory){let bases=[resolveWorktreeBaseDir(directory)];try{let config3=loadPluginConfig(directory),overrides2=[config3?.worktree?.worktree_dir,config3?.turbo?.lean?.worktree_dir].filter((value)=>typeof value==="string");for(let override of overrides2){let base=resolveWorktreeBaseDir(directory,override);if(!bases.some((existing)=>existing===base))bases.push(base)}}catch{}return bases}async function enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths=new Set){let orphanedDirs=[];for(let worktreeRoot of resolveWorktreeEnumerationBases(directory)){let entries2;try{entries2=await fsPromises9.readdir(worktreeRoot,{withFileTypes:!0})}catch{continue}for(let entry of entries2){if(!entry.isDirectory())continue;let sessionId=entry.name;if(activeSessionIds.includes(sessionId))continue;let sessionEntries;try{sessionEntries=await fsPromises9.readdir(path221.join(worktreeRoot,sessionId),{withFileTypes:!0})}catch{continue}for(let laneEntry of sessionEntries){if(!laneEntry.isDirectory())continue;let worktreePath=path221.join(worktreeRoot,sessionId,laneEntry.name);if(protectedWorktreePaths.has(canonicalRootKeyFresh(worktreePath)))continue;orphanedDirs.push(worktreePath)}}}return orphanedDirs}async function isCrossProcessLockHeld(directory){if(_internals179.isLocked(directory,ORPHAN_RECOVERY_LOCK_FILE))return!0;if(_internals179.listActiveLocks(directory).length>0)return!0;return!1}async function crossProcessAdvisoryResult(directory,warning){let result={attempted:!0,crossProcessLockHeld:!0,warnings:[warning],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1};return await writeAdvisoryFile(directory,{removed:[],skipped:[],errors:[]},result.warnings,!1,[]),result}function worktreePathKey(worktreePath,directory){let absolutePath2=path221.isAbsolute(worktreePath)?worktreePath:path221.resolve(directory,worktreePath);return canonicalRootKeyFresh(absolutePath2)}async function runInitOrphanRecovery(directory){let result,recoveryLockRelease,recoveryReplayWarnings=[];try{if(await isCrossProcessLockHeld(directory))return crossProcessAdvisoryResult(directory,"Cross-process lock held — another opencode process may be active. "+"Skipping destructive cleanup to preserve its worktrees/branches. Run '/swarm status' or check '.swarm/locks/' to identify active processes.");let lockAcquireResult=await _internals179.tryAcquireLock(directory,ORPHAN_RECOVERY_LOCK_FILE,"init-orphan-recovery","init");if(!lockAcquireResult.acquired)return crossProcessAdvisoryResult(directory,"Cross-process lifecycle lock was acquired by another process during init; skipping destructive cleanup to preserve its worktrees/branches.");recoveryLockRelease=lockAcquireResult.lock._release;let activeSessionIds=Array.from(swarmState.agentSessions.keys()),replayedClaims=_internals179.replayWorktreeRecoveryClaimJournal(directory),uncertainReplay=replayedClaims.find((entry)=>entry.outcome==="uncertain_committed_without_authority");if(uncertainReplay)throw _internals179.recordDelegationRecoveryObservation(directory,{source:"unknown",ok:!1,reason:`worktree recovery replay is uncertain for authority ${uncertainReplay.authorityDigest}: committed claim is missing its authoritative record`}),Error(`worktree recovery replay is uncertain for authority ${uncertainReplay.authorityDigest}; destructive orphan cleanup skipped`);let replayRepairs=replayedClaims.filter((entry)=>entry.outcome==="aborted_prepared_claim"||entry.outcome==="removed_uncommitted_credential"||entry.outcome==="released_orphaned_committed_claim");if(replayRepairs.length>0)recoveryReplayWarnings.push(`Recovered ${replayRepairs.length} interrupted worktree recovery claim${replayRepairs.length===1?"":"s"} during startup replay before orphan cleanup.`);let recoveryAuthorityScan=_internals179.scanWorktreeRecoveryAuthoritiesForRecovery(directory);if(recoveryAuthorityScan.status!=="ok")throw _internals179.recordDelegationRecoveryObservation(directory,{source:"unknown",ok:!1,reason:`worktree recovery authority state is uncertain: ${recoveryAuthorityScan.reason}`}),Error(`worktree recovery authority state is uncertain; destructive orphan cleanup skipped: ${recoveryAuthorityScan.reason}`);let liveRecoveryAuthorities=recoveryAuthorityScan.authorities.filter((authority)=>authority.status!=="finalized");for(let authority of liveRecoveryAuthorities){for(let sessionId of[authority.immutable.parentSessionId,authority.claim?.claimantSessionId,authority.claim?.childSessionId])if(sessionId&&!activeSessionIds.includes(sessionId))activeSessionIds.push(sessionId);if(authority.status==="claimed"&&authority.claim&&!swarmState.agentSessions.has(authority.claim.childSessionId))recoveryReplayWarnings.push(`Preserved claimed recovery lane "${authority.immutable.laneBranch}" for task ${authority.immutable.taskId}; restart reconciliation may still need to resume prompt delivery for child session ${authority.claim.childSessionId}.`)}let provisioningOwnerScan=await withTimeout(Promise.resolve(_internals179.scanWorktreeProvisioningOwnersForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree provisioning ownership scan exceeded its bounded init budget"));if(provisioningOwnerScan.status==="uncertain")throw Error(`worktree provisioning ownership state is uncertain; destructive orphan cleanup skipped: ${provisioningOwnerScan.reason}`);let provisioningLifecycleScan=_internals179.scanWorktreeProvisioningLifecycleJournalForRecovery(directory);if(provisioningLifecycleScan.status==="uncertain")throw Error(`worktree provisioning lifecycle state is uncertain; destructive orphan cleanup skipped: ${provisioningLifecycleScan.reason}`);let latestLifecycleByCall=new Map(provisioningLifecycleScan.entries.map((entry)=>[entry.callID,entry]));for(let owner of provisioningOwnerScan.owners){if(owner.schemaVersion!==3)continue;let lifecycle=latestLifecycleByCall.get(owner.callID);if(!lifecycle||lifecycle.state!=="OWNER_PUBLISHED"||lifecycle.parentSessionId!==owner.parentSessionId||lifecycle.worktreeSessionId!==owner.worktreeSessionId||lifecycle.taskId!==owner.taskId||lifecycle.reservationId!==owner.reservationId||lifecycle.generation!==owner.generation||lifecycle.branchName!==owner.branchName)throw Error(`worktree provisioning owner ${owner.callID} is not corroborated by its exact lifecycle journal entry; destructive orphan cleanup skipped`)}let registeredWorktrees=provisioningOwnerScan.owners.length===0?{status:"ok",liveBranches:[]}:await withTimeout(_internals179.scanRegisteredWorktreeLiveness(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("registered worktree liveness scan exceeded its bounded init budget"));if(registeredWorktrees.status==="uncertain")throw Error(`registered worktree liveness is uncertain; destructive orphan cleanup skipped: ${registeredWorktrees.reason}`);let liveBranches=new Set(registeredWorktrees.liveBranches),now2=Date.now();for(let owner of provisioningOwnerScan.owners){let leaseIsLive=now2-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS,sessionIds=new Set([owner.parentSessionId,owner.worktreeSessionId]),branchIsLive=owner.schemaVersion===2?[...sessionIds].some((sessionId)=>liveBranches.has(`swarm/lane/${sessionId}/${owner.taskId}`)||liveBranches.has(`swarm-lane/${sessionId}/${owner.taskId}`)):[...liveBranches].some((branch)=>{let segments=branch.split("/"),sessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;return sessionId!==void 0&&sessionIds.has(sessionId)});if(!leaseIsLive&&!branchIsLive){if(!_internals179.removeWorktreeProvisioningOwner(directory,owner.callID,owner.schemaVersion===3?{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}:void 0))throw Error(`expired worktree provisioning owner ${owner.callID} could not be removed; destructive orphan cleanup skipped`);continue}if(!activeSessionIds.includes(owner.worktreeSessionId))activeSessionIds.push(owner.worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}let ownershipTagScan=await withTimeout(_internals179.listOwnershipTagSessionIds(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("background ownership tag scan exceeded its bounded init budget"));if(ownershipTagScan.status==="uncertain")throw Error(`background ownership tag state is uncertain; destructive orphan cleanup skipped: ${ownershipTagScan.reason}`);for(let sessionId of ownershipTagScan.sessionIds)if(!activeSessionIds.includes(sessionId))activeSessionIds.push(sessionId);let fallbackOwnerScan=await withTimeout(_internals179.scanDelegationFallbacksForRecovery(directory),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background delegation fallback ownership scan exceeded its bounded init budget"));if(fallbackOwnerScan.status==="uncertain")throw Error(`background fallback ownership state is uncertain; destructive orphan cleanup skipped: ${fallbackOwnerScan.reason}`);let primaryOwnerScan=await withTimeout(Promise.resolve(_internals179.scanDelegationsForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background primary ownership scan exceeded its bounded init budget"));if(primaryOwnerScan.status==="uncertain")throw _internals179.recordDelegationRecoveryObservation(directory,{source:primaryOwnerScan.source??"legacy-ledger",ok:!1,reason:primaryOwnerScan.reason,...primaryOwnerScan.repairHint?{repairHint:primaryOwnerScan.repairHint}:{}}),Error(`background primary ownership state is uncertain; destructive orphan cleanup skipped: ${primaryOwnerScan.reason}`);_internals179.recordDelegationRecoveryObservation(directory,{source:primaryOwnerScan.source??"legacy-ledger",ok:!0});let isUnsettledOwner=(record3)=>isUnsettledWorktreeOwner(record3),durableWorktreeOwners=primaryOwnerScan.owners.filter(isUnsettledOwner),mergeOwnerScan=await withTimeout(Promise.resolve(_internals179.scanWorktreeMergeFailuresForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree merge ownership scan exceeded its bounded init budget"));if(mergeOwnerScan.status==="uncertain")throw Error(`worktree merge ownership state is uncertain; destructive orphan cleanup skipped: ${mergeOwnerScan.reason}`);let allDurableOwners=[...durableWorktreeOwners,...fallbackOwnerScan.owners.map((artifact)=>artifact.record).filter(isUnsettledOwner)],preservedMergeFailures=mergeOwnerScan.failures.map(([,failure])=>failure).filter((failure)=>typeof failure.worktreePath==="string"),protectedWorktreePaths=new Set([...allDurableOwners.map((record3)=>record3.worktree?.worktreePath),...preservedMergeFailures.map((failure)=>failure.worktreePath),...liveRecoveryAuthorities.map((authority)=>authority.immutable.lanePath)].filter((value)=>typeof value==="string").map((value)=>worktreePathKey(value,directory)));for(let owner of allDurableOwners){let worktreeSessionId=owner.worktree?.worktreeSessionId;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}for(let failure of preservedMergeFailures){let segments=failure.branch?.split("/")??[],worktreeSessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId)}let liveLaneOwners=listLiveLaneOwners(directory);for(let owner of liveLaneOwners.live)if(protectedWorktreePaths.add(worktreePathKey(owner.lanePath,directory)),!activeSessionIds.includes(owner.sessionId))activeSessionIds.push(owner.sessionId);let migration=await withTimeout(migrateLegacyWorktreeBase(directory,liveLaneOwners.live),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("legacy worktree-base migration exceeded its bounded budget; retried next start")).catch((error93)=>({attempted:!0,legacyBaseExists:!0,moved:[],retained:[{lanePath:"<pass>",reason:`migration pass exceeded its budget: ${error93 instanceof Error?error93.message:String(error93)}`}],legacyBaseRemoved:!1}));if(migration.moved.length>0){recoveryReplayWarnings.push(`Migrated ${migration.moved.length} worktree(s) from the legacy shared base into the project base (issue #2527).`);for(let movedPath of migration.moved)protectedWorktreePaths.add(worktreePathKey(movedPath,directory))}if(migration.retained.length>0)recoveryReplayWarnings.push(`${migration.retained.length} legacy-base worktree entr${migration.retained.length===1?"y remains":"ies remain"} left for their owning checkouts (never deleted by this project).`);let orphanedWorktreeDirs=await withTimeout(enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during worktree enumeration; continuing without orphan reclamation`)),removedWorktrees=[],worktreeWarnings=[],recoveryRecords=listRecoveryRecords(directory),recoveryReadError=recoveryReadErrored(directory),recoveryWorktreePaths=new Set(recoveryRecords.map((record3)=>worktreePathKey(record3.worktreePath,directory)));if(recoveryReadError)worktreeWarnings.push("Recovery records are unreadable or fail schema validation; skipped all orphaned worktree deletion this pass (fail-safe).");else for(let worktreePath of orphanedWorktreeDirs){if(recoveryWorktreePaths.has(worktreePathKey(worktreePath,directory))){worktreeWarnings.push(`Preserved recovery worktree "${worktreePath}"; an unresolved recovery record still references it.`);continue}closeProjectDb(worktreePath);let outcome=await removeOwnedWorktreeDir(worktreePath,directory);if(outcome.status==="removed")removedWorktrees.push(worktreePath);else if(outcome.status==="skipped")worktreeWarnings.push(`Preserved worktree candidate "${worktreePath}": ${outcome.reason}.`);else worktreeWarnings.push(`Could not reclaim orphaned worktree "${worktreePath}" (git refused; left in place): ${outcome.reason}`)}let cleanupResult=await withTimeout(cleanupOrphanedBranches(directory,activeSessionIds,{preserveUnmerged:!0}),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during branch cleanup; continuing without orphan reclamation`)),branchWarnings=cleanupResult.errors.map((e)=>`Could not delete orphaned branch "${e.branch}": ${e.error}`),reclaimResult=await withTimeout(reclaimDeadLanes(directory,{activeSessionIds,protectedWorktreePaths}),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during dead-lane reclaim; continuing without reclaim`)).catch((error93)=>({reclaimed:[],retained:[],error:error93 instanceof Error?error93.message:String(error93)}));if(reclaimResult.reclaimed.length>0)removedWorktrees.push(...reclaimResult.reclaimed);for(let retained of reclaimResult.retained)worktreeWarnings.push(`Preserved dead lane "${retained.lanePath}" (${retained.reason}); reclaim scheduled at next start.`);let allWarnings=[...worktreeWarnings,...branchWarnings],mergedWarnings=[...recoveryReplayWarnings,...allWarnings];result={attempted:!0,crossProcessLockHeld:!1,warnings:mergedWarnings,orphanedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:cleanupResult.recoveryReadError!==!0},await writeAdvisoryFile(directory,cleanupResult,mergedWarnings,!0,removedWorktrees)}catch(err){let msg=err instanceof Error?err.message:String(err);log("initOrphanRecovery timed out or failed (non-fatal)",{error:msg}),result={attempted:!1,crossProcessLockHeld:!1,warnings:[`Orphan recovery timed out or failed: ${msg}`],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1,diagnostic:{file:".swarm/advisories/init-orphan-recovery.json",reason:msg}},await writeAdvisoryFile(directory,{removed:[],skipped:[],skippedRecoveryBranches:[],errors:[]},result.warnings,!1,[])}finally{try{await recoveryLockRelease?.()}catch{}}return result}var INIT_ORPHAN_RECOVERY_TIMEOUT_MS=1e4,OWNERSHIP_TAG_SCAN_TIMEOUT_MS2=2000,ORPHAN_RECOVERY_LOCK_FILE,_internals179;var init_init_orphan_recovery=__esm(()=>{init_delegation_health();init_pending_delegations();init_loader();init_project_db();init_file_locks();init_lane_owners();init_state2();init_recovery();init_canonical_root();init_utils();init_timeout();init_base_migration();init_core3();init_merge2();init_ownership();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();init_worktree_recovery_authority();ORPHAN_RECOVERY_LOCK_FILE=WORKTREE_LIFECYCLE_LOCK_FILE,_internals179={rmSync:fs123.rmSync,removeWorktree,isLocked,listActiveLocks,tryAcquireLock,listOwnershipTagSessionIds,scanDelegationsForRecovery,recordDelegationRecoveryObservation,scanDelegationFallbacksForRecovery,scanWorktreeMergeFailuresForRecovery,scanWorktreeRecoveryAuthoritiesForRecovery,replayWorktreeRecoveryClaimJournal,scanWorktreeProvisioningOwnersForRecovery,scanWorktreeProvisioningLifecycleJournalForRecovery,scanRegisteredWorktreeLiveness,removeWorktreeProvisioningOwner}});function entryKey2(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function invocationIdForSession(sessionID){let invocation=getAgentSession(sessionID)?.activeInvocationId;return invocation===void 0||invocation===null?"none":String(invocation)}function evictExpired(now2){if(spawnCircuits.size<=MAX_TRACKED_SPAWN_CIRCUITS){for(let[key2,entry]of spawnCircuits)if(now2-entry.updatedAt>SPAWN_CIRCUIT_TTL_MS)spawnCircuits.delete(key2);return}let byAge=[...spawnCircuits.entries()].sort((a,b)=>a[1].updatedAt-b[1].updatedAt),excess=spawnCircuits.size-MAX_TRACKED_SPAWN_CIRCUITS;for(let i=0;i<excess&&i<byAge.length;i++)spawnCircuits.delete(byAge[i][0]);for(let[key2,entry]of spawnCircuits)if(now2-entry.updatedAt>SPAWN_CIRCUIT_TTL_MS)spawnCircuits.delete(key2)}function dispatchIdentityFor(tool3,args2){let identity=createActionIdentity({tool:tool3,args:args2!=null&&typeof args2==="object"&&!Array.isArray(args2)?args2:void 0});return{digest:identity.digest,pattern:identity.pattern}}function armDispatchIdentity(callID,tool3,args2){let identity=dispatchIdentityFor(tool3,args2);if(armedIdentities.size>=MAX_ARMED_DISPATCH_IDENTITIES){let oldest=armedIdentities.keys().next().value;if(oldest!==void 0)armedIdentities.delete(oldest)}return armedIdentities.set(callID,{digest:identity.digest,pattern:identity.pattern}),{digest:identity.digest,pattern:identity.pattern}}function takeArmedDispatchIdentity(callID){let armed=armedIdentities.get(callID);if(armed)armedIdentities.delete(callID);return armed}function noteDispatchSpawnFailure(input){let now2=input.now??_internals180.now(),key2=entryKey2(input.sessionID,input.invocationID,input.actionDigest),existing=spawnCircuits.get(key2),entry=existing?{...existing,failureCount:existing.failureCount+1,updatedAt:now2}:{state:"CLOSED",sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,failureCount:1,openedAt:0,denyUntil:0,denialsInEpisode:0,updatedAt:now2},opened=!1;if(entry.state==="HALF_OPEN")entry.state="OPEN",entry.openedAt=now2,entry.denyUntil=now2+Math.max(1,input.halfOpenAfterMs),entry.denialsInEpisode=0;else if(entry.state!=="OPEN"&&entry.failureCount>=Math.max(1,input.threshold))entry.state="OPEN",entry.openedAt=now2,entry.denyUntil=now2+Math.max(1,input.halfOpenAfterMs),entry.denialsInEpisode=0,opened=!0;return entry.updatedAt=now2,spawnCircuits.set(key2,entry),evictExpired(now2),{entry,opened}}function assertDispatchSpawnCircuitAdmits(input){let now2=input.now??_internals180.now(),key2=entryKey2(input.sessionID,input.invocationID,input.actionDigest),entry=spawnCircuits.get(key2);if(!entry||entry.state==="CLOSED")return;if(entry.state==="OPEN"){if(now2<entry.denyUntil||entry.denialsInEpisode===0)throw entry.denialsInEpisode+=1,entry.updatedAt=now2,Error(`${SPAWN_CIRCUIT_DENIAL_CODE}: repeated dispatch failures for this action (${entry.failureCount} of ${Math.max(1,input.threshold)}). Read, diagnose, repair, rescope, abort, and handoff controls remain available; one recovery probe is admitted after the half-open interval.`);entry.state="HALF_OPEN",entry.updatedAt=now2;return}throw Error(`${SPAWN_CIRCUIT_DENIAL_CODE}: a recovery probe for this action is already in flight. Read, diagnose, repair, rescope, abort, and handoff controls remain available.`)}function noteDispatchSpawnSuccess(input){spawnCircuits.delete(entryKey2(input.sessionID,input.invocationID,input.actionDigest))}function spawnCircuitIsTaskTool(tool3){return normalizeToolNameLowerCase(tool3)==="task"}var MAX_TRACKED_SPAWN_CIRCUITS=500,SPAWN_CIRCUIT_TTL_MS=1800000,MAX_ARMED_DISPATCH_IDENTITIES=500,SPAWN_CIRCUIT_DENIAL_CODE="SPAWN PROTECTION CIRCUIT OPEN",spawnCircuits,armedIdentities,_internals180;var init_spawn_circuit=__esm(()=>{init_action_identity();init_normalize_tool_name();init_state2();spawnCircuits=new Map,armedIdentities=new Map;_internals180={now:()=>Date.now()}});import{createHash as createHash76}from"node:crypto";function readOwnDataValue(record3,key2){if(!record3||typeof record3!=="object"||Array.isArray(record3))return;try{let descriptor=Object.getOwnPropertyDescriptor(record3,key2);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function readFirstNormalizedOwnDataValue(record3,keys,normalize22){for(let key2 of keys){let value=readOwnDataValue(record3,key2);try{let normalized=normalize22(value);if(normalized!==void 0)return normalized}catch{}}return}function boundedActionString(value){if(typeof value!=="string")return;let trimmed=value.trim();if(trimmed.length===0)return;return trimmed}function boundedActionScalar(value){if(typeof value==="string")return boundedActionString(value);if(typeof value==="number"&&Number.isFinite(value))return value;if(typeof value==="boolean")return value;return}function boundedStableTarget(value){let normalized=boundedActionString(value);if(normalized===void 0||hasControlCharacters(normalized))return;return normalized}function boundedPathAlias(value){if(typeof value==="string"){let normalized=boundedActionString(value);return normalized===void 0?void 0:{value:normalized}}if(!Array.isArray(value))return;try{let paths=value.map((entry)=>boundedActionString(entry)).filter((entry)=>entry!==void 0);if(paths.length===0)return;let normalizedPaths=[...new Set(paths)].sort();if(normalizedPaths.length<=MAX_ACTION_PATH_PREFIX_ITEMS)return{value:normalizedPaths};let tailHasher=createHash76("sha256");tailHasher.update(`tail-count:${normalizedPaths.length-MAX_ACTION_PATH_PREFIX_ITEMS};`);for(let index=MAX_ACTION_PATH_PREFIX_ITEMS;index<normalizedPaths.length;index+=1){let pathValue=normalizedPaths[index];tailHasher.update(`entry-index:${index};length:${pathValue.length};`),tailHasher.update(pathValue)}let tailDigest=tailHasher.digest("hex").slice(0,16);return{value:normalizedPaths,tailDigest}}catch{return}}function gateActionArgs(tool3,args2){let projection={},normalizedTool=normalizeToolNameLowerCase(tool3??"");if(normalizedTool==="task"){let discriminator=gateDenialDiscriminator(tool3,args2);if(discriminator)projection.subagent_type=discriminator}let record3=args2,taskId=readFirstNormalizedOwnDataValue(record3,["taskId","task_id","id"],boundedActionScalar);if(taskId!==void 0)projection.taskId=taskId;if(normalizedTool==="update_task_status"){let status=readFirstNormalizedOwnDataValue(record3,["status"],boundedActionScalar);if(status!==void 0)projection.status=status}let phase=readFirstNormalizedOwnDataValue(record3,["phase","phase_number"],boundedActionScalar);if(phase!==void 0)projection.phase=phase;let mode=readFirstNormalizedOwnDataValue(record3,["mode","execution_mode"],boundedActionScalar);if(mode!==void 0)projection.mode=mode;let background=readFirstNormalizedOwnDataValue(record3,["background","run_in_background","runInBackground"],(value)=>{if(typeof value==="boolean")return value;if(typeof value!=="string")return;let normalized=value.trim().toLowerCase();return normalized==="true"?!0:normalized==="false"?!1:void 0});if(background!==void 0)projection.background=background;let workingDirectory=readFirstNormalizedOwnDataValue(record3,["working_directory","workingDirectory"],boundedActionScalar);if(workingDirectory!==void 0)projection.working_directory=workingDirectory;let scopeId=readFirstNormalizedOwnDataValue(record3,["scope_id","scopeId","scope"],boundedActionScalar);if(scopeId!==void 0)projection.scope_id=scopeId;let pathAlias=readFirstNormalizedOwnDataValue(record3,["filePath","file","path","paths","files"],boundedPathAlias);if(pathAlias!==void 0){if(projection.path=pathAlias.value,pathAlias.tailDigest!==void 0)projection.path_tail_digest=pathAlias.tailDigest}let stableTarget=readFirstNormalizedOwnDataValue(record3,STABLE_TARGET_KEYS,boundedStableTarget);if(stableTarget!==void 0)projection.url=stableTarget;return projection}function gateActionIdentity(tool3,args2){return createActionIdentity({tool:normalizeToolNameLowerCase(tool3??""),args:gateActionArgs(tool3,args2)})}function gateDenialDiscriminator(tool3,args2){try{if(normalizeToolNameLowerCase(tool3??"")!=="task")return"";let subagentType=readOwnDataValue(args2,"subagent_type");if(typeof subagentType!=="string"||subagentType.length===0)return"";let canonical=stripKnownSwarmPrefix(subagentType).trim().toLowerCase();if(canonical.length===0)return"";return canonical.slice(0,MAX_DISCRIMINATOR_LENGTH)}catch{return""}}function deriveGateDenialCode(message){if(typeof message!=="string")return UNCLASSIFIED_GATE_DENIAL_CODE;let colonIndex=message.indexOf(":");if(colonIndex<=0)return UNCLASSIFIED_GATE_DENIAL_CODE;let candidate=message.slice(0,colonIndex).trim();if(candidate.length===0||candidate.length>MAX_CODE_LENGTH)return UNCLASSIFIED_GATE_DENIAL_CODE;if(isGenericLegacyGateCode(candidate))return UNCLASSIFIED_GATE_DENIAL_CODE;return candidate}function isGenericLegacyGateCode(candidate){let normalized=candidate.trim().replace(/\s+/g," ").toUpperCase();return normalized==="BLOCKED"||normalized==="WRITE BLOCKED"||normalized.startsWith("[SANDBOX] BLOCKED")||normalized.startsWith("SANDBOX BLOCKED")||normalized.startsWith("SANDBOX_")}function boundedStructuredGateCode(value){if(typeof value!=="string")return;let candidate=value.trim();if(candidate.length===0||candidate.length>MAX_CODE_LENGTH||hasControlCharacters(candidate))return;if(isGenericLegacyGateCode(candidate))return;return candidate}function hasControlCharacters(value){for(let character of value){let code=character.charCodeAt(0);if(code<=31||code===127)return!0}return!1}function deriveStructuredGateDenialCode(err){for(let key2 of["gateCode","code"]){let candidate=boundedStructuredGateCode(readOwnDataValue(err,key2));if(candidate!==void 0)return candidate}return}function deriveGateDenialCause(err,message){return deriveStructuredGateDenialCode(err)??deriveGateDenialCode(message)}function isAbortLikeError(err){if(err&&typeof err==="object"){if(err.name==="AbortError")return!0;let message=err.message;if(typeof message==="string"&&message.startsWith("AbortError"))return!0}return!1}function gateDenialWarnText(count,code){if(code===UNCLASSIFIED_GATE_DENIAL_CODE)return`
|
|
3755
|
+
`)}var _internals175;var init_reset=__esm(()=>{init_manager4();init_utils2();init_ledger();init_manager();init_reset_backup();_internals175={backupSwarmStateBeforeReset,clearPlanLedgerForReset,withPlanLifecycleLock,existsSync:fs119.existsSync,readFileSync:fs119.readFileSync,unlinkSync:fs119.unlinkSync,writeFileSync:fs119.writeFileSync,rmSync:fs119.rmSync}});import*as fs120 from"node:fs";import*as path218 from"node:path";function resolveWorktreeRepoOwnership(worktreePath,expectedProjectRoot){let io={failed:!1},gitDir=readLinkedWorktreeGitDir(worktreePath,io);if(io.failed||!gitDir)return{owned:!1,uncertain:io.failed};let mainWorktree=resolveMainWorktree(gitDir,io);if(io.failed||!mainWorktree)return{owned:!1,uncertain:!0};let cmp=process.platform==="win32"?(a,b)=>a.toLowerCase()===b.toLowerCase():(a,b)=>a===b,canonical=(p)=>{try{return fs120.realpathSync(p)}catch{return p}},mainReal=path218.resolve(canonical(mainWorktree)),rootReal=path218.resolve(canonical(expectedProjectRoot)),mainLex=path218.resolve(mainWorktree),rootLex=path218.resolve(expectedProjectRoot);if(cmp(mainReal,rootReal)||cmp(mainLex,rootLex)||cmp(mainReal,rootLex)||cmp(mainLex,rootReal))return{owned:!0,mainWorktree,uncertain:!1};let statOf=(p)=>{try{let st=fs120.statSync(p,{bigint:!0});return{dev:st.dev,ino:st.ino}}catch{return}},mainStat=statOf(mainWorktree),rootStat=statOf(expectedProjectRoot);return{owned:mainStat!==void 0&&rootStat!==void 0&&mainStat.dev>0n&&mainStat.ino>0n&&mainStat.dev===rootStat.dev&&mainStat.ino===rootStat.ino,mainWorktree,uncertain:!1}}function sleepSync4(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{}}function remember(key2,displayPath,value,io){if(!io.failed)return cache5(key2,value);try{_internals176.addDeferredWarning(`[swarm] Could not read git metadata for ${displayPath} after ${MAX_DETECTION_ATTEMPTS} attempts; worktree-lane permission scoping was skipped for it. If this directory IS a swarm lane, external-directory prompts raised there cannot be answered and the lane may hang. Check filesystem permissions and open-file limits, then restart the session.`)}catch{}return null}function cache5(key2,value){if(laneContextCache.size>=MAX_CACHED_DIRECTORIES){let oldest=laneContextCache.keys().next();if(!oldest.done)laneContextCache.delete(oldest.value)}return laneContextCache.set(key2,value),value}function isSwarmOwnedBranch(gitDir,io){let head2;try{head2=_internals176.readFileSync(path218.join(gitDir,"HEAD"),"utf-8")}catch(err){if(err?.code!=="ENOENT")io.failed=!0;return!1}let branch=/^\s*ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head2)?.[1];if(!branch)return!1;return matchSwarmLaneBranch(branch)!==void 0}function readLinkedWorktreeGitDir(directory,io){let dotGit=path218.join(directory,".git"),stat21;try{stat21=_internals176.statSync(dotGit)}catch(err){if(err?.code!=="ENOENT")io.failed=!0;return}if(!stat21.isFile())return;let contents;try{contents=_internals176.readFileSync(dotGit,"utf-8")}catch(err){if(err?.code!=="ENOENT")io.failed=!0;return}let pointer=/^\s*gitdir:\s*(.+?)\s*$/m.exec(contents)?.[1];if(!pointer)return;return path218.resolve(directory,pointer)}function resolveMainWorktree(gitDir,io){let commonDir;try{let trimmed=_internals176.readFileSync(path218.join(gitDir,"commondir"),"utf-8").trim();if(trimmed)commonDir=path218.resolve(gitDir,trimmed)}catch(err){if(err?.code!=="ENOENT")io.failed=!0}if(commonDir){let parent2=path218.dirname(commonDir);return parent2&&parent2!==commonDir?parent2:void 0}let worktreesDir=path218.dirname(gitDir);if(path218.basename(worktreesDir)!=="worktrees")return;let sharedGitDir=path218.dirname(worktreesDir);if(path218.basename(sharedGitDir)!==".git")return;let parent=path218.dirname(sharedGitDir);return parent&&parent!==sharedGitDir?parent:void 0}function resolveLaneContext(directory){if(typeof directory!=="string"||directory.trim()==="")return null;let resolved;try{resolved=path218.resolve(directory)}catch{return null}let key2=canonicalRootKeyFresh(resolved),cached3=laneContextCache.get(key2);if(cached3!==void 0)return cached3;let io={failed:!1},result=null;for(let attempt=1;attempt<=MAX_DETECTION_ATTEMPTS;attempt+=1){if(io={failed:!1},result=attemptDetection(resolved,io),result!==null||!io.failed)break;if(attempt<MAX_DETECTION_ATTEMPTS)sleepSync4(DETECTION_RETRY_BACKOFF_MS)}if(result!==null)return cache5(key2,result);return remember(key2,resolved,null,io)}function attemptDetection(resolved,io){try{let laneRoot,gitDir,current=resolved;for(let depth=0;depth<MAX_ANCESTOR_WALK_DEPTH;depth+=1){let candidate=readLinkedWorktreeGitDir(current,io);if(candidate){laneRoot=current,gitDir=candidate;break}let parent=path218.dirname(current);if(parent===current)break;current=parent}if(!laneRoot||!gitDir)return null;if(!(isSwarmOwnedBranch(gitDir,io)||matchSwarmLanePath(laneRoot)!==void 0))return null;let parentProjectPath=resolveMainWorktree(gitDir,io);if(!parentProjectPath)return null;if(sameProjectRoot(parentProjectPath,laneRoot))return null;return{lanePath:laneRoot,parentProjectPath:path218.resolve(parentProjectPath)}}catch{return io.failed=!0,null}}var MAX_CACHED_DIRECTORIES=256,laneContextCache,_internals176,MAX_ANCESTOR_WALK_DEPTH=40,MAX_DETECTION_ATTEMPTS=3,DETECTION_RETRY_BACKOFF_MS=5;var init_lane_context=__esm(()=>{init_warning_buffer();init_canonical_root();init_swarm_branch();laneContextCache=new Map;_internals176={readFileSync:fs120.readFileSync,statSync:fs120.statSync,addDeferredWarning,clearCache:()=>{laneContextCache.clear()}}});import*as fs121 from"node:fs";import*as path219 from"node:path";function listLegacyLanes(legacyBase){let lanes=[],sessions;try{sessions=_internals177.readdirSync(legacyBase,{withFileTypes:!0})}catch{return lanes}for(let session of sessions){if(!session.isDirectory())continue;let laneEntries;try{laneEntries=_internals177.readdirSync(path219.join(legacyBase,session.name),{withFileTypes:!0})}catch{continue}for(let lane of laneEntries){if(!lane.isDirectory())continue;lanes.push({lanePath:path219.join(legacyBase,session.name,lane.name),sessionId:session.name})}}return lanes}async function gitWorktreeMove(projectRoot,from,to){let proc;try{proc=_internals177.bunSpawn([_internals177.resolveGitExecutable(),"-C",projectRoot,"worktree","move",from,to],{cwd:projectRoot,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:GIT_MOVE_TIMEOUT_MS,killProcessTree:!0});let code=await proc.exited;if(code===0)return;return(proc.stderr?await proc.stderr.text().catch(()=>""):"").trim()||`git worktree move exited ${code}`}catch(error93){return error93 instanceof Error?error93.message:String(error93)}finally{try{proc?.kill?.()}catch{}}}function isLive(entry,liveOwners){let canonical=canonicalRootKeyFresh(entry.lanePath);return liveOwners.some((owner)=>owner.lanePath===entry.lanePath||canonicalRootKeyFresh(owner.lanePath)===canonical)}async function migrateLegacyWorktreeBase(directory,liveOwners){let result={attempted:!1,legacyBaseExists:!1,moved:[],retained:[],legacyBaseRemoved:!1},legacyBase=path219.resolve(path219.dirname(directory),SWARM_WORKTREE_DIR_NAME);if(result.legacyBaseExists=_internals177.existsSync(legacyBase),!result.legacyBaseExists)return result;result.attempted=!0;let newBase=resolveWorktreeBaseDir(directory),lanes=listLegacyLanes(legacyBase),movedCount=0;for(let lane of lanes){let dotGit=path219.join(lane.lanePath,".git");if(!_internals177.existsSync(dotGit)){result.retained.push({lanePath:lane.lanePath,reason:"gitless legacy remnant (ownership unprovable)"});continue}let ownership=_internals177.resolveWorktreeRepoOwnership(lane.lanePath,directory);if(!ownership.owned||ownership.uncertain){result.retained.push({lanePath:lane.lanePath,reason:ownership.uncertain?"ownership uncertain":"owned by a different repository"});continue}if(isLive(lane,liveOwners)){result.retained.push({lanePath:lane.lanePath,reason:"live lane (owner process running) — migrates after its dispatch ends"});continue}if(movedCount>=MAX_MIGRATIONS_PER_PASS){result.retained.push({lanePath:lane.lanePath,reason:"per-pass migration cap reached — next start continues"});continue}let target=path219.join(newBase,lane.sessionId,path219.basename(lane.lanePath));try{_internals177.mkdirSync(path219.dirname(target),{recursive:!0})}catch(error93){result.retained.push({lanePath:lane.lanePath,reason:`target mkdir failed: ${error93 instanceof Error?error93.message:String(error93)}`});continue}let moveError=await gitWorktreeMove(directory,lane.lanePath,target);if(moveError){result.retained.push({lanePath:lane.lanePath,reason:moveError});continue}try{_internals177.rmdirSync(path219.dirname(lane.lanePath))}catch{}result.moved.push(target),movedCount++}try{_internals177.rmdirSync(legacyBase),result.legacyBaseRemoved=!0}catch{}if(result.retained.length>0)log(`[base-migration] ${result.retained.length} legacy-base entr${result.retained.length===1?"y":"ies"} left for their owning checkouts (${result.retained[0]?.reason})`);return result}var GIT_MOVE_TIMEOUT_MS=1e4,MAX_MIGRATIONS_PER_PASS=16,_internals177;var init_base_migration=__esm(()=>{init_constants();init_lane_context();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();_internals177={resolveWorktreeRepoOwnership,bunSpawn,resolveGitExecutable,readdirSync:fs121.readdirSync.bind(fs121),existsSync:fs121.existsSync.bind(fs121),mkdirSync:fs121.mkdirSync.bind(fs121),rmdirSync:fs121.rmdirSync.bind(fs121),realpathSync:fs121.realpathSync.bind(fs121)}});import*as fs122 from"node:fs";import*as path220 from"node:path";function probeGitMarker(dotGitPath){try{return _internals178.statSync(dotGitPath),"present"}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return"gitless";return"uncertain"}}async function removeOwnedWorktreeDir(worktreePath,projectRoot){let marker=probeGitMarker(path220.join(worktreePath,".git"));if(marker==="uncertain")return{status:"skipped",reason:"ownership uncertain (unreadable .git marker)"};if(marker==="gitless"){if(!_internals178.isPathUnderSwarmWorktreeBase(worktreePath,projectRoot))return{status:"skipped",reason:"gitless directory outside the project worktree base (ownership unprovable)"};try{return _internals178.rmSync(worktreePath,{recursive:!0,force:!0}),{status:"removed"}}catch(error93){return{status:"skipped",reason:`gitless internal remnant removal failed: ${error93 instanceof Error?error93.message:String(error93)}`}}}let ownership=_internals178.resolveWorktreeRepoOwnership(worktreePath,projectRoot);if(!ownership.owned||ownership.uncertain)return{status:"skipped",reason:ownership.uncertain?"ownership uncertain (unreadable .git pointer)":"owned by a different repository"};let result=await _internals178.removeWorktree(worktreePath,projectRoot);if("error"in result)return{status:"refused",reason:result.error};return{status:"removed"}}var _internals178;var init_ownership=__esm(()=>{init_lane_context();init_core3();_internals178={resolveWorktreeRepoOwnership,isPathUnderSwarmWorktreeBase,removeWorktree,rmSync:fs122.rmSync.bind(fs122),statSync:fs122.statSync.bind(fs122)}});import*as fs123 from"node:fs";import*as fsPromises9 from"node:fs/promises";import*as path221 from"node:path";async function listOwnershipTagSessionIds(directory){let scan=await scanBackgroundWorktreeOwnershipTagsForRecovery(directory);if(scan.status==="uncertain")return scan;return{status:"ok",sessionIds:[...new Set(scan.owners.map((owner)=>owner.sessionId))]}}async function writeAdvisoryFile(directory,cleanupResult,warnings,attempted,removedWorktrees=[]){let advisoryPath=path221.join(directory,".swarm","advisories","init-orphan-recovery.json"),advisory={initTimestamp:new Date().toISOString(),warnings,errors:cleanupResult.errors,reclaimed:{removedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:attempted},...cleanupResult.skippedRecoveryBranches&&cleanupResult.skippedRecoveryBranches.length>0?{preservedRecoveryBranches:cleanupResult.skippedRecoveryBranches}:{},...cleanupResult.recoveryReadError?{recoveryReadError:!0,note:"skipped all lane-branch deletions this pass because .swarm/recovery/ was unreadable (fail-safe)"}:{}};try{await fsPromises9.mkdir(path221.dirname(advisoryPath),{recursive:!0}),await fsPromises9.writeFile(advisoryPath,JSON.stringify(advisory,null,2),"utf-8")}catch{log("initOrphanRecovery advisory file write failed (non-fatal)")}}function resolveWorktreeEnumerationBases(directory){let bases=[resolveWorktreeBaseDir(directory)];try{let config3=loadPluginConfig(directory),overrides2=[config3?.worktree?.worktree_dir,config3?.turbo?.lean?.worktree_dir].filter((value)=>typeof value==="string");for(let override of overrides2){let base=resolveWorktreeBaseDir(directory,override);if(!bases.some((existing)=>existing===base))bases.push(base)}}catch{}return bases}async function enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths=new Set){let orphanedDirs=[];for(let worktreeRoot of resolveWorktreeEnumerationBases(directory)){let entries2;try{entries2=await fsPromises9.readdir(worktreeRoot,{withFileTypes:!0})}catch{continue}for(let entry of entries2){if(!entry.isDirectory())continue;let sessionId=entry.name;if(activeSessionIds.includes(sessionId))continue;let sessionEntries;try{sessionEntries=await fsPromises9.readdir(path221.join(worktreeRoot,sessionId),{withFileTypes:!0})}catch{continue}for(let laneEntry of sessionEntries){if(!laneEntry.isDirectory())continue;let worktreePath=path221.join(worktreeRoot,sessionId,laneEntry.name);if(protectedWorktreePaths.has(canonicalRootKeyFresh(worktreePath)))continue;orphanedDirs.push(worktreePath)}}}return orphanedDirs}async function isCrossProcessLockHeld(directory){if(_internals179.isLocked(directory,ORPHAN_RECOVERY_LOCK_FILE))return!0;if(_internals179.listActiveLocks(directory).length>0)return!0;return!1}async function crossProcessAdvisoryResult(directory,warning){let result={attempted:!0,crossProcessLockHeld:!0,warnings:[warning],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1};return await writeAdvisoryFile(directory,{removed:[],skipped:[],errors:[]},result.warnings,!1,[]),result}function worktreePathKey(worktreePath,directory){let absolutePath2=path221.isAbsolute(worktreePath)?worktreePath:path221.resolve(directory,worktreePath);return canonicalRootKeyFresh(absolutePath2)}async function runInitOrphanRecovery(directory){let result,recoveryLockRelease,recoveryReplayWarnings=[];try{if(await isCrossProcessLockHeld(directory))return crossProcessAdvisoryResult(directory,"Cross-process lock held — another opencode process may be active. "+"Skipping destructive cleanup to preserve its worktrees/branches. Run '/swarm status' or check '.swarm/locks/' to identify active processes.");let lockAcquireResult=await _internals179.tryAcquireLock(directory,ORPHAN_RECOVERY_LOCK_FILE,"init-orphan-recovery","init");if(!lockAcquireResult.acquired)return crossProcessAdvisoryResult(directory,"Cross-process lifecycle lock was acquired by another process during init; skipping destructive cleanup to preserve its worktrees/branches.");recoveryLockRelease=lockAcquireResult.lock._release;let activeSessionIds=Array.from(swarmState.agentSessions.keys()),replayedClaims=_internals179.replayWorktreeRecoveryClaimJournal(directory),uncertainReplay=replayedClaims.find((entry)=>entry.outcome==="uncertain_committed_without_authority");if(uncertainReplay)throw _internals179.recordDelegationRecoveryObservation(directory,{source:"unknown",ok:!1,reason:`worktree recovery replay is uncertain for authority ${uncertainReplay.authorityDigest}: committed claim is missing its authoritative record`}),Error(`worktree recovery replay is uncertain for authority ${uncertainReplay.authorityDigest}; destructive orphan cleanup skipped`);let replayRepairs=replayedClaims.filter((entry)=>entry.outcome==="aborted_prepared_claim"||entry.outcome==="removed_uncommitted_credential"||entry.outcome==="released_orphaned_committed_claim");if(replayRepairs.length>0)recoveryReplayWarnings.push(`Recovered ${replayRepairs.length} interrupted worktree recovery claim${replayRepairs.length===1?"":"s"} during startup replay before orphan cleanup.`);let recoveryAuthorityScan=_internals179.scanWorktreeRecoveryAuthoritiesForRecovery(directory);if(recoveryAuthorityScan.status!=="ok")throw _internals179.recordDelegationRecoveryObservation(directory,{source:"unknown",ok:!1,reason:`worktree recovery authority state is uncertain: ${recoveryAuthorityScan.reason}`}),Error(`worktree recovery authority state is uncertain; destructive orphan cleanup skipped: ${recoveryAuthorityScan.reason}`);let liveRecoveryAuthorities=recoveryAuthorityScan.authorities.filter((authority)=>authority.status!=="finalized");for(let authority of liveRecoveryAuthorities){for(let sessionId of[authority.immutable.parentSessionId,authority.claim?.claimantSessionId,authority.claim?.childSessionId])if(sessionId&&!activeSessionIds.includes(sessionId))activeSessionIds.push(sessionId);if(authority.status==="claimed"&&authority.claim&&!swarmState.agentSessions.has(authority.claim.childSessionId))recoveryReplayWarnings.push(`Preserved claimed recovery lane "${authority.immutable.laneBranch}" for task ${authority.immutable.taskId}; restart reconciliation may still need to resume prompt delivery for child session ${authority.claim.childSessionId}.`)}let provisioningOwnerScan=await withTimeout(Promise.resolve(_internals179.scanWorktreeProvisioningOwnersForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree provisioning ownership scan exceeded its bounded init budget"));if(provisioningOwnerScan.status==="uncertain")throw Error(`worktree provisioning ownership state is uncertain; destructive orphan cleanup skipped: ${provisioningOwnerScan.reason}`);let provisioningLifecycleScan=_internals179.scanWorktreeProvisioningLifecycleJournalForRecovery(directory);if(provisioningLifecycleScan.status==="uncertain")throw Error(`worktree provisioning lifecycle state is uncertain; destructive orphan cleanup skipped: ${provisioningLifecycleScan.reason}`);let latestLifecycleByCall=new Map(provisioningLifecycleScan.entries.map((entry)=>[entry.callID,entry]));for(let owner of provisioningOwnerScan.owners){if(owner.schemaVersion!==3)continue;let lifecycle=latestLifecycleByCall.get(owner.callID);if(!lifecycle||lifecycle.state!=="OWNER_PUBLISHED"||lifecycle.parentSessionId!==owner.parentSessionId||lifecycle.worktreeSessionId!==owner.worktreeSessionId||lifecycle.taskId!==owner.taskId||lifecycle.reservationId!==owner.reservationId||lifecycle.generation!==owner.generation||lifecycle.branchName!==owner.branchName)throw Error(`worktree provisioning owner ${owner.callID} is not corroborated by its exact lifecycle journal entry; destructive orphan cleanup skipped`)}let registeredWorktrees=provisioningOwnerScan.owners.length===0?{status:"ok",liveBranches:[]}:await withTimeout(_internals179.scanRegisteredWorktreeLiveness(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("registered worktree liveness scan exceeded its bounded init budget"));if(registeredWorktrees.status==="uncertain")throw Error(`registered worktree liveness is uncertain; destructive orphan cleanup skipped: ${registeredWorktrees.reason}`);let liveBranches=new Set(registeredWorktrees.liveBranches),now2=Date.now();for(let owner of provisioningOwnerScan.owners){let leaseIsLive=now2-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS,sessionIds=new Set([owner.parentSessionId,owner.worktreeSessionId]),branchIsLive=owner.schemaVersion===2?[...sessionIds].some((sessionId)=>liveBranches.has(`swarm/lane/${sessionId}/${owner.taskId}`)||liveBranches.has(`swarm-lane/${sessionId}/${owner.taskId}`)):[...liveBranches].some((branch)=>{let segments=branch.split("/"),sessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;return sessionId!==void 0&&sessionIds.has(sessionId)});if(!leaseIsLive&&!branchIsLive){if(!_internals179.removeWorktreeProvisioningOwner(directory,owner.callID,owner.schemaVersion===3?{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}:void 0))throw Error(`expired worktree provisioning owner ${owner.callID} could not be removed; destructive orphan cleanup skipped`);continue}if(!activeSessionIds.includes(owner.worktreeSessionId))activeSessionIds.push(owner.worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}let ownershipTagScan=await withTimeout(_internals179.listOwnershipTagSessionIds(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("background ownership tag scan exceeded its bounded init budget"));if(ownershipTagScan.status==="uncertain")throw Error(`background ownership tag state is uncertain; destructive orphan cleanup skipped: ${ownershipTagScan.reason}`);for(let sessionId of ownershipTagScan.sessionIds)if(!activeSessionIds.includes(sessionId))activeSessionIds.push(sessionId);let fallbackOwnerScan=await withTimeout(_internals179.scanDelegationFallbacksForRecovery(directory),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background delegation fallback ownership scan exceeded its bounded init budget"));if(fallbackOwnerScan.status==="uncertain")throw Error(`background fallback ownership state is uncertain; destructive orphan cleanup skipped: ${fallbackOwnerScan.reason}`);let primaryOwnerScan=await withTimeout(Promise.resolve(_internals179.scanDelegationsForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background primary ownership scan exceeded its bounded init budget"));if(primaryOwnerScan.status==="uncertain")throw _internals179.recordDelegationRecoveryObservation(directory,{source:primaryOwnerScan.source??"legacy-ledger",ok:!1,reason:primaryOwnerScan.reason,...primaryOwnerScan.repairHint?{repairHint:primaryOwnerScan.repairHint}:{}}),Error(`background primary ownership state is uncertain; destructive orphan cleanup skipped: ${primaryOwnerScan.reason}`);_internals179.recordDelegationRecoveryObservation(directory,{source:primaryOwnerScan.source??"legacy-ledger",ok:!0});let isUnsettledOwner=(record3)=>isUnsettledWorktreeOwner(record3),durableWorktreeOwners=primaryOwnerScan.owners.filter(isUnsettledOwner),mergeOwnerScan=await withTimeout(Promise.resolve(_internals179.scanWorktreeMergeFailuresForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree merge ownership scan exceeded its bounded init budget"));if(mergeOwnerScan.status==="uncertain")throw Error(`worktree merge ownership state is uncertain; destructive orphan cleanup skipped: ${mergeOwnerScan.reason}`);let allDurableOwners=[...durableWorktreeOwners,...fallbackOwnerScan.owners.map((artifact)=>artifact.record).filter(isUnsettledOwner)],preservedMergeFailures=mergeOwnerScan.failures.map(([,failure])=>failure).filter((failure)=>typeof failure.worktreePath==="string"),protectedWorktreePaths=new Set([...allDurableOwners.map((record3)=>record3.worktree?.worktreePath),...preservedMergeFailures.map((failure)=>failure.worktreePath),...liveRecoveryAuthorities.map((authority)=>authority.immutable.lanePath)].filter((value)=>typeof value==="string").map((value)=>worktreePathKey(value,directory)));for(let owner of allDurableOwners){let worktreeSessionId=owner.worktree?.worktreeSessionId;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}for(let failure of preservedMergeFailures){let segments=failure.branch?.split("/")??[],worktreeSessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId)}let liveLaneOwners=listLiveLaneOwners(directory);for(let owner of liveLaneOwners.live)if(protectedWorktreePaths.add(worktreePathKey(owner.lanePath,directory)),!activeSessionIds.includes(owner.sessionId))activeSessionIds.push(owner.sessionId);let migration=await withTimeout(migrateLegacyWorktreeBase(directory,liveLaneOwners.live),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("legacy worktree-base migration exceeded its bounded budget; retried next start")).catch((error93)=>({attempted:!0,legacyBaseExists:!0,moved:[],retained:[{lanePath:"<pass>",reason:`migration pass exceeded its budget: ${error93 instanceof Error?error93.message:String(error93)}`}],legacyBaseRemoved:!1}));if(migration.moved.length>0){recoveryReplayWarnings.push(`Migrated ${migration.moved.length} worktree(s) from the legacy shared base into the project base (issue #2527).`);for(let movedPath of migration.moved)protectedWorktreePaths.add(worktreePathKey(movedPath,directory))}if(migration.retained.length>0)recoveryReplayWarnings.push(`${migration.retained.length} legacy-base worktree entr${migration.retained.length===1?"y remains":"ies remain"} left for their owning checkouts (never deleted by this project).`);let orphanedWorktreeDirs=await withTimeout(enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during worktree enumeration; continuing without orphan reclamation`)),removedWorktrees=[],worktreeWarnings=[],recoveryRecords=listRecoveryRecords(directory),recoveryReadError=recoveryReadErrored(directory),recoveryWorktreePaths=new Set(recoveryRecords.map((record3)=>worktreePathKey(record3.worktreePath,directory)));if(recoveryReadError)worktreeWarnings.push("Recovery records are unreadable or fail schema validation; skipped all orphaned worktree deletion this pass (fail-safe).");else for(let worktreePath of orphanedWorktreeDirs){if(recoveryWorktreePaths.has(worktreePathKey(worktreePath,directory))){worktreeWarnings.push(`Preserved recovery worktree "${worktreePath}"; an unresolved recovery record still references it.`);continue}closeProjectDb(worktreePath);let outcome=await removeOwnedWorktreeDir(worktreePath,directory);if(outcome.status==="removed")removedWorktrees.push(worktreePath);else if(outcome.status==="skipped")worktreeWarnings.push(`Preserved worktree candidate "${worktreePath}": ${outcome.reason}.`);else worktreeWarnings.push(`Could not reclaim orphaned worktree "${worktreePath}" (git refused; left in place): ${outcome.reason}`)}let cleanupResult=await withTimeout(cleanupOrphanedBranches(directory,activeSessionIds,{preserveUnmerged:!0}),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during branch cleanup; continuing without orphan reclamation`)),branchWarnings=cleanupResult.errors.map((e)=>`Could not delete orphaned branch "${e.branch}": ${e.error}`),reclaimResult=await withTimeout(reclaimDeadLanes(directory,{activeSessionIds,protectedWorktreePaths}),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during dead-lane reclaim; continuing without reclaim`)).catch((error93)=>({reclaimed:[],retained:[],error:error93 instanceof Error?error93.message:String(error93)}));if(reclaimResult.reclaimed.length>0)removedWorktrees.push(...reclaimResult.reclaimed);for(let retained of reclaimResult.retained)worktreeWarnings.push(`Preserved dead lane "${retained.lanePath}" (${retained.reason}); reclaim scheduled at next start.`);let allWarnings=[...worktreeWarnings,...branchWarnings],mergedWarnings=[...recoveryReplayWarnings,...allWarnings];result={attempted:!0,crossProcessLockHeld:!1,warnings:mergedWarnings,orphanedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:cleanupResult.recoveryReadError!==!0},await writeAdvisoryFile(directory,cleanupResult,mergedWarnings,!0,removedWorktrees)}catch(err){let msg=err instanceof Error?err.message:String(err);log("initOrphanRecovery timed out or failed (non-fatal)",{error:msg}),result={attempted:!1,crossProcessLockHeld:!1,warnings:[`Orphan recovery timed out or failed: ${msg}`],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1,diagnostic:{file:".swarm/advisories/init-orphan-recovery.json",reason:msg}},await writeAdvisoryFile(directory,{removed:[],skipped:[],skippedRecoveryBranches:[],errors:[]},result.warnings,!1,[])}finally{try{await recoveryLockRelease?.()}catch{}}return result}var INIT_ORPHAN_RECOVERY_TIMEOUT_MS=1e4,OWNERSHIP_TAG_SCAN_TIMEOUT_MS2=2000,ORPHAN_RECOVERY_LOCK_FILE,_internals179;var init_init_orphan_recovery=__esm(()=>{init_delegation_health();init_pending_delegations();init_loader();init_project_db();init_file_locks();init_lane_owners();init_state2();init_recovery();init_canonical_root();init_utils();init_timeout();init_base_migration();init_core3();init_merge2();init_ownership();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();init_worktree_recovery_authority();ORPHAN_RECOVERY_LOCK_FILE=WORKTREE_LIFECYCLE_LOCK_FILE,_internals179={rmSync:fs123.rmSync,removeWorktree,isLocked,listActiveLocks,tryAcquireLock,listOwnershipTagSessionIds,scanDelegationsForRecovery,recordDelegationRecoveryObservation,scanDelegationFallbacksForRecovery,scanWorktreeMergeFailuresForRecovery,scanWorktreeRecoveryAuthoritiesForRecovery,replayWorktreeRecoveryClaimJournal,scanWorktreeProvisioningOwnersForRecovery,scanWorktreeProvisioningLifecycleJournalForRecovery,scanRegisteredWorktreeLiveness,removeWorktreeProvisioningOwner}});function entryKey2(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function invocationIdForSession(sessionID){let invocation=getAgentSession(sessionID)?.activeInvocationId;return invocation===void 0||invocation===null?"none":String(invocation)}function evictExpired(now2){if(spawnCircuits.size<=MAX_TRACKED_SPAWN_CIRCUITS){for(let[key2,entry]of spawnCircuits)if(now2-entry.updatedAt>SPAWN_CIRCUIT_TTL_MS)spawnCircuits.delete(key2);return}let byAge=[...spawnCircuits.entries()].sort((a,b)=>a[1].updatedAt-b[1].updatedAt),excess=spawnCircuits.size-MAX_TRACKED_SPAWN_CIRCUITS;for(let i=0;i<excess&&i<byAge.length;i++)spawnCircuits.delete(byAge[i][0]);for(let[key2,entry]of spawnCircuits)if(now2-entry.updatedAt>SPAWN_CIRCUIT_TTL_MS)spawnCircuits.delete(key2)}function dispatchIdentityFor(tool3,args2){let identity=createActionIdentity({tool:tool3,args:args2!=null&&typeof args2==="object"&&!Array.isArray(args2)?args2:void 0});return{digest:identity.digest,pattern:identity.pattern}}function armDispatchIdentity(callID,tool3,args2){let identity=dispatchIdentityFor(tool3,args2);if(armedIdentities.size>=MAX_ARMED_DISPATCH_IDENTITIES){let oldest=armedIdentities.keys().next().value;if(oldest!==void 0)armedIdentities.delete(oldest)}return armedIdentities.set(callID,{digest:identity.digest,pattern:identity.pattern}),{digest:identity.digest,pattern:identity.pattern}}function takeArmedDispatchIdentity(callID){let armed=armedIdentities.get(callID);if(armed)armedIdentities.delete(callID);return armed}function noteDispatchSpawnFailure(input){let now2=input.now??_internals180.now(),key2=entryKey2(input.sessionID,input.invocationID,input.actionDigest),existing=spawnCircuits.get(key2),entry=existing?{...existing,failureCount:existing.failureCount+1,updatedAt:now2}:{state:"CLOSED",sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,failureCount:1,openedAt:0,denyUntil:0,denialsInEpisode:0,updatedAt:now2},opened=!1;if(entry.state==="HALF_OPEN")entry.state="OPEN",entry.openedAt=now2,entry.denyUntil=now2+Math.max(1,input.halfOpenAfterMs),entry.denialsInEpisode=0;else if(entry.state!=="OPEN"&&entry.failureCount>=Math.max(1,input.threshold))entry.state="OPEN",entry.openedAt=now2,entry.denyUntil=now2+Math.max(1,input.halfOpenAfterMs),entry.denialsInEpisode=0,opened=!0;return entry.updatedAt=now2,spawnCircuits.set(key2,entry),evictExpired(now2),{entry,opened}}function assertDispatchSpawnCircuitAdmits(input){let now2=input.now??_internals180.now(),key2=entryKey2(input.sessionID,input.invocationID,input.actionDigest),entry=spawnCircuits.get(key2);if(!entry||entry.state==="CLOSED")return;if(entry.state==="OPEN"){if(now2<entry.denyUntil||entry.denialsInEpisode===0)throw entry.denialsInEpisode+=1,entry.updatedAt=now2,Error(`${SPAWN_CIRCUIT_DENIAL_CODE}: repeated dispatch failures for this action (${entry.failureCount} of ${Math.max(1,input.threshold)}). Read, diagnose, repair, rescope, abort, and handoff controls remain available; one recovery probe is admitted after the half-open interval.`);entry.state="HALF_OPEN",entry.updatedAt=now2;return}throw Error(`${SPAWN_CIRCUIT_DENIAL_CODE}: a recovery probe for this action is already in flight. Read, diagnose, repair, rescope, abort, and handoff controls remain available.`)}function noteDispatchSpawnSuccess(input){spawnCircuits.delete(entryKey2(input.sessionID,input.invocationID,input.actionDigest))}function spawnCircuitIsTaskTool(tool3){return isTaskToolId(tool3)}var MAX_TRACKED_SPAWN_CIRCUITS=500,SPAWN_CIRCUIT_TTL_MS=1800000,MAX_ARMED_DISPATCH_IDENTITIES=500,SPAWN_CIRCUIT_DENIAL_CODE="SPAWN PROTECTION CIRCUIT OPEN",spawnCircuits,armedIdentities,_internals180;var init_spawn_circuit=__esm(()=>{init_action_identity();init_normalize_tool_name();init_state2();spawnCircuits=new Map,armedIdentities=new Map;_internals180={now:()=>Date.now()}});import{createHash as createHash76}from"node:crypto";function readOwnDataValue(record3,key2){if(!record3||typeof record3!=="object"||Array.isArray(record3))return;try{let descriptor=Object.getOwnPropertyDescriptor(record3,key2);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function readFirstNormalizedOwnDataValue(record3,keys,normalize22){for(let key2 of keys){let value=readOwnDataValue(record3,key2);try{let normalized=normalize22(value);if(normalized!==void 0)return normalized}catch{}}return}function boundedActionString(value){if(typeof value!=="string")return;let trimmed=value.trim();if(trimmed.length===0)return;return trimmed}function boundedActionScalar(value){if(typeof value==="string")return boundedActionString(value);if(typeof value==="number"&&Number.isFinite(value))return value;if(typeof value==="boolean")return value;return}function boundedStableTarget(value){let normalized=boundedActionString(value);if(normalized===void 0||hasControlCharacters(normalized))return;return normalized}function boundedPathAlias(value){if(typeof value==="string"){let normalized=boundedActionString(value);return normalized===void 0?void 0:{value:normalized}}if(!Array.isArray(value))return;try{let paths=value.map((entry)=>boundedActionString(entry)).filter((entry)=>entry!==void 0);if(paths.length===0)return;let normalizedPaths=[...new Set(paths)].sort();if(normalizedPaths.length<=MAX_ACTION_PATH_PREFIX_ITEMS)return{value:normalizedPaths};let tailHasher=createHash76("sha256");tailHasher.update(`tail-count:${normalizedPaths.length-MAX_ACTION_PATH_PREFIX_ITEMS};`);for(let index=MAX_ACTION_PATH_PREFIX_ITEMS;index<normalizedPaths.length;index+=1){let pathValue=normalizedPaths[index];tailHasher.update(`entry-index:${index};length:${pathValue.length};`),tailHasher.update(pathValue)}let tailDigest=tailHasher.digest("hex").slice(0,16);return{value:normalizedPaths,tailDigest}}catch{return}}function gateActionArgs(tool3,args2){let projection={},normalizedTool=normalizeToolNameLowerCase(tool3??"");if(isTaskToolId(tool3)){let discriminator=gateDenialDiscriminator(tool3,args2);if(discriminator)projection.subagent_type=discriminator}let record3=args2,taskId=readFirstNormalizedOwnDataValue(record3,["taskId","task_id","id"],boundedActionScalar);if(taskId!==void 0)projection.taskId=taskId;if(normalizedTool==="update_task_status"){let status=readFirstNormalizedOwnDataValue(record3,["status"],boundedActionScalar);if(status!==void 0)projection.status=status}let phase=readFirstNormalizedOwnDataValue(record3,["phase","phase_number"],boundedActionScalar);if(phase!==void 0)projection.phase=phase;let mode=readFirstNormalizedOwnDataValue(record3,["mode","execution_mode"],boundedActionScalar);if(mode!==void 0)projection.mode=mode;let background=readFirstNormalizedOwnDataValue(record3,["background","run_in_background","runInBackground"],(value)=>{if(typeof value==="boolean")return value;if(typeof value!=="string")return;let normalized=value.trim().toLowerCase();return normalized==="true"?!0:normalized==="false"?!1:void 0});if(background!==void 0)projection.background=background;let workingDirectory=readFirstNormalizedOwnDataValue(record3,["working_directory","workingDirectory"],boundedActionScalar);if(workingDirectory!==void 0)projection.working_directory=workingDirectory;let scopeId=readFirstNormalizedOwnDataValue(record3,["scope_id","scopeId","scope"],boundedActionScalar);if(scopeId!==void 0)projection.scope_id=scopeId;let pathAlias=readFirstNormalizedOwnDataValue(record3,["filePath","file","path","paths","files"],boundedPathAlias);if(pathAlias!==void 0){if(projection.path=pathAlias.value,pathAlias.tailDigest!==void 0)projection.path_tail_digest=pathAlias.tailDigest}let stableTarget=readFirstNormalizedOwnDataValue(record3,STABLE_TARGET_KEYS,boundedStableTarget);if(stableTarget!==void 0)projection.url=stableTarget;return projection}function gateActionIdentity(tool3,args2){return createActionIdentity({tool:normalizeToolNameLowerCase(tool3??""),args:gateActionArgs(tool3,args2)})}function gateDenialDiscriminator(tool3,args2){try{if(!isTaskToolId(tool3??""))return"";let subagentType=readOwnDataValue(args2,"subagent_type");if(typeof subagentType!=="string"||subagentType.length===0)return"";let canonical=stripKnownSwarmPrefix(subagentType).trim().toLowerCase();if(canonical.length===0)return"";return canonical.slice(0,MAX_DISCRIMINATOR_LENGTH)}catch{return""}}function deriveGateDenialCode(message){if(typeof message!=="string")return UNCLASSIFIED_GATE_DENIAL_CODE;let colonIndex=message.indexOf(":");if(colonIndex<=0)return UNCLASSIFIED_GATE_DENIAL_CODE;let candidate=message.slice(0,colonIndex).trim();if(candidate.length===0||candidate.length>MAX_CODE_LENGTH)return UNCLASSIFIED_GATE_DENIAL_CODE;if(isGenericLegacyGateCode(candidate))return UNCLASSIFIED_GATE_DENIAL_CODE;return candidate}function isGenericLegacyGateCode(candidate){let normalized=candidate.trim().replace(/\s+/g," ").toUpperCase();return normalized==="BLOCKED"||normalized==="WRITE BLOCKED"||normalized.startsWith("[SANDBOX] BLOCKED")||normalized.startsWith("SANDBOX BLOCKED")||normalized.startsWith("SANDBOX_")}function boundedStructuredGateCode(value){if(typeof value!=="string")return;let candidate=value.trim();if(candidate.length===0||candidate.length>MAX_CODE_LENGTH||hasControlCharacters(candidate))return;if(isGenericLegacyGateCode(candidate))return;return candidate}function hasControlCharacters(value){for(let character of value){let code=character.charCodeAt(0);if(code<=31||code===127)return!0}return!1}function deriveStructuredGateDenialCode(err){for(let key2 of["gateCode","code"]){let candidate=boundedStructuredGateCode(readOwnDataValue(err,key2));if(candidate!==void 0)return candidate}return}function deriveGateDenialCause(err,message){return deriveStructuredGateDenialCode(err)??deriveGateDenialCode(message)}function isAbortLikeError(err){if(err&&typeof err==="object"){if(err.name==="AbortError")return!0;let message=err.message;if(typeof message==="string"&&message.startsWith("AbortError"))return!0}return!1}function gateDenialWarnText(count,code){if(code===UNCLASSIFIED_GATE_DENIAL_CODE)return`
|
|
3756
3756
|
[swarm] This is denial #${count} with no stable cause classification. Do NOT retry the same dispatch; diagnose the current blocker and present it to the user if it persists.`;return`
|
|
3757
3757
|
[swarm] This is denial #${count} with the same cause (${code}). Do NOT retry the same dispatch; fix the named cause or present the blocker to the user.`}function gateDenialStopText(count,code,tool3,actionPattern=tool3){let safePattern=actionPattern.slice(0,MAX_ACTION_STRING_LENGTH).replace(/[^a-zA-Z0-9_.:-]/g,"_");return`
|
|
3758
3758
|
[swarm] GATE DENIAL LOOP: ${count} consecutive ${code} denial(s) for action ${safePattern}. Do not retry this exact action unchanged. Diagnose the current cause, then repair or rescope it; otherwise handoff, abort, or exit Full-Auto.`}function noteGateDenial(sessionID,tool3,err,options,args2){try{if(options?.enabled===!1)return NOT_COUNTED;if(isAbortLikeError(err))return NOT_COUNTED;if(!err||typeof err!=="object"||typeof err.message!=="string")return NOT_COUNTED;let errorObject=err,code=deriveGateDenialCause(err,errorObject.message);if(code===SPAWN_CIRCUIT_DENIAL_CODE)return NOT_COUNTED;let originalMessage=errorObject.message,normalizedTool=normalizeToolNameLowerCase(tool3??""),session=ensureAgentSession(sessionID),invocationID=session.activeInvocationId??0,action=gateActionIdentity(tool3,args2),generationToken=armActionCircuitAttempt(sessionID,invocationID,action.digest),warnThreshold=normalizeThreshold(options?.warnThreshold,DEFAULT_GATE_DENIAL_WARN_THRESHOLD),stopThreshold=normalizeThreshold(options?.stopThreshold,DEFAULT_GATE_DENIAL_STOP_THRESHOLD),circuitKind=`policy.gate_denial:${code}`,{entry}=noteActionCircuitFailure({sessionID,invocationID,actionDigest:action.digest,circuitKind,signal:originalMessage,generationToken,hardStopThreshold:code===UNCLASSIFIED_GATE_DENIAL_CODE?Number.MAX_SAFE_INTEGER:stopThreshold});if(!entry)return NOT_COUNTED;let count=entry.count,warned=count>=warnThreshold,stopped=count>=stopThreshold&&code!==UNCLASSIFIED_GATE_DENIAL_CODE;if(!warned&&!stopped)return{code,count,warned:!1,stopped:!1,decorated:!1};let appended="";if(warned)appended+=gateDenialWarnText(count,code);if(stopped)appended+=gateDenialStopText(count,code,normalizedTool,action.pattern);let decorated=!1;try{errorObject.message=originalMessage+appended,decorated=errorObject.message!==originalMessage}catch{decorated=!1}if(stopped){let stopText=gateDenialStopText(count,code,normalizedTool,action.pattern),advisoryKey=`[swarm:gate-denial-loop:${code}:${action.digest.slice(0,12)}]`;try{pushAdvisory(session,`${advisoryKey}${stopText}`,{dedupeKey:advisoryKey})}catch{}try{telemetry.gateDenialLoop(sessionID,normalizedTool,code,count)}catch{}}return{code,count,warned,stopped,decorated}}catch{return NOT_COUNTED}}function normalizeThreshold(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function resetGateDenialStreaks(sessionID,tool3,args2){try{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0,action=gateActionIdentity(tool3,args2);clearActionCircuit(sessionID,invocationID,action.digest,{reason:"success"})}catch{}}var DEFAULT_GATE_DENIAL_WARN_THRESHOLD=3,DEFAULT_GATE_DENIAL_STOP_THRESHOLD=5,MAX_CODE_LENGTH=64,MAX_ACTION_STRING_LENGTH=128,MAX_ACTION_PATH_PREFIX_ITEMS=64,STABLE_TARGET_KEYS,UNCLASSIFIED_GATE_DENIAL_CODE="UNCLASSIFIED",MAX_DISCRIMINATOR_LENGTH=64,NOT_COUNTED,_test_exports4;var init_gate_denial_tracker=__esm(()=>{init_schema();init_spawn_circuit();init_action_circuit();init_action_identity();init_state2();init_telemetry();init_normalize_tool_name();STABLE_TARGET_KEYS=["url","uri","source_url","pr_url"];NOT_COUNTED=Object.freeze({code:UNCLASSIFIED_GATE_DENIAL_CODE,count:0,warned:!1,stopped:!1,decorated:!1});_test_exports4={MAX_TRACKED_DENIAL_STREAKS:_test_exports.MAX_TRACKED_ACTION_CIRCUITS,GATE_DENIAL_TTL_MS:_test_exports.ACTION_CIRCUIT_TTL_MS,MAX_CODE_LENGTH,MAX_DISCRIMINATOR_LENGTH,streakCount:()=>_test_exports.size(),peekStreak:(sessionID,tool3,code,target=void 0)=>peekActionCircuitCount(sessionID,getAgentSession(sessionID)?.activeInvocationId??0,gateActionIdentity(tool3,typeof target==="string"?{subagent_type:target}:target).digest,`policy.gate_denial:${code}`),expireStreak:(sessionID,tool3,code,target=void 0)=>{expireActionCircuit(sessionID,getAgentSession(sessionID)?.activeInvocationId??0,gateActionIdentity(tool3,typeof target==="string"?{subagent_type:target}:target).digest,`policy.gate_denial:${code}`)}}});import*as fs124 from"node:fs/promises";import*as path222 from"node:path";function isSensitiveKey(key2){let lower=key2.toLowerCase();return SENSITIVE_SUBSTRINGS.some((substr)=>lower.includes(substr))}async function truncateTrajectoryFile(filePath,maxLines){try{let lines=(await fs124.readFile(filePath,"utf-8")).split(`
|
|
3759
3759
|
`).filter((line)=>line.trim().length>0);if(lines.length<=maxLines)return;let keepCount=Math.floor(maxLines/2),keptLines=lines.slice(-keepCount);await fs124.writeFile(filePath,`${keptLines.join(`
|
|
3760
3760
|
`)}
|
|
3761
|
-
`,"utf-8"),invalidateCachedArtifact(filePath)}catch{}}function deriveAction(tool3){let toolLower=normalizeToolNameLowerCase(tool3??"");if(
|
|
3761
|
+
`,"utf-8"),invalidateCachedArtifact(filePath)}catch{}}function deriveAction(tool3){let toolLower=normalizeToolNameLowerCase(tool3??"");if(isTaskToolId(tool3))return"delegate";if(["write","edit","apply_patch","swarm_apply_patch"].includes(toolLower))return"edit";if(["read","glob","grep","search"].includes(toolLower))return"read";if(["bash","shell"].includes(toolLower))return"execute";if(toolLower==="test_runner")return"test";return"tool_use"}function fnv1aHex(text){let hash5=2166136261;for(let i=0;i<text.length;i++)hash5^=text.charCodeAt(i),hash5=Math.imul(hash5,16777619)>>>0;return hash5.toString(16).padStart(8,"0")}function redactCommandSecrets(text){let redacted=redactSecrets(text).replace(URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@"),beginMarker=redacted.search(/-----BEGIN [A-Z ]*PRIVATE KEY-----/);return beginMarker===-1?redacted:`${redacted.slice(0,beginMarker)}[REDACTED:private_key_block]`}function normalizeCommandTarget(command){let normalized=command.trim().replace(/\s+/g," "),bounded=normalized.length>MAX_COMMAND_TARGET_LENGTH?`${normalized.slice(0,MAX_COMMAND_TARGET_LENGTH-3)}...`:normalized,redacted=redactCommandSecrets(bounded);if(redacted===bounded)return redacted;let prefix=`#${fnv1aHex(bounded)} `,room=MAX_COMMAND_TARGET_LENGTH-prefix.length,body=redacted.length>room?`${redacted.slice(0,room-3)}...`:redacted;return`${prefix}${body}`}function extractTarget(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let subagentType=args2.subagent_type;if(typeof subagentType==="string"&&subagentType.length>0)return subagentType}let targetFields=["filePath","path","file","target"];for(let field of targetFields){let value=args2[field];if(typeof value==="string"&&value.length>0)return value}let toolLower=tool3.toLowerCase();if(toolLower==="bash"||toolLower==="shell"||toolLower==="execute"||toolLower==="command"){let command=args2.command;if(typeof command==="string"&&command.trim().length>0)return normalizeCommandTarget(command);let description=args2.description;if(typeof description==="string"&&description.length>0){let safeDescription=redactCommandSecrets(description.slice(0,REDACTION_SCAN_WINDOW));return safeDescription.length>30?`${safeDescription.slice(0,27)}...`:safeDescription}let argsStr=args2.args;if(typeof argsStr==="string"&&argsStr.trim().length>0)return normalizeCommandTarget(argsStr)}return""}function extractIntent(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let{prompt,description}=args2,safeText=redactCommandSecrets((typeof prompt==="string"?prompt:typeof description==="string"?description:"").slice(0,REDACTION_SCAN_WINDOW));if(safeText.length>100)return`${safeText.slice(0,97)}...`;return safeText}let intentFields=["description","task"];for(let field of intentFields){let value=args2[field];if(typeof value==="string"&&value.length>0){let safe=redactCommandSecrets(value.slice(0,REDACTION_SCAN_WINDOW));return safe.length>200?`${safe.slice(0,197)}...`:safe}}return""}function mapResult(verdict){if(verdict==="success")return"success";if(verdict==="failure")return"failure";return"pending"}function stepSeedKey(sessionId,directory){return`${trajectoryStepGeneration()}:${compositeSessionKey(directory,sessionId)}`}function markStepSeedGate(gateKey){if(stepSeedGate.has(gateKey))return;while(stepSeedGate.size>=MAX_STEP_SEED_GATE_SESSIONS){let oldest=stepSeedGate.keys().next().value;if(oldest===void 0)break;stepSeedGate.delete(oldest)}stepSeedGate.set(gateKey,!0)}async function ensureSessionStepSeeded(sessionId,directory){let gateKey=stepSeedKey(sessionId,directory);if(stepSeedGate.has(gateKey))return;let inFlight=stepSeedPromises.get(gateKey);if(inFlight!==void 0){await inFlight;return}let promise3=(async()=>{let lastStep=await getCurrentStep(sessionId,directory);if(lastStep>0)seedTrajectoryStepCounter(sessionId,directory,lastStep);markStepSeedGate(gateKey)})().catch(()=>{markStepSeedGate(gateKey)}).finally(()=>{stepSeedPromises.delete(gateKey)});stepSeedPromises.set(gateKey,promise3),await promise3}function invalidateStepSeedGate(sessionId){if(sessionId===void 0){stepSeedGate.clear();return}let suffix=sessionKeySuffix(sessionId);for(let gateKey of stepSeedGate.keys())if(gateKey.endsWith(suffix))stepSeedGate.delete(gateKey)}function createTrajectoryLoggerHook(config3,_directory2){let enabled=config3.enabled??!0,maxLines=config3.max_lines??500;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID;if(consumeDeniedCallMarker(sessionId,input.callID)){callStartTimes.delete(`${sessionId}:${input.callID}`);return}let session=swarmState.agentSessions.get(sessionId);if(!session?.delegationActive)return;let taskId=session.currentTaskId;if(!taskId)return;let startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes.get(startKey)??Date.now();callStartTimes.delete(startKey);let elapsed_ms=Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionId)??session?.agentName??"unknown",args_summary=summarizeArgs(input.args,200),verdict=deriveVerdict(output);await ensureSessionStepSeeded(sessionId,_directory2);let step=nextTrajectoryStep(sessionId,_directory2),action=deriveAction(input.tool),target=extractTarget(input.tool,input.args),intent=extractIntent(input.tool,input.args),result=mapResult(verdict),entry={step,agent:agentName,action,target,intent,timestamp:new Date().toISOString(),result,tool:input.tool,args_summary,verdict,elapsed_ms},sanitized=sanitizeTaskId2(taskId),relativePath2=path222.join("evidence",sanitized,"trajectory.jsonl"),trajectoryPath=validateSwarmPath(_directory2,relativePath2);try{await fs124.mkdir(path222.dirname(trajectoryPath),{recursive:!0});let line=`${JSON.stringify(entry)}
|
|
3762
3762
|
`;await fs124.appendFile(trajectoryPath,line,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}try{await appendTrajectoryEntry(sessionId,entry,_directory2,maxLines)}catch{}}}}function markDeniedCall(sessionId,callID){if(!callID)return;let now2=Date.now();for(let[key3,expiresAt]of deniedCallMarkers)if(expiresAt<=now2)deniedCallMarkers.delete(key3);let key2=`${sessionId}:${callID}`;deniedCallMarkers.delete(key2),deniedCallMarkers.set(key2,now2+DENIED_CALL_TTL_MS);while(deniedCallMarkers.size>MAX_DENIED_CALL_MARKERS){let oldest=deniedCallMarkers.keys().next().value;if(oldest===void 0||oldest===key2)break;deniedCallMarkers.delete(oldest)}}function consumeDeniedCallMarker(sessionId,callID){if(!callID)return!1;let key2=`${sessionId}:${callID}`,expiresAt=deniedCallMarkers.get(key2);if(expiresAt===void 0)return!1;return deniedCallMarkers.delete(key2),expiresAt>Date.now()}async function recordDeniedToolCall(sessionID,input,errorMessage2,directory,options){try{let session=swarmState.agentSessions.get(sessionID);if(!session?.delegationActive)return;let maxLines=options?.maxLines??500,startKey=`${sessionID}:${input.callID}`,startTime=callStartTimes.get(startKey);if(startTime!==void 0)callStartTimes.delete(startKey);let elapsed_ms=startTime===void 0?0:Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionID)??session.agentName??"unknown",code=deriveGateDenialCode(errorMessage2);await ensureSessionStepSeeded(sessionID,directory);let entry={step:nextTrajectoryStep(sessionID,directory),agent:agentName,action:deriveAction(input.tool),target:extractTarget(input.tool,input.args),intent:`denied: ${code}`,timestamp:new Date().toISOString(),result:"failure",tool:input.tool,args_summary:summarizeArgs(input.args,200),verdict:"failure",elapsed_ms,callID:input.callID};markDeniedCall(sessionID,input.callID);try{await appendTrajectoryEntry(sessionID,entry,directory,maxLines)}catch{}let taskId=session.currentTaskId;if(!taskId)return;try{let relativePath2=path222.join("evidence",sanitizeTaskId2(taskId),"trajectory.jsonl"),trajectoryPath=validateSwarmPath(directory,relativePath2);await fs124.mkdir(path222.dirname(trajectoryPath),{recursive:!0}),await fs124.appendFile(trajectoryPath,`${JSON.stringify(entry)}
|
|
3763
3763
|
`,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}}catch{}}function clearTrajectoryStep(sessionId){clearTrajectoryStepCounters(sessionId),invalidateStepSeedGate(sessionId)}function summarizeArgs(args2,maxLength){if(!args2||Object.keys(args2).length===0)return"";let summaries=[];for(let[key2,value]of Object.entries(args2)){if(SENSITIVE_FIELDS.has(key2)||isSensitiveKey(key2)){summaries.push(`${key2}:[REDACTED]`);continue}if(value===null||value===void 0)summaries.push(`${key2}:null`);else if(typeof value==="string"){let window2=value.slice(0,REDACTION_SCAN_WINDOW),redacted=redactCommandSecrets(window2),truncated=redacted.length>50?`${redacted.slice(0,50)}...`:redacted;summaries.push(`${key2}:"${truncated}"`)}else if(typeof value==="number"||typeof value==="boolean")summaries.push(`${key2}:${String(value)}`);else if(Array.isArray(value)){let itemSummary=value.length>3?`${value.slice(0,3).map(String).join(",")},...(+${value.length-3})`:value.map(String).join(",");summaries.push(`${key2}:[${itemSummary}]`)}else if(typeof value==="object"){let keys=Object.keys(value);summaries.push(`${key2}:{${keys.join(",")}}`)}else summaries.push(`${key2}:${typeof value}`)}let summary=summaries.join(" ");return summary.length>maxLength?`${summary.slice(0,maxLength-3)}...`:summary}function deriveVerdict(output){if(output.metadata&&typeof output.metadata==="object"&&!Array.isArray(output.metadata)){let meta3=output.metadata;if(typeof meta3.verdict==="string"&&meta3.verdict.length>0)return meta3.verdict;if(meta3.success===!1||meta3.passed===!1)return"failure";if(meta3.success===!0||meta3.passed===!0)return"success"}let outputStr=String(output.output??"");if(outputStr.startsWith("Error:")||outputStr.startsWith("error:")||outputStr.startsWith("Error: "))return"failure";return"success"}var callStartTimes,SENSITIVE_FIELDS,SENSITIVE_SUBSTRINGS,URL_CREDENTIALS_PATTERN,REDACTION_SCAN_WINDOW=4096,MAX_COMMAND_TARGET_LENGTH=200,stepSeedGate,MAX_STEP_SEED_GATE_SESSIONS=500,stepSeedPromises,MAX_DENIED_CALL_MARKERS=500,DENIED_CALL_TTL_MS=300000,deniedCallMarkers;var init_trajectory_logger=__esm(()=>{init_manager2();init_redaction();init_trajectory_store();init_state2();init_canonical_root();init_swarm_artifact_cache();init_gate_denial_tracker();init_normalize_tool_name();init_trajectory_step_state();init_utils2();callStartTimes=new Map,SENSITIVE_FIELDS=new Set(["password","token","secret","api_key","apikey","authorization","access_token","refresh_token","private_key","secret_key","credential","auth","bearer","x-api-key","session_id","cookie"]),SENSITIVE_SUBSTRINGS=["key","secret","token","password","auth","credential","private","certificate","bearer","session","cookie"];URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g;stepSeedGate=new Map,stepSeedPromises=new Map;deniedCallMarkers=new Map});import{createHash as createHash77,randomBytes as randomBytes7}from"node:crypto";import*as fs125 from"node:fs";import*as path223 from"node:path";function pendingPath(directory){return validateSwarmPath(directory,PENDING_PURGE_PATH)}function resolveCandidates(scopeTarget,extra){if(extra?.candidates&&extra.candidates.length>0)return{kind:"set",candidates:extra.candidates};return{kind:"single",candidates:[{path:scopeTarget,reason:"operator-requested"}]}}function scopeDigest(kind,candidates){let paths=candidates.map((c)=>path223.resolve(c.path)).sort().join(`
|
|
3764
3764
|
`);return createHash77("sha256").update(`${kind}\x00${paths}`).digest("hex")}function mintToken(digest4){return createHash77("sha256").update(`${digest4}:${_internals181.randomBytes(16).toString("hex")}`).digest("hex").slice(0,24)}function readPending(directory){try{let raw=_internals181.readFileSync(pendingPath(directory),"utf-8"),parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||typeof parsed.scopeDigest!=="string"||typeof parsed.confirmToken!=="string"||typeof parsed.createdAt!=="number")return null;if(!Number.isFinite(parsed.createdAt))return null;if(parsed.createdAt>_internals181.now()+60000)return null;if(_internals181.now()-parsed.createdAt>PENDING_PURGE_TTL_MS)return null;return{schemaVersion:1,scopeDigest:parsed.scopeDigest,confirmToken:parsed.confirmToken,createdAt:parsed.createdAt}}catch{return null}}function writePending(directory,record3){_internals181.atomicWriteSwarmFileSync(pendingPath(directory),JSON.stringify(record3,null,2))}function previewDestructivePurge(scopeTarget,projectRoot,extra){let scope=resolveCandidates(scopeTarget,extra);return{previewLines:[`Destructive purge preview (${scope.candidates.length} candidate(s)) for ${projectRoot}:`,...scope.candidates.map((c)=>` - ${c.path} (${c.reason})`),"Uncommitted work inside these directories will be DESTROYED."],counts:{total:scope.candidates.length},optionLabel:"--confirm=<token>",confirmToken:"<run again to receive your confirm token>",candidates:scope.candidates}}function issueConfirmToken(scopeTarget,projectRoot,extra){let scope=resolveCandidates(scopeTarget,extra),digest4=scopeDigest(scope.kind,scope.candidates),token=mintToken(digest4);return writePending(projectRoot,{schemaVersion:1,scopeDigest:digest4,confirmToken:token,createdAt:_internals181.now()}),token}function executeDestructivePurge(scopeTarget,projectRoot,token,extra){let pending=readPending(projectRoot);if(!pending)return{ok:!1,reason:"no pending purge for this scope (expired, overwritten, or already executed)"};let scope=resolveCandidates(scopeTarget,extra),digest4=scopeDigest(scope.kind,scope.candidates);if(pending.confirmToken!==token)return{ok:!1,reason:"confirm token mismatch"};if(pending.scopeDigest!==digest4)return{ok:!1,reason:"purge scope changed since the token was issued — re-run the preview and confirm the new token"};let purged=[];for(let candidate of scope.candidates){if(!_internals181.existsSync(candidate.path))continue;try{_internals181.rmSync(candidate.path,{recursive:!0,force:!0}),purged.push(candidate.path)}catch(error93){try{_internals181.rmSync(pendingPath(projectRoot),{force:!0})}catch{}return{ok:!1,reason:`candidate ${candidate.path} could not be purged: ${error93 instanceof Error?error93.message:String(error93)}`}}}try{_internals181.rmSync(pendingPath(projectRoot),{force:!0})}catch(error93){log(`[destructive-purge] could not consume pending record: ${error93 instanceof Error?error93.message:String(error93)}`)}return{ok:!0,purged}}var PENDING_PURGE_PATH="pending-purge.json",PENDING_PURGE_TTL_MS=900000,_internals181;var init_destructive_purge=__esm(()=>{init_utils2();init_atomic_write();init_logger();_internals181={readFileSync:fs125.readFileSync,rmSync:fs125.rmSync.bind(fs125),existsSync:fs125.existsSync.bind(fs125),atomicWriteSwarmFileSync,now:()=>Date.now(),randomBytes:randomBytes7}});import*as fs126 from"node:fs";import*as path224 from"node:path";function errorMessage2(err){if(err instanceof Error)return err.message;return String(err)}async function releaseKnowledgeGateObligations(directory,sessionID){let results=[],live;try{live=await _internals182.queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0})}catch(err){return[`⚠️ Knowledge gate state not cleared: receipt authority unavailable (${errorMessage2(err)})`]}if(!live.ok)return[`⚠️ Knowledge gate state not cleared: receipt authority unavailable (${live.code})`];let pending=live.memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.application_marker&&membership.gate_release?.membership_event_id!==membership.membership_event_id);if(pending.length===0)return["⏭️ No pending knowledge gate obligations for this session"];let byTrace=new Map;for(let membership of pending){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}let committedCount=0,releasedPairs=[];for(let[traceId,group]of byTrace){let committed=await _internals182.commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:group.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_session_reset_release",reason:"/swarm reset-session operator escape (#2398)"}))});if(!committed.ok){results.push(`⚠️ Failed to release knowledge gate obligations on trace ${sanitizeDiagnosticText(traceId,64)}: ${committed.code}`);continue}committedCount+=committed.committed.length;for(let item of committed.committed)releasedPairs.push(`${traceId}/${item.entry_id}`);if(committed.rejected.length>0)results.push(`⚠️ Partially released trace ${sanitizeDiagnosticText(traceId,64)}: ${committed.rejected.map((item)=>item.reason).join("; ")}`)}if(committedCount===0)return results;if(committedCount<pending.length)results.push(`⚠️ Released ${committedCount} of ${pending.length} pending knowledge gate obligation(s) — ${pending.length-committedCount} not released; see warnings above`);else results.push(`✅ Released ${committedCount} pending knowledge gate obligation(s) for this session`);try{appendCoreEventSync(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_session_reset_clear",sessionID,released_pairs:releasedPairs})}catch{}return results}async function handleResetSessionCommand(directory,args2,sessionID){let results=[],snapshotResetGuard;try{if(snapshotResetGuard=await _internals182.beginSnapshotCoordinationReset(directory),snapshotResetGuard.closeError){if(snapshotResetGuard.priorUnsettled)return results.push(`❌ Snapshot coordination close timed out; reset aborted to avoid racing an in-flight initializer: ${errorMessage2(snapshotResetGuard.closeError)}`),snapshotResetGuard.release(),results.join(`
|
|
@@ -6018,17 +6018,25 @@ Do not pad responses with hedging when confidence is HIGH. A precise answer is m
|
|
|
6018
6018
|
- Mark every finding with its individual confidence level
|
|
6019
6019
|
- Do not fabricate URLs — cite "source: not found" rather than inventing a link
|
|
6020
6020
|
- Cross-platform and version-specific constraints must be flagged explicitly
|
|
6021
|
-
`});function encodeDirectiveCorrelationId(value){return encodeURIComponent(value)}function decodeDirectiveCorrelationId(token){if(!CORRELATION_TOKEN_PATTERN.test(token))return null;try{let decoded=decodeURIComponent(token);return decoded.length>0&&decoded.length<=512?decoded:null}catch{return null}}function renderOptionalText(value){return JSON.stringify(value)}function parseOptionalText(value){try{let parsed=JSON.parse(value);return typeof parsed==="string"?parsed:void 0}catch{return}}function
|
|
6021
|
+
`});function encodeDirectiveCorrelationId(value){return encodeURIComponent(value)}function decodeDirectiveCorrelationId(token){if(!CORRELATION_TOKEN_PATTERN.test(token))return null;try{let decoded=decodeURIComponent(token);return decoded.length>0&&decoded.length<=512?decoded:null}catch{return null}}function renderOptionalText(value){return JSON.stringify(value)}function renderTruncatedOptionalText(value){let truncated=value.length>400?`${value.slice(0,400)}...`:value;return renderOptionalText(truncated).replace(/<\//g,"<\\/")}function parseOptionalText(value){try{let parsed=JSON.parse(value);return typeof parsed==="string"?parsed:void 0}catch{return}}function renderDirectiveLines(d){let lines=[`- trace_id: ${encodeDirectiveCorrelationId(d.trace_id)}`,` entry_id: ${encodeDirectiveCorrelationId(d.entry_id)}`,` session_id: ${encodeDirectiveCorrelationId(d.session_id)}`];if(d.cohort_id)lines.push(` cohort_id: ${encodeDirectiveCorrelationId(d.cohort_id)}`);if(d.source_link_id)lines.push(` source_link_id: ${encodeDirectiveCorrelationId(d.source_link_id)}`);if(d.prior_terminal_outcome)lines.push(` prior_terminal_outcome: ${d.prior_terminal_outcome}`);if(d.prior_terminal_event_id)lines.push(` prior_terminal_event_id: ${encodeDirectiveCorrelationId(d.prior_terminal_event_id)}`);if(lines.push(` priority: ${d.priority}`),d.lesson)lines.push(` lesson: ${renderTruncatedOptionalText(d.lesson)}`);if(d.verification_predicate)lines.push(` verification_predicate: ${renderTruncatedOptionalText(d.verification_predicate)}`);return lines}function buildDirectiveComplianceBlock(directives,charBudget){if(directives.length===0)return null;let tailReserve=Buffer.byteLength(`</directives_to_verify>
|
|
6022
|
+
|
|
6023
|
+
DIRECTIVE_COMPLIANCE: one line per listed obligation. Copy the encoded trace_id and entry_id tokens exactly from the DIRECTIVES TO VERIFY block. Use exactly one of:
|
|
6024
|
+
VERIFIED:<trace_id>:<entry_id> evidence=<file:line | predicate_passed>
|
|
6025
|
+
VIOLATED:<trace_id>:<entry_id> evidence=<file:line | failing_predicate>
|
|
6026
|
+
N/A:<trace_id>:<entry_id> reason=<why it does not apply to this change>
|
|
6027
|
+
Every listed trace_id + entry_id pair MUST appear exactly once in your verdicts. If a directive carries a verification_predicate, you MUST run it and report predicate_passed / failing_predicate as the evidence. Omitting a listed CRITICAL pair is itself a VIOLATED verdict.`,"utf-8")+256,effectiveBudget=Math.max(0,Math.min(charBudget??24000,24000)-tailReserve),sorted2=[...directives].sort((a,b)=>{let pr=(PRIORITY_RANK[a.priority]??2)-(PRIORITY_RANK[b.priority]??2);if(pr!==0)return pr;if(a.entry_id!==b.entry_id)return a.entry_id<b.entry_id?-1:1;return a.trace_id<b.trace_id?-1:a.trace_id>b.trace_id?1:0}),lines=[];lines.push("<directives_to_verify>"),lines.push("Produce a DIRECTIVE_COMPLIANCE verdict for EVERY trace_id + entry_id pair below. Copy the encoded tokens exactly and run any verification_predicate provided.");let usedBytes=Buffer.byteLength(lines.join(`
|
|
6028
|
+
`),"utf-8"),omittedNonCritical=[],criticalOverflowCount=0;for(let d of sorted2){let entryLines=renderDirectiveLines(d),entryBytes=Buffer.byteLength(entryLines.join(`
|
|
6029
|
+
`),"utf-8")+1;if(d.priority==="critical"){if(lines.push(...entryLines),usedBytes+=entryBytes,usedBytes>effectiveBudget)criticalOverflowCount+=1;continue}if(usedBytes+entryBytes>effectiveBudget){omittedNonCritical.push(d.entry_id);continue}lines.push(...entryLines),usedBytes+=entryBytes}if(criticalOverflowCount>0)lines.push(`critical overflow: ${criticalOverflowCount} critical directive(s) rendered beyond the char budget`);if(omittedNonCritical.length>0)lines.push(`(+${omittedNonCritical.length} non-critical directive(s) omitted this phase; they remain live and will resurface)`);return lines.push("</directives_to_verify>"),lines.push(""),lines.push(`DIRECTIVE_COMPLIANCE: one line per listed obligation. Copy the encoded trace_id and entry_id tokens exactly from the DIRECTIVES TO VERIFY block. Use exactly one of:
|
|
6022
6030
|
VERIFIED:<trace_id>:<entry_id> evidence=<file:line | predicate_passed>
|
|
6023
6031
|
VIOLATED:<trace_id>:<entry_id> evidence=<file:line | failing_predicate>
|
|
6024
6032
|
N/A:<trace_id>:<entry_id> reason=<why it does not apply to this change>
|
|
6025
|
-
Every listed trace_id + entry_id pair MUST appear exactly once
|
|
6033
|
+
Every listed trace_id + entry_id pair MUST appear exactly once in your verdicts. If a directive carries a verification_predicate, you MUST run it and report predicate_passed / failing_predicate as the evidence. Omitting a listed CRITICAL pair is itself a VIOLATED verdict.`),lines.join(`
|
|
6026
6034
|
`)}function parseDirectivesToVerifyBlock(text){if(!text||!text.includes("<directives_to_verify>"))return[];let start=text.indexOf("<directives_to_verify>"),end=text.indexOf("</directives_to_verify>",start),body=end>=0?text.slice(start,end):text.slice(start),out=[],current=null,flush=()=>{if(current&&typeof current.trace_id==="string"&&typeof current.entry_id==="string"&&typeof current.session_id==="string"&&Boolean(current.prior_terminal_outcome)===Boolean(current.prior_terminal_event_id)&¤t.priority)out.push(current);current=null};for(let line of body.split(`
|
|
6027
|
-
`)){let traceM=/^- trace_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(traceM){flush();let traceId=decodeDirectiveCorrelationId(traceM[1]);current=traceId?{trace_id:traceId}:null;continue}if(!current)continue;let entryM=/^\s+entry_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(entryM){let entryId=decodeDirectiveCorrelationId(entryM[1]);if(entryId)current.entry_id=entryId;continue}let sessionM=/^\s+session_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(sessionM){let sessionId=decodeDirectiveCorrelationId(sessionM[1]);if(sessionId)current.session_id=sessionId;continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM){current.priority=prM[1];continue}let cohortM=/^\s+cohort_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(cohortM){let cohortId=decodeDirectiveCorrelationId(cohortM[1]);if(cohortId)current.cohort_id=cohortId;continue}let sourceLinkM=/^\s+source_link_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(sourceLinkM){let sourceLinkId=decodeDirectiveCorrelationId(sourceLinkM[1]);if(sourceLinkId)current.source_link_id=sourceLinkId;continue}
|
|
6035
|
+
`)){let traceM=/^- trace_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(traceM){flush();let traceId=decodeDirectiveCorrelationId(traceM[1]);current=traceId?{trace_id:traceId}:null;continue}if(!current)continue;let entryM=/^\s+entry_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(entryM){let entryId=decodeDirectiveCorrelationId(entryM[1]);if(entryId)current.entry_id=entryId;continue}let sessionM=/^\s+session_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(sessionM){let sessionId=decodeDirectiveCorrelationId(sessionM[1]);if(sessionId)current.session_id=sessionId;continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM){current.priority=prM[1];continue}let cohortM=/^\s+cohort_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(cohortM){let cohortId=decodeDirectiveCorrelationId(cohortM[1]);if(cohortId)current.cohort_id=cohortId;continue}let sourceLinkM=/^\s+source_link_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(sourceLinkM){let sourceLinkId=decodeDirectiveCorrelationId(sourceLinkM[1]);if(sourceLinkId)current.source_link_id=sourceLinkId;continue}let priorOutcomeM=/^\s+prior_terminal_outcome:\s*(violated|contradicted)\s*$/.exec(line);if(priorOutcomeM){current.prior_terminal_outcome=priorOutcomeM[1];continue}let priorEventM=/^\s+prior_terminal_event_id:\s*([^:\s]{1,512})\s*$/.exec(line);if(priorEventM){let eventId=decodeDirectiveCorrelationId(priorEventM[1]);if(eventId)current.prior_terminal_event_id=eventId;continue}let predM=/^\s+verification_predicate:\s*("(?:[^"\\]|\\.)*")\s*$/.exec(line);if(predM){current.verification_predicate=parseOptionalText(predM[1]);continue}let lessonM=/^\s+lesson:\s*("(?:[^"\\]|\\.)*")\s*$/.exec(line);if(lessonM)current.lesson=parseOptionalText(lessonM[1])}return flush(),out}var DIRECTIVE_COMPLIANCE_HARD_CHAR_CAP=24000,DIRECTIVE_COMPLIANCE_DEFAULT_CHAR_BUDGET=24000,DIRECTIVE_COMPLIANCE_OUTPUT_SPEC=`DIRECTIVE_COMPLIANCE: one line per listed obligation. Copy the encoded trace_id and entry_id tokens exactly from the DIRECTIVES TO VERIFY block. Use exactly one of:
|
|
6028
6036
|
VERIFIED:<trace_id>:<entry_id> evidence=<file:line | predicate_passed>
|
|
6029
6037
|
VIOLATED:<trace_id>:<entry_id> evidence=<file:line | failing_predicate>
|
|
6030
6038
|
N/A:<trace_id>:<entry_id> reason=<why it does not apply to this change>
|
|
6031
|
-
Every listed trace_id + entry_id pair MUST appear exactly once
|
|
6039
|
+
Every listed trace_id + entry_id pair MUST appear exactly once in your verdicts. If a directive carries a verification_predicate, you MUST run it and report predicate_passed / failing_predicate as the evidence. Omitting a listed CRITICAL pair is itself a VIOLATED verdict.`,PRIORITY_RANK,CORRELATION_TOKEN_PATTERN;var init_reviewer_directive_compliance=__esm(()=>{PRIORITY_RANK={critical:0,high:1,medium:2,low:3},CORRELATION_TOKEN_PATTERN=/^[^:\s]{1,512}$/});function withStructuredFindingsContract(prompt){return prompt.replace("VERBOSITY CONTROL: Token budget ≤800 tokens. TRIVIAL APPROVED = 2-3 lines. COMPLEX REJECTED = full output. Scale response to complexity.",STRUCTURED_VERBOSITY).replace("ISSUES: list with line numbers, grouped by CHECK dimension","ISSUES: none (see structured findings JSON)").replace("Use INFO only inside ISSUES for non-blocking suggestions. RISK reflects the highest blocking severity, so it never uses INFO.",STRUCTURED_FINDINGS_CONTRACT).replace("- Only flag real issues, not theoretical",["- Only flag real issues, not theoretical. To flag an issue, identify the other parts of the code that are provably affected; do not speculate about hypothetical callers or states.","- If there is no finding the author would definitely want to fix, prefer outputting no findings."].join(`
|
|
6032
6040
|
`))}function createReviewerAgent(model,customPrompt,customAppendPrompt,structuredFindings=!1){let prompt=structuredFindings?withStructuredFindingsContract(LEGACY_REVIEWER_PROMPT):LEGACY_REVIEWER_PROMPT;return prompt=resolvePrompt(prompt,customPrompt,customAppendPrompt),{name:"reviewer",description:"Code reviewer. Verifies correctness, finds vulnerabilities, and checks quality across architect-specified dimensions.",config:{model,temperature:0.1,prompt,tools:{write:!1,edit:!1,patch:!1}}}}var REVIEWER_MEMORY_OUTCOME_GUIDANCE="Use `swarm_memory_outcome` after evaluating recalled memory or a graph answer. When overturning a memory-backed claim, record `corrected` and include the correction text and relevant file/symbol anchors.",SECURITY_CATEGORIES,LEGACY_REVIEWER_PROMPT,STRUCTURED_VERBOSITY="VERBOSITY CONTROL: Token budget ≤800 tokens, including the structured findings block. The JSON findings replace a prose ISSUES list rather than duplicating it. TRIVIAL APPROVED = 2-3 lines plus the required empty findings block. COMPLEX REJECTED = full output. Scale response to complexity.",STRUCTURED_FINDINGS_CONTRACT=`Then emit exactly one fenced JSON block with this shape:
|
|
6033
6041
|
\`\`\`json
|
|
6034
6042
|
{
|
|
@@ -6842,7 +6850,7 @@ ${instruction}`}async function sendWakePrompt(sessionID,events,messageID){let ac
|
|
|
6842
6850
|
`,"utf-8");try{let lines=(await readFile52(filePath,"utf-8")).split(`
|
|
6843
6851
|
`).filter((line)=>line.trim().length>0);if(lines.length>MAX_LEGACY_APPLICATION_LOG_ENTRIES){let trimmed=lines.slice(-MAX_LEGACY_APPLICATION_LOG_ENTRIES);await atomicWriteFile(filePath,`${trimmed.join(`
|
|
6844
6852
|
`)}
|
|
6845
|
-
`)}}catch(err){warn(`[knowledge-application] appendAudit cap failed: ${err instanceof Error?err.message:String(err)}`)}}finally{if(release)await release().catch(()=>{})}}async function bumpCountersBatch(directory,bumps){let filteredBumps=bumps.filter((b)=>b.ids.length>0);if(filteredBumps.length===0)return;let idToFields=new Map;for(let b of filteredBumps)for(let id of b.ids){let list=idToFields.get(id);if(list)list.push(b.field);else idToFields.set(id,[b.field])}let now2=new Date().toISOString(),applyOne=(entries2)=>{let updated=!1;for(let e of entries2){let fields=idToFields.get(e.id);if(!fields)continue;let ro=e.retrieval_outcomes;for(let field of fields){if(ro[field]=(ro[field]??0)+1,field==="applied_explicit_count")e.last_applied_at=now2;if(field==="acknowledged_count")e.last_acknowledged_at=now2;updated=!0}}return updated?entries2:null},swarmPath3=resolveSwarmKnowledgePath(directory);await transactKnowledge(swarmPath3,applyOne);let hivePath=resolveHiveKnowledgePath2();if(existsSync142(hivePath))await transactKnowledge(hivePath,applyOne)}async function bumpCounters(directory,ids,field){return bumpCountersBatch(directory,[{ids,field}])}async function recordKnowledgeShown(directory,ids,ctx){if(ids.length===0)return;try{let ts=new Date().toISOString();for(let id of ids)await appendAudit(directory,{timestamp:ts,phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:id,result:"shown"});await bumpCounters(directory,ids,"shown_count")}catch(err){warn(`[knowledge-application] recordKnowledgeShown failed: ${err instanceof Error?err.message:String(err)}`)}}async function recordAcknowledgment(directory,ack,ctx){try{let result=ack.result==="n_a"?"acknowledged":ack.result;await appendAudit(directory,{timestamp:new Date().toISOString(),phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:ack.id,result,reason:ack.reason});let bumps=[{ids:[ack.id],field:"acknowledged_count"}];if(ack.result==="applied")bumps.push({ids:[ack.id],field:"applied_explicit_count"});else if(ack.result==="ignored")bumps.push({ids:[ack.id],field:"ignored_count"});else if(ack.result==="contradicted")bumps.push({ids:[ack.id],field:"contradicted_count"});else if(ack.result==="violated")bumps.push({ids:[ack.id],field:"violated_count"});await bumpCountersBatch(directory,bumps)}catch(err){warn(`[knowledge-application] recordAcknowledgment failed: ${err instanceof Error?err.message:String(err)}`)}}function buildAckDedupKey(sessionId,id,result,_now=new Date){return`${sessionId}|${id}|${result}`}var import_proper_lockfile16,MAX_LEGACY_APPLICATION_LOG_ENTRIES=5000,EXACT_ACK_PATTERN,LEGACY_ACK_PATTERN;var init_knowledge_application=__esm(()=>{init_task_file();init_logger();init_knowledge_link();init_knowledge_store();import_proper_lockfile16=__toESM(require_proper_lockfile(),1);EXACT_ACK_PATTERN=/KNOWLEDGE_(APPLIED|IGNORED|CONTRADICTED|VIOLATED|N_A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+reason\s*=\s*([^\n\r]+?)(?=$|[\n\r]|\s+KNOWLEDGE_))?/gi,LEGACY_ACK_PATTERN=/KNOWLEDGE_(APPLIED|IGNORED|CONTRADICTED|VIOLATED|N_A)\s*:\s*([0-9a-fA-F-]{8,64})(?:\s+reason\s*=\s*([^\n\r]+?)(?=$|[\n\r]|\s+KNOWLEDGE_))?(?=[^0-9a-fA-F-]|$)/gi});function resolveAgent(sessionID){if(typeof sessionID==="string"&&sessionID.length>0){let mapped=swarmState.activeAgent.get(sessionID);if(mapped)return mapped}return log("[host-boundary] no activeAgent mapped; defaulting to orchestrator",{sessionID:sessionID??"<none>"}),ORCHESTRATOR_NAME}function isPlainObject7(v){return typeof v==="object"&&v!==null&&!Array.isArray(v)}function toArgs(v){return isPlainObject7(v)?v:null}function resolveToolBeforeContext(input,output){let agent=resolveAgent(input.sessionID),callerRole=stripKnownSwarmPrefix(agent).toLowerCase();return{tool:input.tool,sessionID:input.sessionID,callID:input.callID,agent,callerRole,args:toArgs(output?.args),isArchitect:callerRole===ORCHESTRATOR_NAME}}function resolveToolAfterContext(input){let agent=resolveAgent(input.sessionID),callerRole=stripKnownSwarmPrefix(agent).toLowerCase();return{tool:input.tool,sessionID:input.sessionID,callID:input.callID,agent,callerRole,args:toArgs(getStoredInputArgs(input.callID)),isArchitect:callerRole===ORCHESTRATOR_NAME}}function resolveMessageTransformContext(output){let messages=Array.isArray(output?.messages)?output.messages:[],sessionID;for(let m of messages){let sid=m?.info?.sessionID;if(typeof sid==="string"&&sid.length>0){sessionID=sid;break}}let agent=resolveAgentOptional(sessionID);if(!agent)for(let i=messages.length-1;i>=0;i--){let info=messages[i]?.info;if(info?.role==="user"&&typeof info.agent==="string"&&info.agent){agent=info.agent;break}}let callerRole=agent?stripKnownSwarmPrefix(agent).toLowerCase():void 0;return{sessionID,agent,callerRole,isArchitect:callerRole===ORCHESTRATOR_NAME,isDelegate:!!agent&&!!callerRole&&callerRole!==ORCHESTRATOR_NAME}}function resolveAgentOptional(sessionID){if(typeof sessionID==="string"&&sessionID.length>0){let mapped=swarmState.activeAgent.get(sessionID);if(mapped)return mapped}return}var init_host_boundary=__esm(()=>{init_agent_names();init_schema();init_state2();init_logger();init_stored_input_args()});import{existsSync as existsSync143}from"node:fs";async function readEntriesById(directory){let map3=new Map,swarm=await readKnowledge(resolveSwarmKnowledgePath(directory));for(let e of swarm)map3.set(e.id,e);let hivePath=resolveHiveKnowledgePath2();if(existsSync143(hivePath)){let hive=await readKnowledge(hivePath);for(let e of hive)if(!map3.has(e.id))map3.set(e.id,e)}return map3}async function readPhaseDirectivesToVerify(directory,phaseLabel){try{let result=await queryLiveMemberships(directory,{phase:phaseLabel||void 0,include_terminal:!0,include_phase_closed:!1});if(!result.ok||result.memberships.length===0)return[];let entries2=await readEntriesById(directory),
|
|
6853
|
+
`)}}catch(err){warn(`[knowledge-application] appendAudit cap failed: ${err instanceof Error?err.message:String(err)}`)}}finally{if(release)await release().catch(()=>{})}}async function bumpCountersBatch(directory,bumps){let filteredBumps=bumps.filter((b)=>b.ids.length>0);if(filteredBumps.length===0)return;let idToFields=new Map;for(let b of filteredBumps)for(let id of b.ids){let list=idToFields.get(id);if(list)list.push(b.field);else idToFields.set(id,[b.field])}let now2=new Date().toISOString(),applyOne=(entries2)=>{let updated=!1;for(let e of entries2){let fields=idToFields.get(e.id);if(!fields)continue;let ro=e.retrieval_outcomes;for(let field of fields){if(ro[field]=(ro[field]??0)+1,field==="applied_explicit_count")e.last_applied_at=now2;if(field==="acknowledged_count")e.last_acknowledged_at=now2;updated=!0}}return updated?entries2:null},swarmPath3=resolveSwarmKnowledgePath(directory);await transactKnowledge(swarmPath3,applyOne);let hivePath=resolveHiveKnowledgePath2();if(existsSync142(hivePath))await transactKnowledge(hivePath,applyOne)}async function bumpCounters(directory,ids,field){return bumpCountersBatch(directory,[{ids,field}])}async function recordKnowledgeShown(directory,ids,ctx){if(ids.length===0)return;try{let ts=new Date().toISOString();for(let id of ids)await appendAudit(directory,{timestamp:ts,phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:id,result:"shown"});await bumpCounters(directory,ids,"shown_count")}catch(err){warn(`[knowledge-application] recordKnowledgeShown failed: ${err instanceof Error?err.message:String(err)}`)}}async function recordAcknowledgment(directory,ack,ctx){try{let result=ack.result==="n_a"?"acknowledged":ack.result;await appendAudit(directory,{timestamp:new Date().toISOString(),phase:ctx.phase,taskId:ctx.taskId,action:ctx.action,tool:ctx.tool,targetAgent:ctx.targetAgent,sessionId:ctx.sessionId,knowledgeId:ack.id,result,reason:ack.reason});let bumps=[{ids:[ack.id],field:"acknowledged_count"}];if(ack.result==="applied")bumps.push({ids:[ack.id],field:"applied_explicit_count"});else if(ack.result==="ignored")bumps.push({ids:[ack.id],field:"ignored_count"});else if(ack.result==="contradicted")bumps.push({ids:[ack.id],field:"contradicted_count"});else if(ack.result==="violated")bumps.push({ids:[ack.id],field:"violated_count"});await bumpCountersBatch(directory,bumps)}catch(err){warn(`[knowledge-application] recordAcknowledgment failed: ${err instanceof Error?err.message:String(err)}`)}}function buildAckDedupKey(sessionId,id,result,_now=new Date){return`${sessionId}|${id}|${result}`}var import_proper_lockfile16,MAX_LEGACY_APPLICATION_LOG_ENTRIES=5000,EXACT_ACK_PATTERN,LEGACY_ACK_PATTERN;var init_knowledge_application=__esm(()=>{init_task_file();init_logger();init_knowledge_link();init_knowledge_store();import_proper_lockfile16=__toESM(require_proper_lockfile(),1);EXACT_ACK_PATTERN=/KNOWLEDGE_(APPLIED|IGNORED|CONTRADICTED|VIOLATED|N_A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+reason\s*=\s*([^\n\r]+?)(?=$|[\n\r]|\s+KNOWLEDGE_))?/gi,LEGACY_ACK_PATTERN=/KNOWLEDGE_(APPLIED|IGNORED|CONTRADICTED|VIOLATED|N_A)\s*:\s*([0-9a-fA-F-]{8,64})(?:\s+reason\s*=\s*([^\n\r]+?)(?=$|[\n\r]|\s+KNOWLEDGE_))?(?=[^0-9a-fA-F-]|$)/gi});function resolveAgent(sessionID){if(typeof sessionID==="string"&&sessionID.length>0){let mapped=swarmState.activeAgent.get(sessionID);if(mapped)return mapped}return log("[host-boundary] no activeAgent mapped; defaulting to orchestrator",{sessionID:sessionID??"<none>"}),ORCHESTRATOR_NAME}function isPlainObject7(v){return typeof v==="object"&&v!==null&&!Array.isArray(v)}function toArgs(v){return isPlainObject7(v)?v:null}function resolveToolBeforeContext(input,output){let agent=resolveAgent(input.sessionID),callerRole=stripKnownSwarmPrefix(agent).toLowerCase();return{tool:input.tool,sessionID:input.sessionID,callID:input.callID,agent,callerRole,args:toArgs(output?.args),isArchitect:callerRole===ORCHESTRATOR_NAME}}function resolveToolAfterContext(input){let agent=resolveAgent(input.sessionID),callerRole=stripKnownSwarmPrefix(agent).toLowerCase();return{tool:input.tool,sessionID:input.sessionID,callID:input.callID,agent,callerRole,args:toArgs(getStoredInputArgs(input.callID)),isArchitect:callerRole===ORCHESTRATOR_NAME}}function resolveMessageTransformContext(output){let messages=Array.isArray(output?.messages)?output.messages:[],sessionID;for(let m of messages){let sid=m?.info?.sessionID;if(typeof sid==="string"&&sid.length>0){sessionID=sid;break}}let agent=resolveAgentOptional(sessionID);if(!agent)for(let i=messages.length-1;i>=0;i--){let info=messages[i]?.info;if(info?.role==="user"&&typeof info.agent==="string"&&info.agent){agent=info.agent;break}}let callerRole=agent?stripKnownSwarmPrefix(agent).toLowerCase():void 0;return{sessionID,agent,callerRole,isArchitect:callerRole===ORCHESTRATOR_NAME,isDelegate:!!agent&&!!callerRole&&callerRole!==ORCHESTRATOR_NAME}}function resolveAgentOptional(sessionID){if(typeof sessionID==="string"&&sessionID.length>0){let mapped=swarmState.activeAgent.get(sessionID);if(mapped)return mapped}return}var init_host_boundary=__esm(()=>{init_agent_names();init_schema();init_state2();init_logger();init_stored_input_args()});import{existsSync as existsSync143}from"node:fs";async function readEntriesById(directory){let map3=new Map,swarm=await readKnowledge(resolveSwarmKnowledgePath(directory));for(let e of swarm)map3.set(e.id,e);let hivePath=resolveHiveKnowledgePath2();if(existsSync143(hivePath)){let hive=await readKnowledge(hivePath);for(let e of hive)if(!map3.has(e.id))map3.set(e.id,e)}return map3}function isPreferredDirectiveCandidate(next,incumbent){let nextViolation=next.directive.prior_terminal_outcome==="violated"||next.directive.prior_terminal_outcome==="contradicted",incumbentViolation=incumbent.directive.prior_terminal_outcome==="violated"||incumbent.directive.prior_terminal_outcome==="contradicted";if(nextViolation!==incumbentViolation)return nextViolation;if(next.committed_at!==incumbent.committed_at)return next.committed_at>incumbent.committed_at;return next.directive.trace_id>incumbent.directive.trace_id}function pickDirectiveRepresentatives(candidates){let byEntry=new Map;for(let candidate2 of candidates){let incumbent=byEntry.get(candidate2.directive.entry_id);if(!incumbent||isPreferredDirectiveCandidate(candidate2,incumbent))byEntry.set(candidate2.directive.entry_id,candidate2)}return[...byEntry.values()]}async function readPhaseDirectivesToVerify(directory,phaseLabel){try{let result=await queryLiveMemberships(directory,{phase:phaseLabel||void 0,include_terminal:!0,include_phase_closed:!1});if(!result.ok||result.memberships.length===0)return[];let entries2=await readEntriesById(directory),candidates=[];for(let membership of result.memberships){if(membership.terminal&&membership.terminal.outcome!=="violated"&&membership.terminal.outcome!=="contradicted")continue;let e=entries2.get(membership.entry_id);if(!e)continue;if(!isActiveStatus(e.status))continue;let outcome=membership.terminal?.outcome;candidates.push({committed_at:membership.committed_at,directive:{trace_id:membership.trace_id,entry_id:membership.entry_id,session_id:membership.session_id,cohort_id:membership.cohort_id,source_link_id:membership.source_link_id,prior_terminal_outcome:outcome==="violated"||outcome==="contradicted"?outcome:void 0,prior_terminal_event_id:outcome==="violated"||outcome==="contradicted"?membership.terminal?.event_id:void 0,priority:membership.critical?"critical":e.directive_priority??"medium",lesson:e.lesson,verification_predicate:e.verification_predicate}})}return pickDirectiveRepresentatives(candidates).map((candidate2)=>candidate2.directive)}catch{return[]}}var init_phase_directives=__esm(()=>{init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_types()});import{createHash as createHash86}from"node:crypto";function phaseNumberOf(label){if(!label)return;let m=/^Phase\s+(\d+)/i.exec(label);return m?Number(m[1]):void 0}function recordInjectionSkip(directory,reason,detail){let context={};if(detail?.messageCount!==void 0)context.message_count=detail.messageCount;if(detail?.modelId!==void 0)context.model_id=detail.modelId;if(detail?.providerId!==void 0)context.provider_id=detail.providerId;if(detail?.storeAvailable!==void 0)context.store_available=detail.storeAvailable;if(detail?.missing!==void 0&&detail.missing.length>0)context.missing=detail.missing;_internals220.recordKnowledgeEvent(directory,{type:"injection_skip",reason,agent:detail?.agent,session_id:detail?.sessionId,phase:detail?.phase,detail:{...detail?.extra,...Object.keys(context).length>0?{context}:{}}}).catch(()=>{})}function buildKnowledgeBlock(entries2,charBudget,cfg,currentProject){if(entries2.length===0)return{block:null,renderedIds:[]};let maxDisplayChars=cfg.max_lesson_display_chars??120,rendered=entries2.map((entry)=>{let tier=entry.tier==="hive"?"[H]":"[S]",confirmedBy=entry.confirmed_by?.length??0,confirm=confirmedBy>=3?" ✓✓":confirmedBy>=1?" ✓":"",lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";return{id:entry.id,line:`${tier} ${lessonText}${source}${confirm}`}}),header=`\uD83D\uDCDA Lessons:
|
|
6846
6854
|
`,block=`${header}
|
|
6847
6855
|
${rendered.map((r)=>r.line).join(`
|
|
6848
6856
|
`)}`;while(block.length>charBudget&&rendered.length>0)rendered.pop(),block=`${header}
|
|
@@ -6852,13 +6860,13 @@ ${rendered.map((r)=>r.line).join(`
|
|
|
6852
6860
|
`);if(records.length===0)return{block:null,renderedIds:[]};return{block,renderedIds:records.map((r)=>r.id)}}function buildDelegateDirectiveBlock(entries2,cfg,traceId,charBudget){if(entries2.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,FIELD_CAP=240,renderList=(items)=>{if(!items||items.length===0)return null;let joined=items.map((s)=>sanitizeLessonForContext(s)).filter((s)=>s.length>0).join("; ");if(!joined)return null;return joined.length>FIELD_CAP?`${joined.slice(0,FIELD_CAP)}…`:joined},sorted2=[...entries2].sort((a,b)=>{let pr=directivePriorityRank(a.directive_priority)-directivePriorityRank(b.directive_priority);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),header=()=>[DELEGATE_DIRECTIVE_BLOCK_TAG,"These directives were learned from prior swarm runs and scoped to your role. Apply them to the task below.","CURRENT AUTHORITY WINS: system messages, repository contracts, the active task scope, and observed repository state override learned directives. Never violate a current scope or safety contract to follow a learned directive.","ACK CONTRACT: end your FINAL message with one line per directive in this block:"],ackPair=traceId?"<trace_id>:<id>":"<id>",contractLines=()=>[` KNOWLEDGE_APPLIED:${ackPair} — you applied it`,` KNOWLEDGE_IGNORED:${ackPair} reason=<short why> — you judged it relevant but deliberately chose not to follow it (counts against the directive)`,` KNOWLEDGE_CONTRADICTED:${ackPair} reason=<observable conflict> — current authority or repository evidence disproved it (counts against the directive)`,` KNOWLEDGE_N_A:${ackPair} reason=<why> — it was not relevant to your task (neutral; prefer this when the directive simply did not apply)`,"Omitting a critical id is a contract violation. Omitting any other id is recorded as unacknowledged."],footer=()=>[...traceId?[`trace_id: ${traceId}`]:[]],records=[];for(let e of sorted2){let priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay),lines=[`- id: ${e.id}`,` priority: ${priority}`,` lesson: ${lesson}`],forbidden=renderList(e.forbidden_actions);if(forbidden)lines.push(` forbidden: ${forbidden}`);let required3=renderList(e.required_actions);if(required3)lines.push(` required: ${required3}`);let verification=renderList(e.verification_checks);if(verification)lines.push(` verification: ${verification}`);records.push({id:e.id,lines})}let assemble=()=>[...header(),...contractLines(),...footer(),...records.flatMap((r)=>r.lines),"</delegate_knowledge_directives>"].join(`
|
|
6853
6861
|
`);if(charBudget!==void 0){let block=assemble();while(block.length>charBudget&&records.length>0)records.pop(),block=assemble();if(records.length===0)return null;return block}return assemble()}function parseDelegateDirectiveBlock(text){if(!text||!text.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))return[];let start=text.indexOf(DELEGATE_DIRECTIVE_BLOCK_TAG),endTag="</delegate_knowledge_directives>",endIdx=text.indexOf(endTag,start),body=endIdx>=0?text.slice(start,endIdx):text.slice(start),out=[];for(let line of body.split(`
|
|
6854
6862
|
`)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM&&out.length>0)out[out.length-1].priority=prM[1]}return out}function parseDelegateDirectiveTraceId(text){if(!text||!text.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))return;let start=text.indexOf(DELEGATE_DIRECTIVE_BLOCK_TAG),endTag="</delegate_knowledge_directives>",endIdx=text.indexOf(endTag,start),body=endIdx>=0?text.slice(start,endIdx):text.slice(start);for(let line of body.split(`
|
|
6855
|
-
`)){let m=/^trace_id:\s*(\S+)\s*$/m.exec(line);if(m)return m[1]}return}function bumpKnowledgeGeneration(){return knowledgeGeneration++,knowledgeGeneration}function getKnowledgeGeneration(){return knowledgeGeneration}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params;if(!sessionId)return{entries:[],trace_id:""};let cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&¶ms.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals220.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals220.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let cohortId=await _internals220.ensureCohortIdCached(directory,sessionId),sourceLinkId=_internals220.readLinkPointer(directory)?.linkId,membership=await _internals220.commitDisplayedMembership(directory,{trace_id:search.trace_id,session_id:sessionId,exposure_kind:"delegate_directive",phase:params.phase,task_id:params.taskId,agent,cohort_id:cohortId,source_link_id:sourceLinkId,grace_days:config3.receipt_close_grace_days,entries:capped.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return recordInjectionSkip(directory,membership.ok?"terminal_trace_reuse":membership.code,{agent,sessionId,missing:membership.ok?["reusable_trace"]:["valid_membership"],extra:{trace_id:search.trace_id}}),{entries:[],trace_id:""};if(await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:params.phase,task_id:params.taskId,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores}),params.phase){let shownIds=capped.map((e)=>e.id);_internals220.recordLessonsShown(directory,shownIds,params.phase).catch(()=>{}),_internals220.recordKnowledgeShown(directory,shownIds,{phase:params.phase,targetAgent:agent,sessionId}).catch(()=>{});let phaseNum=phaseNumberOf(params.phase);if(phaseNum!==void 0){let projectName=(await loadPlan(directory).catch(()=>null))?.title??"unknown";_internals220.confirmEntriesPhase(directory,shownIds,phaseNum,projectName).catch(()=>{})}}}if(capped.length===0)try{let empty=await _internals220.commitEmptyRetrieval(directory,{trace_id:search.trace_id,session_id:sessionId,phase:params.phase,agent,grace_days:config3.receipt_close_grace_days});if(!empty.ok||!empty.terminal_event_id)return{entries:[],trace_id:""};await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:params.phase,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:[],ranks:{},scores:{}}),await _internals220.recordKnowledgeEvent(directory,{type:"no_relevant",trace_id:search.trace_id,session_id:sessionId,phase:params.phase,agent,reason:"empty delegate retrieval"})}catch{}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId,charBudget){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries:entries2,trace_id}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,phase:phaseLabel,config:config3}),block=buildDelegateDirectiveBlock(entries2,config3,trace_id,charBudget),isReviewer=stripKnownSwarmPrefix(agentName).toLowerCase()==="reviewer",alreadyVerified=isReviewer&&output.messages.some((m)=>m.parts?.some((p)=>typeof p.text==="string"&&parseDirectivesToVerifyBlock(p.text).length>0));if(block)injectKnowledgeMessage(output,block,sessionId);if(isReviewer&&!alreadyVerified){let toVerify=await readPhaseDirectivesToVerify(directory,phaseLabel),complianceBlock=buildDirectiveComplianceBlock(toVerify);if(complianceBlock)injectReviewerComplianceMessage(output,complianceBlock,sessionId)}}function injectReviewerComplianceMessage(output,text,sessionId){if(!output.messages)return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let message=insertGuidanceCarrier(output.messages,"knowledge",`${text}`,insertIdx);if(!deliveredGuidanceDelta(message,text))log("[knowledge-injector] reviewer compliance block not delivered (empty text or non-renderable carrier) — emission skipped");if(sessionId&&deliveredGuidanceDelta(message,text))recordProducerEmission(sessionId,"knowledge-injector",estimateTokens(message?.parts[0]?.text??""),0,"messages")}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text,sessionId){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage=insertGuidanceCarrier(output.messages,"knowledge",`${INJECTION_SENTINEL}${text}`,insertIdx);if(!deliveredGuidanceDelta(knowledgeMessage,`${INJECTION_SENTINEL}${text}`))log("[knowledge-injector] knowledge block not delivered (empty text or non-renderable carrier) — emission skipped");if(sessionId&&deliveredGuidanceDelta(knowledgeMessage,`${INJECTION_SENTINEL}${text}`))recordProducerEmission(sessionId,"knowledge-injector",estimateTokens(knowledgeMessage?.parts[0]?.text??""),0,"messages")}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),String(getKnowledgeGeneration()),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash86("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash86("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[],cachedTraceId=null;return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0){recordInjectionSkip(directory,"no_messages",{missing:["messages"]});return}let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,mctx=resolveMessageTransformContext(output),agentName=mctx.agent,sessionId=mctx.sessionID;if(!sessionId){recordInjectionSkip(directory,"missing_session_id",{agent:agentName,messageCount:output.messages.length,missing:["session_id"]});return}let liveModelInfo=getLiveContextModelIdentity(sessionId),{modelID,providerID}=liveModelInfo??extractModelInfo(output.messages),liveContextLimit=getLiveContextWindow(sessionId,{modelID,providerID}),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides,liveContextLimit,directory).limit,MODEL_LIMIT_CHARS=estimateCharsForTokens(modelLimitTokens),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`),recordInjectionSkip(directory,"headroom_budget",{agent:agentName,sessionId,messageCount:output.messages.length,modelId:modelID,providerId:providerID,missing:["headroom"],extra:{headroomChars,existingChars,modelLimitChars:MODEL_LIMIT_CHARS,modelID}});return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25);if(!agentName){recordInjectionSkip(directory,"no_agent_name",{sessionId,messageCount:output.messages.length,missing:["agent_name"]});return}if(unifiedInjectionTokens!==void 0){let sessionID2=sessionId,seDemand=sessionID2?getProducerEmission(sessionID2,"system-enhancer"):0,requestedTokens=estimateTokensFromCharCount(effectiveBudget),allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});if(effectiveBudget=estimateCharsForTokens(allocation.knowledgeInjectorTokens),sessionID2)recordProducerGrant(sessionID2,"knowledge-injector",requestedTokens,allocation.knowledgeInjectorTokens,"messages")}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId,Math.min(effectiveBudget,DELEGATE_INJECT_HARD_CHAR_CAP));return}if(!isOrchestratorAgent(agentName)){recordInjectionSkip(directory,"not_architect",{agent:agentName,sessionId,messageCount:output.messages.length,missing:["architect_agent"]});return}let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){let cacheVerifiable=cachedShownIds.length===0;if(cachedShownIds.length>0&&cachedTraceId){let live=await _internals220.queryLiveMemberships(directory,{session_id:sessionId,include_terminal:!1});if(live.ok){let liveIds=new Set(live.memberships.filter((membership)=>membership.trace_id===cachedTraceId).map((membership)=>membership.entry_id));cacheVerifiable=cachedShownIds.every((id)=>liveIds.has(id))}}if(cacheVerifiable)injectKnowledgeMessage(output,cachedInjectionText,sessionId);let sessionID2=sessionId;if(sessionID2&&cacheVerifiable)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);if(cacheVerifiable)return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[],cachedTraceId=null;let search=await(_internals220.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals220.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId,emitEvent:!1});cachedTraceId=search.trace_id;let filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
|
|
6863
|
+
`)){let m=/^trace_id:\s*(\S+)\s*$/m.exec(line);if(m)return m[1]}return}function bumpKnowledgeGeneration(){return knowledgeGeneration++,knowledgeGeneration}function getKnowledgeGeneration(){return knowledgeGeneration}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params;if(!sessionId)return{entries:[],trace_id:""};let cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&¶ms.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals220.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals220.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let cohortId=await _internals220.ensureCohortIdCached(directory,sessionId),sourceLinkId=_internals220.readLinkPointer(directory)?.linkId,membership=await _internals220.commitDisplayedMembership(directory,{trace_id:search.trace_id,session_id:sessionId,exposure_kind:"delegate_directive",phase:params.phase,task_id:params.taskId,agent,cohort_id:cohortId,source_link_id:sourceLinkId,grace_days:config3.receipt_close_grace_days,entries:capped.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return recordInjectionSkip(directory,membership.ok?"terminal_trace_reuse":membership.code,{agent,sessionId,missing:membership.ok?["reusable_trace"]:["valid_membership"],extra:{trace_id:search.trace_id}}),{entries:[],trace_id:""};if(await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:params.phase,task_id:params.taskId,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores}),params.phase){let shownIds=capped.map((e)=>e.id);_internals220.recordLessonsShown(directory,shownIds,params.phase).catch(()=>{}),_internals220.recordKnowledgeShown(directory,shownIds,{phase:params.phase,targetAgent:agent,sessionId}).catch(()=>{});let phaseNum=phaseNumberOf(params.phase);if(phaseNum!==void 0){let projectName=(await loadPlan(directory).catch(()=>null))?.title??"unknown";_internals220.confirmEntriesPhase(directory,shownIds,phaseNum,projectName).catch(()=>{})}}}if(capped.length===0)try{let empty=await _internals220.commitEmptyRetrieval(directory,{trace_id:search.trace_id,session_id:sessionId,phase:params.phase,agent,grace_days:config3.receipt_close_grace_days});if(!empty.ok||!empty.terminal_event_id)return{entries:[],trace_id:""};await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:params.phase,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:[],ranks:{},scores:{}}),await _internals220.recordKnowledgeEvent(directory,{type:"no_relevant",trace_id:search.trace_id,session_id:sessionId,phase:params.phase,agent,reason:"empty delegate retrieval"})}catch{}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId,charBudget){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries:entries2,trace_id}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,phase:phaseLabel,config:config3}),block=buildDelegateDirectiveBlock(entries2,config3,trace_id,charBudget),isReviewer=stripKnownSwarmPrefix(agentName).toLowerCase()==="reviewer",alreadyVerified=isReviewer&&output.messages.some((m)=>m.parts?.some((p)=>typeof p.text==="string"&&parseDirectivesToVerifyBlock(p.text).length>0));if(block)injectKnowledgeMessage(output,block,sessionId);if(isReviewer&&!alreadyVerified){let toVerify=await readPhaseDirectivesToVerify(directory,phaseLabel),complianceBlock=buildDirectiveComplianceBlock(toVerify,Math.min(config3.inject_char_budget??DIRECTIVE_COMPLIANCE_DEFAULT_CHAR_BUDGET,DIRECTIVE_COMPLIANCE_HARD_CHAR_CAP));if(complianceBlock)injectReviewerComplianceMessage(output,complianceBlock,sessionId)}}function injectReviewerComplianceMessage(output,text,sessionId){if(!output.messages)return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let message=insertGuidanceCarrier(output.messages,"knowledge",`${text}`,insertIdx);if(!deliveredGuidanceDelta(message,text))log("[knowledge-injector] reviewer compliance block not delivered (empty text or non-renderable carrier) — emission skipped");if(sessionId&&deliveredGuidanceDelta(message,text))recordProducerEmission(sessionId,"knowledge-injector",estimateTokens(message?.parts[0]?.text??""),0,"messages")}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text,sessionId){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage=insertGuidanceCarrier(output.messages,"knowledge",`${INJECTION_SENTINEL}${text}`,insertIdx);if(!deliveredGuidanceDelta(knowledgeMessage,`${INJECTION_SENTINEL}${text}`))log("[knowledge-injector] knowledge block not delivered (empty text or non-renderable carrier) — emission skipped");if(sessionId&&deliveredGuidanceDelta(knowledgeMessage,`${INJECTION_SENTINEL}${text}`))recordProducerEmission(sessionId,"knowledge-injector",estimateTokens(knowledgeMessage?.parts[0]?.text??""),0,"messages")}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),String(getKnowledgeGeneration()),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash86("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash86("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[],cachedTraceId=null;return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0){recordInjectionSkip(directory,"no_messages",{missing:["messages"]});return}let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,mctx=resolveMessageTransformContext(output),agentName=mctx.agent,sessionId=mctx.sessionID;if(!sessionId){recordInjectionSkip(directory,"missing_session_id",{agent:agentName,messageCount:output.messages.length,missing:["session_id"]});return}let liveModelInfo=getLiveContextModelIdentity(sessionId),{modelID,providerID}=liveModelInfo??extractModelInfo(output.messages),liveContextLimit=getLiveContextWindow(sessionId,{modelID,providerID}),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides,liveContextLimit,directory).limit,MODEL_LIMIT_CHARS=estimateCharsForTokens(modelLimitTokens),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`),recordInjectionSkip(directory,"headroom_budget",{agent:agentName,sessionId,messageCount:output.messages.length,modelId:modelID,providerId:providerID,missing:["headroom"],extra:{headroomChars,existingChars,modelLimitChars:MODEL_LIMIT_CHARS,modelID}});return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25);if(!agentName){recordInjectionSkip(directory,"no_agent_name",{sessionId,messageCount:output.messages.length,missing:["agent_name"]});return}if(unifiedInjectionTokens!==void 0){let sessionID2=sessionId,seDemand=sessionID2?getProducerEmission(sessionID2,"system-enhancer"):0,requestedTokens=estimateTokensFromCharCount(effectiveBudget),allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});if(effectiveBudget=estimateCharsForTokens(allocation.knowledgeInjectorTokens),sessionID2)recordProducerGrant(sessionID2,"knowledge-injector",requestedTokens,allocation.knowledgeInjectorTokens,"messages")}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId,Math.min(effectiveBudget,DELEGATE_INJECT_HARD_CHAR_CAP));return}if(!isOrchestratorAgent(agentName)){recordInjectionSkip(directory,"not_architect",{agent:agentName,sessionId,messageCount:output.messages.length,missing:["architect_agent"]});return}let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){let cacheVerifiable=cachedShownIds.length===0;if(cachedShownIds.length>0&&cachedTraceId){let live=await _internals220.queryLiveMemberships(directory,{session_id:sessionId,include_terminal:!1});if(live.ok){let liveIds=new Set(live.memberships.filter((membership)=>membership.trace_id===cachedTraceId).map((membership)=>membership.entry_id));cacheVerifiable=cachedShownIds.every((id)=>liveIds.has(id))}}if(cacheVerifiable)injectKnowledgeMessage(output,cachedInjectionText,sessionId);let sessionID2=sessionId;if(sessionID2&&cacheVerifiable)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);if(cacheVerifiable)return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[],cachedTraceId=null;let search=await(_internals220.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals220.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId,emitEvent:!1});cachedTraceId=search.trace_id;let filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
|
|
6856
6864
|
|
|
6857
6865
|
${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}catch{}if(filteredEntries.length===0){let sessionID2=sessionId;if(sessionID2)clearCriticalShownIds(sessionID2);cachedShownIds=[],cachedCriticalIds=[],recordInjectionSkip(directory,"no_matching_entries",{agent:agentName,sessionId:sessionID2,phase:currentPhase,messageCount:output.messages.length,missing:["matching_entries"]});let empty=await _internals220.commitEmptyRetrieval(directory,{trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",grace_days:config3.receipt_close_grace_days}),emptyCommitted=empty.ok&&Boolean(empty.terminal_event_id);try{if(emptyCommitted)await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:[],ranks:{},scores:{}})}catch{}if(freshPreamble===null){try{if(emptyCommitted)await _internals220.recordKnowledgeEvent(directory,{type:"no_relevant",trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",reason:"empty auto-injection retrieval"})}catch{}return}cachedInjectionText=freshPreamble,injectKnowledgeMessage(output,cachedInjectionText,sessionId);return}let runMemory=null;try{runMemory=await getRunMemorySummary(directory)}catch(err){warn(`[knowledge-injector] run memory summary unavailable: ${err instanceof Error?err.message:String(err)}`)}let isFullBudget=effectiveBudget===maxInjectChars,directiveBudget=Math.floor(effectiveBudget*0.45),lessonBudget=Math.floor(effectiveBudget*0.3),directiveEntries=filteredEntries.filter((e)=>e.triggers&&e.triggers.length>0||e.required_actions&&e.required_actions.length>0||e.forbidden_actions&&e.forbidden_actions.length>0||e.directive_priority==="critical"||e.directive_priority==="high"||e.generated_skill_path),directiveBuilt=buildDirectiveBlock(directiveEntries,directiveBudget,config3,search.trace_id),directiveBlock=directiveBuilt.block,lessonBuilt=buildKnowledgeBlock(filteredEntries,lessonBudget,config3,projectName),lessonBlock=lessonBuilt.block,renderedDirectiveIdSet=new Set(directiveBuilt.renderedIds);if(cachedShownIds=[...new Set([...directiveBuilt.renderedIds,...lessonBuilt.renderedIds])],cachedShownIds.length===0)recordInjectionSkip(directory,"rendered_id_match_failed",{agent:agentName,sessionId,phase:currentPhase,messageCount:output.messages.length,missing:["rendered_entries"],extra:{filteredCount:filteredEntries.length,directiveCount:directiveEntries.length}});let parts=[],remaining=effectiveBudget;try{let escalations=await _internals220.readRecentEscalations(directory),escalationBriefing=_internals220.buildEscalationBriefing(escalations);if(escalationBriefing&&escalationBriefing.length<=remaining)parts.push(escalationBriefing),remaining-=escalationBriefing.length}catch{}if(directiveBlock)parts.push(directiveBlock),remaining-=directiveBlock.length;if(lessonBlock)parts.push(lessonBlock),remaining-=lessonBlock.length;if(runMemory&&remaining>300){let sanitizedRunMemory=sanitizeContextText(runMemory);if(sanitizedRunMemory.length<=remaining)parts.push(sanitizedRunMemory),remaining-=sanitizedRunMemory.length}if(freshPreamble&&remaining>200){let preambleToUse=freshPreamble;if(!isFullBudget)preambleToUse=preambleToUse.replace(/<curator_briefing>[\s\S]*?<\/curator_briefing>\s*/g,"");if(preambleToUse.trim().length>0&&preambleToUse.length<=remaining)parts.push(preambleToUse),remaining-=preambleToUse.length}try{let rejected2=await readRejectedLessons(directory);if(rejected2.length>0&&remaining>150){let rejectedBlock=`⚠️ Previously rejected patterns (do not re-learn):
|
|
6858
6866
|
`+rejected2.slice(-3).map((r)=>` ⚠️ REJECTED PATTERN: "${sanitizeLessonForContext(r.lesson).slice(0,80)}" — ${sanitizeLessonForContext(r.rejection_reason)}`).join(`
|
|
6859
6867
|
`);if(rejectedBlock.length<=remaining)parts.push(rejectedBlock)}}catch(err){warn(`[knowledge-injector] rejected pattern warnings unavailable: ${err instanceof Error?err.message:String(err)}`)}cachedInjectionText=parts.join(`
|
|
6860
6868
|
|
|
6861
|
-
`);let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedShownIds.length>0){let byId=new Map(filteredEntries.map((entry)=>[entry.id,entry])),cohortId=await _internals220.ensureCohortIdCached(directory,sessionId),sourceLinkId=_internals220.readLinkPointer(directory)?.linkId,membership=await _internals220.commitDisplayedMembership(directory,{trace_id:search.trace_id,session_id:sessionId,exposure_kind:"architect_directive",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",cohort_id:cohortId,source_link_id:sourceLinkId,grace_days:config3.receipt_close_grace_days,entries:cachedShownIds.map((id,index)=>({entry_id:id,critical:criticalIds.includes(id),rank:index+1,score:byId.get(id)?.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal)){if(cachedInjectionText="",cachedShownIds=[],cachedCriticalIds=[],sessionId)clearCriticalShownIds(sessionId);recordInjectionSkip(directory,membership.ok?"terminal_trace_reuse":membership.code,{agent:agentName,sessionId,phase:currentPhase,extra:{trace_id:search.trace_id}});return}}injectKnowledgeMessage(output,cachedInjectionText,sessionId);let sessionID=sessionId;if(sessionID)if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID);if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals220.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{}),_internals220.recordLessonsShown(directory,cachedShownIds,phaseLabel).catch(()=>{}),_internals220.confirmEntriesPhase(directory,cachedShownIds,currentPhase,projectName).catch(()=>{})}})}var INJECTION_SENTINEL,defaultSearchKnowledge,sanitizeLessonForContext,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>",DELEGATE_INJECT_HARD_CHAR_CAP=2000,knowledgeGeneration=0,DELEGATED_AGENTS,DELEGATE_DEFAULT_TOOLS,DIRECTIVE_PRIORITY_RANK,_internals220;var init_knowledge_injector=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_manager();init_injection_budget();init_run_memory();init_state2();init_logger();init_cohort_cache();init_curator_drift();init_extractors();init_host_boundary();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_link();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_types();init_model_limits();init_phase_directives();init_search_knowledge();init_utils2();INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;sanitizeLessonForContext=sanitizeContextText;DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};_internals220={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing,recordLessonsShown,confirmEntriesPhase,commitDisplayedMembership,commitEmptyRetrieval,queryLiveMemberships,ensureCohortIdCached,readLinkPointer}});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 existsSync147,readdirSync as readdirSync40,readFileSync as readFileSync114,statSync as statSync80}from"node:fs";import*as path275 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=path275.resolve(directory),resolved=path275.resolve(baseDir,concrete),rel3=path275.relative(baseDir,resolved);if(rel3.startsWith("..")||path275.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(path275.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path275.join(dir,name);if(existsSync147(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((resolve109)=>setTimeout(()=>resolve109("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=readdirSync40(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path275.join(dir,entry.name),relPath=path275.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(statSync80(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync114(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(path275.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=path275.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 _internals227.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_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 _internals227.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 _internals227.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 _internals227.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 _internals227,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();_internals227={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 createHash89}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:createHash89("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash89("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:createHash89("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash89("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:()=>_internals246,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs171 from"node:fs";import*as path296 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 _internals246.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=_internals246.findByCorrelationId(directory,record3.correlationId);if(!reread)return{kind:"missing"};if(isTerminalDelegationStatus(reread.status)){if(reread.terminalResult)return{kind:"conflict",record:reread};return emitDelegationEventlessTerminalEnd(reread,reread.status),{kind:"already_terminal_without_event",record:reread}}return{kind:"not_open",record:reread}}function emitDelegationBegin(record3){try{_internals246.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"")}catch{}}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})),_internals246.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields)}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=path296.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs171.existsSync(filePath))return null;let parsed=JSON.parse(fs171.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=path296.join(directory,".swarm");fs171.mkdirSync(swarmDir,{recursive:!0});let filePath=path296.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs171.rmSync(filePath,{force:!0});else fs171.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 candidates=readDelegations(directory).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",_internals246;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_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals246={claimTerminalResult,findByCorrelationId,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals267});import*as fs192 from"node:fs";import*as path319 from"node:path";function mtimeMsOrNull(absPath){try{return fs192.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path319.resolve(directory),resolved=path319.resolve(root,anchor),rel3=path319.relative(root,resolved);if(rel3.startsWith("..")||path319.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path319.resolve(directory),outAbs=path319.resolve(root,outDir),outRel=path319.relative(root,outAbs);if(outRel.startsWith("..")||path319.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path319.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path319.join(outDir,relFile));else checkedDocs.push(path319.join(outDir,relFile))}let traceabilityAbs=path319.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs192.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs192.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry3=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry3=null}let noDocs=checkedDocs.length===0||registry3===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry3?.sections))for(let section of registry3.sections){if(!section||typeof section.section_id!=="string")continue;if(typeof section.doc!=="string"||!docMtimes.has(section.doc))continue;let docMtime=docMtimes.get(section.doc)??null;if(docMtime===null){staleSections.push({section_id:section.section_id,doc:section.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section.section_id,doc:section.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section.spec_frs?.length??0)>0)staleSections.push({section_id:section.section_id,doc:section.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,_internals267;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":path319.join("reference","reference-impl.md"),"idiom-notes":path319.join("reference","idiom-notes.md")},TRACEABILITY_REL=path319.join("reference","traceability.json");_internals267={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals298,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs222 from"node:fs";import*as path357 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs222.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs222.accessSync(path357.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs222.readFileSync(path357.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 _internals298.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals298.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,_internals298;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals298={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash101}from"node:crypto";import*as path358 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath7}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs137 from"node:fs";import*as path249 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 path249.resolve(this.directory,".swarm")}getPlanJsonPath(){return path249.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=fs137.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs137.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs137.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(!fs137.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs137.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(_internals50.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals50.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=path249.join(swarmDir,"plan.json"),markerPath=path249.join(swarmDir,".plan-write-marker"),planStats=fs137.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs137.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((resolve100,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve100(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash83}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 createHash82}from"node:crypto";import*as fs139 from"node:fs";import*as path252 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 correlationKey(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha2567(value){return createHash82("sha256").update(value).digest("hex")}function policyDigest(policy){return sha2567(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=correlationKey(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=correlationKey(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:computePlanStructureHash(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=fs139.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=fs139.openSync(filePath,fs139.constants.O_RDONLY|(fs139.constants.O_NOFOLLOW??0));let openedStat=fs139.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=fs139.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{fs139.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 fs139.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 fs139.promises.open(filePath,fs139.constants.O_RDONLY|(fs139.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=sha2567(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs139.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs139.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 fs139.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 fs139.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 fs139.promises.mkdir(path252.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function bindingMatchesPlan(binding,plan,phase){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===computePlanStructureHash(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 addReceipt(store,pending,text,childIdentityAvailable){let receiptId=sha2567(stableCanonicalStringify({parentSessionId:pending.parentSessionId,callId:pending.callId,childSessionId:pending.childSessionId,planIdentityHash:pending.planIdentityHash,planStructureHash:pending.planStructureHash,phase:pending.phase,role:pending.role})),receipt={...pending,receiptId,resultDigest:sha2567(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:${sha2567(correlationKey(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);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&bindingMatchesPlan(receipt,plan,phase)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace))}}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();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;return match[1]==="APPROVED"||match[1]==="PASS"?"pass":"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);return{...check3,ok:!check3.stale}}function compareStageBWorkspace(record3,actualWorkspace){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace)}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 state=getTaskState(parentSession,taskId);if(state!=="idle"&&state!=="coder_delegated"&&state!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state}`}}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))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!=="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}`}}if(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}),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);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 applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt){for(let session of candidateSessions(parentSessionId)){recordStageBCompletion(session,taskId,agent);let state=getTaskState(session,taskId);if(state==="tests_run"||state==="complete")continue;if(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer"){try{if(state==="coder_delegated"||state==="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"&&(state==="coder_delegated"||state==="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(agent==="test_engineer"&&state==="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((resolve101)=>setTimeout(resolve101,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){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,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{return await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}}),(await findDelegationForCompletion(directory,record3.subagentSessionId))?.record.status==="consumed"}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=errorCode(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 errorCode(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 createHash83("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash83("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 fs140 from"node:fs";import*as path253 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=path253.join(projectDirectory,".swarm"),dest=path253.join(swarmDir,"config.example.json");if(fs140.existsSync(dest))return;if(!fs140.existsSync(swarmDir))fs140.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};fs140.writeFileSync(dest,`${JSON.stringify(example,null,2)}
|
|
6869
|
+
`);let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedShownIds.length>0){let byId=new Map(filteredEntries.map((entry)=>[entry.id,entry])),cohortId=await _internals220.ensureCohortIdCached(directory,sessionId),sourceLinkId=_internals220.readLinkPointer(directory)?.linkId,membership=await _internals220.commitDisplayedMembership(directory,{trace_id:search.trace_id,session_id:sessionId,exposure_kind:"architect_directive",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",cohort_id:cohortId,source_link_id:sourceLinkId,grace_days:config3.receipt_close_grace_days,entries:cachedShownIds.map((id,index)=>({entry_id:id,critical:criticalIds.includes(id),rank:index+1,score:byId.get(id)?.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal)){if(cachedInjectionText="",cachedShownIds=[],cachedCriticalIds=[],sessionId)clearCriticalShownIds(sessionId);recordInjectionSkip(directory,membership.ok?"terminal_trace_reuse":membership.code,{agent:agentName,sessionId,phase:currentPhase,extra:{trace_id:search.trace_id}});return}}injectKnowledgeMessage(output,cachedInjectionText,sessionId);let sessionID=sessionId;if(sessionID)if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID);if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals220.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals220.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{}),_internals220.recordLessonsShown(directory,cachedShownIds,phaseLabel).catch(()=>{}),_internals220.confirmEntriesPhase(directory,cachedShownIds,currentPhase,projectName).catch(()=>{})}})}var INJECTION_SENTINEL,defaultSearchKnowledge,sanitizeLessonForContext,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>",DELEGATE_INJECT_HARD_CHAR_CAP=2000,knowledgeGeneration=0,DELEGATED_AGENTS,DELEGATE_DEFAULT_TOOLS,DIRECTIVE_PRIORITY_RANK,_internals220;var init_knowledge_injector=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_manager();init_injection_budget();init_run_memory();init_state2();init_logger();init_cohort_cache();init_curator_drift();init_extractors();init_host_boundary();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_link();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_types();init_model_limits();init_phase_directives();init_search_knowledge();init_utils2();INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;sanitizeLessonForContext=sanitizeContextText;DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};_internals220={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing,recordLessonsShown,confirmEntriesPhase,commitDisplayedMembership,commitEmptyRetrieval,queryLiveMemberships,ensureCohortIdCached,readLinkPointer}});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 existsSync147,readdirSync as readdirSync40,readFileSync as readFileSync114,statSync as statSync80}from"node:fs";import*as path275 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=path275.resolve(directory),resolved=path275.resolve(baseDir,concrete),rel3=path275.relative(baseDir,resolved);if(rel3.startsWith("..")||path275.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(path275.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path275.join(dir,name);if(existsSync147(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((resolve109)=>setTimeout(()=>resolve109("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=readdirSync40(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path275.join(dir,entry.name),relPath=path275.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(statSync80(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync114(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(path275.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=path275.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 _internals227.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 _internals227.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 _internals227.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 _internals227.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 _internals227,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();_internals227={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 createHash89}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:createHash89("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash89("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:createHash89("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash89("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:()=>_internals246,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs171 from"node:fs";import*as path296 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 _internals246.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=_internals246.findByCorrelationId(directory,record3.correlationId);if(!reread)return{kind:"missing"};if(isTerminalDelegationStatus(reread.status)){if(reread.terminalResult)return{kind:"conflict",record:reread};return emitDelegationEventlessTerminalEnd(reread,reread.status),{kind:"already_terminal_without_event",record:reread}}return{kind:"not_open",record:reread}}function emitDelegationBegin(record3){try{_internals246.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"")}catch{}}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})),_internals246.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields)}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=path296.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs171.existsSync(filePath))return null;let parsed=JSON.parse(fs171.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=path296.join(directory,".swarm");fs171.mkdirSync(swarmDir,{recursive:!0});let filePath=path296.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs171.rmSync(filePath,{force:!0});else fs171.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 candidates=readDelegations(directory).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",_internals246;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_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals246={claimTerminalResult,findByCorrelationId,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals267});import*as fs192 from"node:fs";import*as path319 from"node:path";function mtimeMsOrNull(absPath){try{return fs192.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path319.resolve(directory),resolved=path319.resolve(root,anchor),rel3=path319.relative(root,resolved);if(rel3.startsWith("..")||path319.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path319.resolve(directory),outAbs=path319.resolve(root,outDir),outRel=path319.relative(root,outAbs);if(outRel.startsWith("..")||path319.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path319.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path319.join(outDir,relFile));else checkedDocs.push(path319.join(outDir,relFile))}let traceabilityAbs=path319.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs192.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs192.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry3=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry3=null}let noDocs=checkedDocs.length===0||registry3===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry3?.sections))for(let section of registry3.sections){if(!section||typeof section.section_id!=="string")continue;if(typeof section.doc!=="string"||!docMtimes.has(section.doc))continue;let docMtime=docMtimes.get(section.doc)??null;if(docMtime===null){staleSections.push({section_id:section.section_id,doc:section.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section.section_id,doc:section.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section.spec_frs?.length??0)>0)staleSections.push({section_id:section.section_id,doc:section.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,_internals267;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":path319.join("reference","reference-impl.md"),"idiom-notes":path319.join("reference","idiom-notes.md")},TRACEABILITY_REL=path319.join("reference","traceability.json");_internals267={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals298,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs222 from"node:fs";import*as path357 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs222.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs222.accessSync(path357.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs222.readFileSync(path357.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 _internals298.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals298.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,_internals298;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals298={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash101}from"node:crypto";import*as path358 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath7}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs137 from"node:fs";import*as path249 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 path249.resolve(this.directory,".swarm")}getPlanJsonPath(){return path249.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=fs137.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs137.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs137.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(!fs137.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs137.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(_internals50.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals50.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=path249.join(swarmDir,"plan.json"),markerPath=path249.join(swarmDir,".plan-write-marker"),planStats=fs137.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs137.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((resolve100,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve100(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash83}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 createHash82}from"node:crypto";import*as fs139 from"node:fs";import*as path252 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 correlationKey(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha2567(value){return createHash82("sha256").update(value).digest("hex")}function policyDigest(policy){return sha2567(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=correlationKey(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=correlationKey(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:computePlanStructureHash(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=fs139.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=fs139.openSync(filePath,fs139.constants.O_RDONLY|(fs139.constants.O_NOFOLLOW??0));let openedStat=fs139.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=fs139.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{fs139.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 fs139.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 fs139.promises.open(filePath,fs139.constants.O_RDONLY|(fs139.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=sha2567(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs139.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs139.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 fs139.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 fs139.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 fs139.promises.mkdir(path252.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function bindingMatchesPlan(binding,plan,phase){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===computePlanStructureHash(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 addReceipt(store,pending,text,childIdentityAvailable){let receiptId=sha2567(stableCanonicalStringify({parentSessionId:pending.parentSessionId,callId:pending.callId,childSessionId:pending.childSessionId,planIdentityHash:pending.planIdentityHash,planStructureHash:pending.planStructureHash,phase:pending.phase,role:pending.role})),receipt={...pending,receiptId,resultDigest:sha2567(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:${sha2567(correlationKey(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);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&bindingMatchesPlan(receipt,plan,phase)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace))}}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();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;return match[1]==="APPROVED"||match[1]==="PASS"?"pass":"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);return{...check3,ok:!check3.stale}}function compareStageBWorkspace(record3,actualWorkspace){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace)}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 state=getTaskState(parentSession,taskId);if(state!=="idle"&&state!=="coder_delegated"&&state!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state}`}}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))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!=="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}`}}if(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}),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);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 applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt){for(let session of candidateSessions(parentSessionId)){recordStageBCompletion(session,taskId,agent);let state=getTaskState(session,taskId);if(state==="tests_run"||state==="complete")continue;if(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer"){try{if(state==="coder_delegated"||state==="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"&&(state==="coder_delegated"||state==="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(agent==="test_engineer"&&state==="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((resolve101)=>setTimeout(resolve101,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){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,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{return await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}}),(await findDelegationForCompletion(directory,record3.subagentSessionId))?.record.status==="consumed"}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=errorCode(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 errorCode(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 createHash83("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash83("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 fs140 from"node:fs";import*as path253 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=path253.join(projectDirectory,".swarm"),dest=path253.join(swarmDir,"config.example.json");if(fs140.existsSync(dest))return;if(!fs140.existsSync(swarmDir))fs140.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};fs140.writeFileSync(dest,`${JSON.stringify(example,null,2)}
|
|
6862
6870
|
`,"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=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);output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs143 from"node:fs";import*as path256 from"node:path";import*as fs142 from"node:fs";import*as path255 from"node:path";import*as crypto13 from"node:crypto";import*as fs141 from"node:fs";import*as path254 from"node:path";var _internals204={readFileSync:fs141.readFileSync,writeFileSync:fs141.writeFileSync,mkdirSync:fs141.mkdirSync,renameSync:fs141.renameSync,existsSync:fs141.existsSync,statSync:fs141.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals204.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=path254.join(directory,".swarm","context-map.json");try{if(!_internals204.existsSync(filePath))return null;let raw=_internals204.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=path254.join(directory,".swarm"),tmpPath=path254.join(swarmDir,"context-map.tmp"),finalPath=path254.join(swarmDir,"context-map.json");_internals204.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals204.writeFileSync(tmpPath,json3,"utf-8"),_internals204.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=path255.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=extractImports5(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs142.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 extractImports5(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(`
|
|
6863
6871
|
`).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(!_internals205.existsSync(absolutePath2))return null;return _internals205.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals205.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals205={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs143.existsSync,readFileSync:fs143.readFileSync,readdirSync:fs143.readdirSync,realpathSync:fs143.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path256.join(directory,".swarm","evidence",taskId);if(!_internals205.existsSync(evidenceDir))return result;let evidenceFiles=_internals205.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=path256.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=_internals205.loadContextMap(params.directory);if(map3===null)map3=_internals205.createEmptyContextMap();let root=path256.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals205.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path256.resolve(root,filePath),realResolved=_internals205.realpathSync(resolved),relative60=path256.relative(realRoot,realResolved);if(relative60.startsWith("..")||path256.isAbsolute(relative60))continue;let normalizedRelative=relative60.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=_internals205.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=_internals205.appendDecision(map3,decision)}return _internals205.saveContextMap(map3,params.directory),map3}catch{try{return _internals205.loadContextMap(params.directory)??_internals205.createEmptyContextMap()}catch{return _internals205.createEmptyContextMap()}}}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){_internals206.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals206.now(),hydrated:!0};try{let row=_internals206.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals206.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){_internals206.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=_internals206.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 _internals206.sleep(Math.min(waitMs,1000))}}var _internals206={now:()=>Date.now(),sleep:(ms)=>new Promise((resolve102)=>setTimeout(resolve102,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 _internals207=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals183.boundedAbort,set:(value)=>{_internals183.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals183.boundedDelete,set:(value)=>{_internals183.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals183.log,set:(value)=>{_internals183.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve102,reject)=>{let onAbort=()=>reject(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve102,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(state,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state.counters.toolCalls>0&&state.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state.counters.architectTurns>0&&state.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state.lastOversightAt){let lastTs=Date.parse(state.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state.denialCounters.consecutive>=denials.maxConsecutive-1&&state.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state.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 resolveOversightAgentName(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=resolveOversightAgentName(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,path257=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path257,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(`
|
|
6864
6872
|
`);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(`
|
|
@@ -7054,18 +7062,18 @@ ${activitySection}`;break}if(contextSummary.length>maxChars)return`${contextSumm
|
|
|
7054
7062
|
`).length,byteSize=Buffer.byteLength(output,"utf8"),formattedSize=formatBytes2(byteSize),headerLine=`[SUMMARY ${summaryId}] ${formattedSize} | ${contentType} | ${lineCount} lines`,footerLine=`→ Use /swarm retrieve ${summaryId} for full content`,overhead=Buffer.byteLength(headerLine,"utf8")+1+Buffer.byteLength(footerLine,"utf8")+1,maxPreviewChars=maxSummaryChars-overhead,preview;switch(contentType){case"json":{try{let parsed=JSON.parse(output.trim());if(Array.isArray(parsed))preview=summarizeJsonArray(parsed);else if(typeof parsed==="object"&&parsed!==null)preview=summarizeJsonObject(parsed);else preview=summarizeText(output,3)}catch{preview=summarizeText(output,3)}break}case"code":{preview=summarizeCode(output);break}case"text":{preview=summarizeText(output,5);break}case"binary":{preview=`[Binary content - ${formattedSize}]`;break}default:preview=summarizeText(output,5)}let previewBytes=Buffer.byteLength(preview,"utf8");if(previewBytes>maxPreviewChars){let marker=`[... ${previewBytes} bytes total, truncated ...]`;if(Buffer.byteLength(marker,"utf8")>maxPreviewChars)marker="...";let{text:kept}=truncateToBytes(preview,Math.max(0,maxPreviewChars-Buffer.byteLength(marker,"utf8")));preview=`${kept}${marker}`}return`${headerLine}
|
|
7055
7063
|
${preview}
|
|
7056
7064
|
${footerLine}`}init_utils();var nextSummaryId=1;function createToolSummarizerHook(config3,directory){if(config3.enabled===!1)return async()=>{};return async(input,output)=>{if(typeof output.output!=="string"||output.output.length===0)return;let exemptTools=config3.exempt_tools??[];if(SUMMARIZER_EXEMPT_TOOL_NAMES.includes(input.tool)||exemptTools.includes(input.tool))return;if(!shouldSummarize(output.output,config3.threshold_bytes))return;let summaryId=`S${nextSummaryId++}`,summaryText=createSummary(output.output,input.tool,summaryId,config3.max_summary_chars);try{await storeSummary(directory,summaryId,output.output,summaryText,config3.max_stored_bytes),output.output=summaryText}catch(error93){warn(`Tool output summarization failed for ${summaryId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}}init_utils2();init_schema();init_core_events();init_engine2();init_runtime3();init_state2();init_logger();init_normalize_tool_name();var MAX_TRACKED_SESSIONS7=256,COOLDOWN_MS=60000;function injectAutoReviewAdvisory(injectAdvisory,sessionID,message){try{injectAdvisory(sessionID,message)}catch(error93){warn(`[auto-review] advisory injection failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}function evictCooldownMap(lastDispatchBySession){while(lastDispatchBySession.size>MAX_TRACKED_SESSIONS7){let firstKey=lastDispatchBySession.keys().next().value;if(firstKey===void 0)break;lastDispatchBySession.delete(firstKey)}}function writeAutoReviewEvent(directory,event){try{appendCoreEventSync(directory,{...event})}catch(error93){warn(`[auto-review] event write failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}async function runAutoReview(input){if(!input.dispatcher){writeAutoReviewEvent(input.directory,{type:"auto_review",timestamp:new Date().toISOString(),session_id:input.sessionID,trigger:"task_completion",task_id:input.taskId,verdict:"error",detail:"review runtime unavailable",model_calls:0});return}try{let agents=resolveReviewAgentNames(input.generatedAgentNames??swarmState.generatedAgentNames,input.activeAgentName),result=await _internals219.runReviewEngine({directory:input.directory,sessionID:input.sessionID,trigger:"task_completion",selector:{kind:"working-tree"},config:input.config,dispatcher:input.dispatcher,reviewerAgent:agents.reviewer,validatorAgent:agents.validator,reviewerFallbackModels:resolveReviewFallbackModels(agents.reviewer,input.agentModelRegistry),validatorModel:optionalModelOverride(input.config.validation_model),validatorFallbackModels:resolveReviewFallbackModels(agents.validator,input.agentModelRegistry),injectAdvisory:input.injectAdvisory});return writeAutoReviewEvent(input.directory,{type:"auto_review",timestamp:new Date().toISOString(),session_id:input.sessionID,trigger:"task_completion",task_id:input.taskId,verdict:result.reviewVerdict??result.status,detail:result.message,receipt_path:result.receiptPath,evidence_path:result.evidencePath,scope_hash:result.scopeHash,model_calls:result.modelCalls}),result}catch(error93){warn(`[auto-review] run failed: ${error93 instanceof Error?error93.message:String(error93)}`),writeAutoReviewEvent(input.directory,{type:"auto_review",timestamp:new Date().toISOString(),session_id:input.sessionID,trigger:"task_completion",task_id:input.taskId,verdict:"error",detail:error93 instanceof Error?error93.message:String(error93),model_calls:0});return}}function createAutoReviewHook(options){let config3=AutoReviewConfigSchema.parse(options.config),inFlightSessions=new Set,lastDispatchBySession=new Map,resetTracking=()=>{inFlightSessions.clear(),lastDispatchBySession.clear()},generatedAgentNames=options.generatedAgentNames?Object.freeze([...options.generatedAgentNames]):void 0;if(!(config3.enabled&&(config3.trigger==="task_completion"||config3.trigger==="both")))return{toolAfter:async()=>{},resetTracking};return{resetTracking,toolAfter:async(input,context)=>{try{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase(),args2=context.args??void 0;if(tool3!=="update_task_status"||args2?.status!=="completed"||!input.sessionID)return;let agentName=options.getActiveAgentName?.(input.sessionID)??swarmState.activeAgent.get(input.sessionID)??swarmState.agentSessions.get(input.sessionID)?.agentName??"";if(agentName&&stripKnownSwarmPrefix(agentName)!=="architect")return;if(inFlightSessions.has(input.sessionID))return;let now2=_internals219.now();if(now2-(lastDispatchBySession.get(input.sessionID)??0)<COOLDOWN_MS)return;let taskId=typeof args2.task_id==="string"?args2.task_id:void 0;if(inFlightSessions.size>=MAX_TRACKED_SESSIONS7){let detail=`active review capacity reached (${MAX_TRACKED_SESSIONS7}); task-completion review skipped`;writeAutoReviewEvent(options.directory,{type:"auto_review",timestamp:new Date().toISOString(),session_id:input.sessionID,trigger:"task_completion",task_id:taskId,verdict:"skipped",detail,model_calls:0}),injectAutoReviewAdvisory(options.injectAdvisory,input.sessionID,`[AUTO-REVIEW TASK_COMPLETION] ${detail}. Completion remains fail-open.`);return}inFlightSessions.add(input.sessionID),lastDispatchBySession.delete(input.sessionID),lastDispatchBySession.set(input.sessionID,now2),evictCooldownMap(lastDispatchBySession);let runInput={directory:options.directory,sessionID:input.sessionID,trigger:"task_completion",taskId,config:config3,dispatcher:options.dispatcher,generatedAgentNames,activeAgentName:agentName||void 0,agentModelRegistry:options.agentModelRegistry,injectAdvisory:options.injectAdvisory},pending;try{pending=Promise.resolve(_internals219.runAutoReview(runInput))}catch(error93){inFlightSessions.delete(input.sessionID);let detail=`unexpected review scheduler failure: ${error93 instanceof Error?error93.message:String(error93)}`;writeAutoReviewEvent(options.directory,{type:"auto_review",timestamp:new Date().toISOString(),session_id:input.sessionID,trigger:"task_completion",task_id:taskId,verdict:"error",detail,model_calls:0}),injectAutoReviewAdvisory(options.injectAdvisory,input.sessionID,`[AUTO-REVIEW TASK_COMPLETION] ${detail}. Completion remains fail-open.`);return}pending.catch((error93)=>{let detail=`unexpected review scheduler rejection: ${error93 instanceof Error?error93.message:String(error93)}`;writeAutoReviewEvent(options.directory,{type:"auto_review",timestamp:new Date().toISOString(),session_id:input.sessionID,trigger:"task_completion",task_id:taskId,verdict:"error",detail,model_calls:0}),injectAutoReviewAdvisory(options.injectAdvisory,input.sessionID,`[AUTO-REVIEW TASK_COMPLETION] ${detail}. Completion remains fail-open.`)}).finally(()=>{inFlightSessions.delete(input.sessionID)})}catch(error93){warn(`[auto-review] hook error: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}var _internals219={runReviewEngine,runAutoReview,now:()=>Date.now()};init_utils();init_bun_compat();init_utils2();function normalizePath3(filePath){return filePath.replace(/\\/g,"/")}async function readCoChangeJson(directory){try{let filePath=validateSwarmPath(directory,"co-change.json"),content=await bunFile(filePath).text(),data=JSON.parse(content);if(!data||typeof data.version!=="string"||!Array.isArray(data.entries))return null;let seen=new Set,dedupedEntries=[];for(let entry of data.entries){if(typeof entry.fileA!=="string"||typeof entry.fileB!=="string"||typeof entry.coChangeCount!=="number"||typeof entry.npmi!=="number")continue;let normalizedA=normalizePath3(entry.fileA),normalizedB=normalizePath3(entry.fileB),key2=[normalizedA,normalizedB].sort().join("|");if(!seen.has(key2))seen.add(key2),dedupedEntries.push(entry)}return{...data,entries:dedupedEntries}}catch{return null}}function getCoChangePartnersForFile(entries2,filePath){let normalizedTarget=normalizePath3(filePath);return entries2.filter((entry)=>{let normalizedA=normalizePath3(entry.fileA),normalizedB=normalizePath3(entry.fileB);return normalizedA===normalizedTarget||normalizedB===normalizedTarget})}function createCoChangeSuggesterHook(directory){return safeHook(async(input,_output)=>{let record3=input,toolName=typeof record3.tool==="string"?record3.tool:"";if(!["write","edit","apply_patch","swarm_apply_patch","patch","create_file"].includes(toolName))return;let toolInput=record3.input,filePath=toolInput?.filePath??toolInput?.file_path??toolInput?.path;if(!filePath)return;let coChangeData=await readCoChangeJson(directory);if(!coChangeData)return;let partners=getCoChangePartnersForFile(coChangeData.entries,filePath);if(partners.length===0)return;let partnerList=partners.slice(0,3).map((e)=>{let normalizedFilePath=normalizePath3(filePath);return`${normalizePath3(e.fileA)===normalizedFilePath?e.fileB:e.fileA} (co-change: ${e.coChangeCount}x, npmi: ${e.npmi.toFixed(2)})`}).join(", ");log(`[CO-CHANGE] Files frequently modified with ${filePath}: ${partnerList}`)})}init_cohort_cache();init_utils();init_bun_compat();init_utils2();function parseDarkMatterGaps(content){let unresolved=[],resolved=[],lines=content.split(`
|
|
7057
|
-
`);for(let line of lines){let unresolvedMatch=line.match(/^-\s+\[\s*\]\s*(.+)$/);if(unresolvedMatch){unresolved.push(unresolvedMatch[1].trim());continue}let resolvedMatch=line.match(/^-\s+\[x\]\s*(.+)$/i);if(resolvedMatch)resolved.push(resolvedMatch[1].trim())}return{unresolved,resolved}}async function readDarkMatterMd(directory){let filePath=validateSwarmPath(directory,"dark-matter.md"),file3=bunFile(filePath);try{let content=await file3.text();if(!content||!content.trim())return null;return parseDarkMatterGaps(content)}catch{return null}}function createDarkMatterDetectorHook(directory){let callCount=0;async function hook(_input,_output){if(callCount++,callCount%10!==0)return;let gaps=await readDarkMatterMd(directory);if(!gaps||gaps.unresolved.length===0)return;let count=gaps.unresolved.length;log(`[DARK-MATTER] ${count} unresolved coupling gap(s) in .swarm/dark-matter.md. Run /swarm dark-matter to review.`);let displayGaps=gaps.unresolved.slice(0,3);for(let description of displayGaps)log(` - ${description}`);if(count>3)log(` - ... and ${count-3} more`)}return safeHook(hook)}init_delegate_ack_collector();init_reviewer_directive_compliance();init_schema();init_manager();init_logger();init_extractors();init_knowledge_events();init_knowledge_injector();init_phase_directives();init_plan_task_id_context();init_skill_propagation_gate();init_task_id_resolver();function recordDelegateInjectionSkip(directory,reason,options){recordKnowledgeEvent(directory,{type:"injection_skip",reason,agent:options?.agent,session_id:options?.sessionId,detail:options?.detail}).catch(()=>{})}function isTaskTool4(tool3){return tool3==="Task"||tool3==="task"}function hasDelegateDirectiveBlock(text){return parseDelegateDirectiveBlock(text).length>0}function hasDirectiveComplianceBlock(text){return parseDirectivesToVerifyBlock(text).length>0}async function injectDelegateDirectivesBefore(directory,input,config3){let sessionId;try{sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;let debugSkip=(reason,data)=>{return log("[delegate-directive-injection] skipped",{reason,caller_agent:typeof input.agent==="string"?input.agent:void 0,tool:input.tool,...data}),0};if(config3.enabled===!1)return debugSkip("knowledge_disabled");if(!isTaskTool4(input.tool))return debugSkip("not_task_tool");let callerAgent=typeof input.agent==="string"?input.agent:"",callerRole=stripKnownSwarmPrefix(callerAgent).toLowerCase();if(!callerAgent||callerRole!=="architect")return recordDelegateInjectionSkip(directory,"delegate_caller_not_allowed",{agent:callerAgent||void 0,sessionId,detail:{caller_role:callerRole}}),debugSkip("caller_not_allowed",{caller_role:callerRole});let argsRecord=input.args&&typeof input.args==="object"?input.args:null;if(!argsRecord)return recordDelegateInjectionSkip(directory,"delegate_missing_args",{agent:callerAgent,sessionId}),debugSkip("missing_args");let promptRaw=argsRecord.prompt;if(typeof promptRaw!=="string")return recordDelegateInjectionSkip(directory,"delegate_missing_prompt",{agent:callerAgent,sessionId}),debugSkip("missing_prompt");let parsed=parseDelegationArgs(input.args);if(!parsed)return recordDelegateInjectionSkip(directory,"delegate_unparseable_delegation_args",{agent:callerAgent,sessionId}),debugSkip("unparseable_delegation_args");let targetAgent=parsed.targetAgent;if(!isDelegatedAgent(targetAgent))return recordDelegateInjectionSkip(directory,"delegate_target_not_delegated_agent",{agent:targetAgent,sessionId,detail:{target_agent:targetAgent}}),debugSkip("target_not_delegated_agent",{target_agent:targetAgent});if(hasDelegateDirectiveBlock(promptRaw)||hasDirectiveComplianceBlock(promptRaw))return recordDelegateInjectionSkip(directory,"delegate_already_injected",{agent:targetAgent,sessionId}),debugSkip("already_injected",{target_agent:targetAgent});let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,planTaskIdOptions=plan?toTaskIdPlanContextOptions(collectPlanTaskIdContextFromPhases(plan.phases)):{},taskIdResolution=resolveTaskId(argsRecord,{policy:"attribution",...planTaskIdOptions}),taskId=taskIdResolution.status==="resolved"?taskIdResolution.taskId:void 0,{entries:entries2,trace_id}=await injectForDelegate({directory,agent:targetAgent,expectedTools:defaultExpectedToolsForAgent(targetAgent),taskTitle:promptRaw.slice(0,800),taskId,sessionId,phase:phaseLabel,config:config3}),prefixParts=[],delegateBlock=buildDelegateDirectiveBlock(entries2,config3,trace_id,Math.min(config3.inject_char_budget??2000,DELEGATE_INJECT_HARD_CHAR_CAP));if(delegateBlock)prefixParts.push(delegateBlock);if(stripKnownSwarmPrefix(targetAgent).toLowerCase()==="reviewer"){let toVerify=await readPhaseDirectivesToVerify(directory,phaseLabel),complianceBlock=buildDirectiveComplianceBlock(toVerify);if(complianceBlock)prefixParts.push(complianceBlock)}if(prefixParts.length===0)return recordDelegateInjectionSkip(directory,"delegate_no_directives_to_inject",{agent:targetAgent,sessionId}),debugSkip("no_directives_to_inject",{target_agent:targetAgent});return argsRecord.prompt=`${prefixParts.join(`
|
|
7065
|
+
`);for(let line of lines){let unresolvedMatch=line.match(/^-\s+\[\s*\]\s*(.+)$/);if(unresolvedMatch){unresolved.push(unresolvedMatch[1].trim());continue}let resolvedMatch=line.match(/^-\s+\[x\]\s*(.+)$/i);if(resolvedMatch)resolved.push(resolvedMatch[1].trim())}return{unresolved,resolved}}async function readDarkMatterMd(directory){let filePath=validateSwarmPath(directory,"dark-matter.md"),file3=bunFile(filePath);try{let content=await file3.text();if(!content||!content.trim())return null;return parseDarkMatterGaps(content)}catch{return null}}function createDarkMatterDetectorHook(directory){let callCount=0;async function hook(_input,_output){if(callCount++,callCount%10!==0)return;let gaps=await readDarkMatterMd(directory);if(!gaps||gaps.unresolved.length===0)return;let count=gaps.unresolved.length;log(`[DARK-MATTER] ${count} unresolved coupling gap(s) in .swarm/dark-matter.md. Run /swarm dark-matter to review.`);let displayGaps=gaps.unresolved.slice(0,3);for(let description of displayGaps)log(` - ${description}`);if(count>3)log(` - ... and ${count-3} more`)}return safeHook(hook)}init_delegate_ack_collector();init_reviewer_directive_compliance();init_schema();init_manager();init_logger();init_extractors();init_knowledge_events();init_knowledge_injector();init_phase_directives();init_plan_task_id_context();init_skill_propagation_gate();init_task_id_resolver();function recordDelegateInjectionSkip(directory,reason,options){recordKnowledgeEvent(directory,{type:"injection_skip",reason,agent:options?.agent,session_id:options?.sessionId,detail:options?.detail}).catch(()=>{})}function isTaskTool4(tool3){return tool3==="Task"||tool3==="task"}function hasDelegateDirectiveBlock(text){return parseDelegateDirectiveBlock(text).length>0}function hasDirectiveComplianceBlock(text){return parseDirectivesToVerifyBlock(text).length>0}async function injectDelegateDirectivesBefore(directory,input,config3){let sessionId;try{sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;let debugSkip=(reason,data)=>{return log("[delegate-directive-injection] skipped",{reason,caller_agent:typeof input.agent==="string"?input.agent:void 0,tool:input.tool,...data}),0};if(config3.enabled===!1)return debugSkip("knowledge_disabled");if(!isTaskTool4(input.tool))return debugSkip("not_task_tool");let callerAgent=typeof input.agent==="string"?input.agent:"",callerRole=stripKnownSwarmPrefix(callerAgent).toLowerCase();if(!callerAgent||callerRole!=="architect")return recordDelegateInjectionSkip(directory,"delegate_caller_not_allowed",{agent:callerAgent||void 0,sessionId,detail:{caller_role:callerRole}}),debugSkip("caller_not_allowed",{caller_role:callerRole});let argsRecord=input.args&&typeof input.args==="object"?input.args:null;if(!argsRecord)return recordDelegateInjectionSkip(directory,"delegate_missing_args",{agent:callerAgent,sessionId}),debugSkip("missing_args");let promptRaw=argsRecord.prompt;if(typeof promptRaw!=="string")return recordDelegateInjectionSkip(directory,"delegate_missing_prompt",{agent:callerAgent,sessionId}),debugSkip("missing_prompt");let parsed=parseDelegationArgs(input.args);if(!parsed)return recordDelegateInjectionSkip(directory,"delegate_unparseable_delegation_args",{agent:callerAgent,sessionId}),debugSkip("unparseable_delegation_args");let targetAgent=parsed.targetAgent;if(!isDelegatedAgent(targetAgent))return recordDelegateInjectionSkip(directory,"delegate_target_not_delegated_agent",{agent:targetAgent,sessionId,detail:{target_agent:targetAgent}}),debugSkip("target_not_delegated_agent",{target_agent:targetAgent});if(hasDelegateDirectiveBlock(promptRaw)||hasDirectiveComplianceBlock(promptRaw))return recordDelegateInjectionSkip(directory,"delegate_already_injected",{agent:targetAgent,sessionId}),debugSkip("already_injected",{target_agent:targetAgent});let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,planTaskIdOptions=plan?toTaskIdPlanContextOptions(collectPlanTaskIdContextFromPhases(plan.phases)):{},taskIdResolution=resolveTaskId(argsRecord,{policy:"attribution",...planTaskIdOptions}),taskId=taskIdResolution.status==="resolved"?taskIdResolution.taskId:void 0,{entries:entries2,trace_id}=await injectForDelegate({directory,agent:targetAgent,expectedTools:defaultExpectedToolsForAgent(targetAgent),taskTitle:promptRaw.slice(0,800),taskId,sessionId,phase:phaseLabel,config:config3}),prefixParts=[],delegateBlock=buildDelegateDirectiveBlock(entries2,config3,trace_id,Math.min(config3.inject_char_budget??2000,DELEGATE_INJECT_HARD_CHAR_CAP));if(delegateBlock)prefixParts.push(delegateBlock);if(stripKnownSwarmPrefix(targetAgent).toLowerCase()==="reviewer"){let toVerify=await readPhaseDirectivesToVerify(directory,phaseLabel),complianceBlock=buildDirectiveComplianceBlock(toVerify,Math.min(config3.inject_char_budget??DIRECTIVE_COMPLIANCE_DEFAULT_CHAR_BUDGET,DIRECTIVE_COMPLIANCE_HARD_CHAR_CAP));if(complianceBlock)prefixParts.push(complianceBlock)}if(prefixParts.length===0)return recordDelegateInjectionSkip(directory,"delegate_no_directives_to_inject",{agent:targetAgent,sessionId}),debugSkip("no_directives_to_inject",{target_agent:targetAgent});return argsRecord.prompt=`${prefixParts.join(`
|
|
7058
7066
|
|
|
7059
7067
|
`)}
|
|
7060
7068
|
|
|
7061
7069
|
${promptRaw}`,log("[delegate-directive-injection] injected",{caller_agent:callerAgent,caller_role:callerRole,target_agent:targetAgent,count:entries2.length,session_id:sessionId}),entries2.length}catch(err){let message=err instanceof Error?err.message:String(err);return recordDelegateInjectionSkip(directory,"delegate_injection_error",{sessionId,detail:{message}}),warn(`[delegate-directive-injection] non-fatal: ${message}`),0}}init_state2();init_normalize_tool_name();var ledgerBySession=new Map,MAX_TRACKED_SESSIONS8=500,MAX_LEDGER_ENTRIES_PER_SESSION=200,droppedEntryCounts=new Map,callStartTimes2=new Map;function createDelegationLedgerHook(config3,_directory2,injectAdvisory){let enabled=config3.enabled??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID,startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes2.get(startKey)??Date.now();callStartTimes2.delete(startKey);let duration_ms=Date.now()-startTime,args2=input.args??{},file3=typeof args2.path==="string"?args2.path:typeof args2.filePath==="string"?args2.filePath:typeof args2.file==="string"?args2.file:void 0,session=swarmState.agentSessions.get(sessionId),agentName=swarmState.activeAgent?.get(sessionId)??session?.agentName??"unknown",outputStr=String(output.output??""),success3=!outputStr.startsWith("Error:")&&!outputStr.startsWith("error: "),entry={agent:agentName,tool:input.tool,file:file3,duration_ms,success:success3,timestamp:Date.now()},existing=ledgerBySession.get(sessionId)??[];if(existing.push(entry),existing.length>MAX_LEDGER_ENTRIES_PER_SESSION){let dropped=existing.length-MAX_LEDGER_ENTRIES_PER_SESSION;existing.splice(0,dropped),droppedEntryCounts.set(sessionId,(droppedEntryCounts.get(sessionId)??0)+dropped)}ledgerBySession.set(sessionId,existing);while(ledgerBySession.size>MAX_TRACKED_SESSIONS8){let oldest=ledgerBySession.keys().next().value;if(oldest===void 0||oldest===sessionId)break;ledgerBySession.delete(oldest),droppedEntryCounts.delete(oldest)}},onArchitectResume:(architectSessionId)=>{if(!enabled)return;let allEntries=[],totalDroppedEntries=0;for(let[sessionId,entries2]of ledgerBySession){if(sessionId===architectSessionId)continue;allEntries.push(...entries2),totalDroppedEntries+=droppedEntryCounts.get(sessionId)??0}if(allEntries.length===0)return;for(let sessionId of ledgerBySession.keys())if(sessionId!==architectSessionId)ledgerBySession.delete(sessionId),droppedEntryCounts.delete(sessionId);let toolCallCount=allEntries.length,filesModified=[...new Set(allEntries.filter((e)=>isWriteTool3(e.tool)&&e.file).map((e)=>e.file))],filesRead=[...new Set(allEntries.filter((e)=>isReadTool(e.tool)&&e.file).map((e)=>e.file))],failedCalls=allEntries.filter((e)=>!e.success).length,scopeViolations=allEntries.filter((e)=>e.tool.includes("scope")).length,summary=["DELEGATION SUMMARY:",` Tool calls: ${toolCallCount}${failedCalls>0?` (${failedCalls} failed)`:""}`,filesModified.length>0?` Files modified: ${filesModified.slice(0,5).join(", ")}${filesModified.length>5?` (+${filesModified.length-5} more)`:""}`:null,filesRead.length>0?` Files read: ${filesRead.slice(0,5).join(", ")}${filesRead.length>5?` (+${filesRead.length-5} more)`:""}`:null,scopeViolations>0?` ⚠️ ${scopeViolations} scope violation(s) detected`:null,totalDroppedEntries>0?` ...and ${totalDroppedEntries} earlier call(s) omitted (per-session ledger cap)`:null].filter(Boolean).join(`
|
|
7062
|
-
`);try{injectAdvisory(architectSessionId,summary)}catch{}}}}var WRITE_TOOL_PATTERNS=["write","edit","patch","create","insert","replace","append","prepend"];function isWriteTool3(toolName){let normalized=normalizeToolNameLowerCase(toolName);return WRITE_TOOL_PATTERNS.some((p)=>normalized.includes(p))}var READ_TOOL_PATTERNS=["read","cat","view","fetch","get"];function isReadTool(toolName){let normalized=normalizeToolNameLowerCase(toolName);return READ_TOOL_PATTERNS.some((p)=>normalized.includes(p))}init_constants();init_schema();init_core_events();init_policy();init_severe_result();init_state3();init_state2();init_logger();init_normalize_tool_name();var RETURN_WARNING_PATTERNS=[{category:"skipped_tests",regex:/\b(?:skipped (?:the )?tests?|tests? (?:were |was )?skipped|did(?:n['']t)? run tests?|tests? not run|bypass(?:ed)? (?:the )?tests?|test (?:step|phase) (?:was )?bypass|tests? (?:are )?failing|tests? (?:are )?broken)\b/i},{category:"tool_timeout",regex:/\b(?:tool|process|command|test|build|lint)\s+(?:timed out|timeout|hung|killed|aborted|terminated|did not (?:complete|finish))/i},{category:"scope_changed",regex:/\b(?:expanded|changed|widened|exceeded|broke|extended|enlarged|grew|altered|adjusted) (?:the )?(?:declared |working |task |allowed )?(?:scope|file ?list|file ?set|working set|set of files)\b|\bscope (?:expansion|creep|drift|change)\b/i},{category:"external_instructions",regex:/\b(?:followed |received |applied |honored |obeyed )?(?:instructions|directives|guidance|orders|commands|hints) (?:from|in|per|according to) (?:the )?(?:tool output|web|search|fetched|fetch|external|untrusted|upstream|page|site|doc|documentation|response|prompt)\b|\bper (?:the )?(?:upstream|external|fetched|web|tool) (?:doc|documentation|page|response|content|guidance)\b/i},{category:"unable_to_verify",regex:/\b(?:unable|could ?n['']t|cannot|can ?not|wasn['']?t able) (?:to )?(?:verify|confirm|reproduce|test|check|validate|prove)\b|\bverification (?:deferred|skipped|postponed|incomplete|pending|impossible)\b/i},{category:"missing_evidence",regex:/\b(?:no |missing |without |lacking )(?:evidence|proof|verification|tests? passing|test results|coverage)\b|\bevidence (?:is )?(?:missing|absent|unavailable)\b/i},{category:"out_of_scope_files",regex:/\b(?:created|generated|wrote|modified|added|edited|patched|touched) (?:files? |code )?(?:outside|beyond|past|not in|that (?:are|were) outside) (?:the )?(?:declared |task |coder |allowed )?(?:scope|file ?list|file ?set|allowed (?:paths|files))\b/i}],CANONICAL_ROLES_LOWER=new Set(ALL_AGENT_NAMES.map((s)=>s.toLowerCase())),PROTECTED_PATH_SCAN=/(?:^|\s)([A-Za-z0-9._/-]+(?:\.[A-Za-z0-9_-]+|\/(?:CODEOWNERS|package\.json|bun\.lock|CHANGELOG\.md)))/g,BARE_PROTECTED_PATH_SCAN=[".git",".opencode",".swarm",".github/workflows","docs/releases","src/security","src/hooks/guardrails"].map((entry)=>entry.toLowerCase());function isExactCanonicalRole(name){return CANONICAL_ROLES_LOWER.has(name.toLowerCase())}function isTaskTool5(toolName){let lower=toolName
|
|
7070
|
+
`);try{injectAdvisory(architectSessionId,summary)}catch{}}}}var WRITE_TOOL_PATTERNS=["write","edit","patch","create","insert","replace","append","prepend"];function isWriteTool3(toolName){let normalized=normalizeToolNameLowerCase(toolName);return WRITE_TOOL_PATTERNS.some((p)=>normalized.includes(p))}var READ_TOOL_PATTERNS=["read","cat","view","fetch","get"];function isReadTool(toolName){let normalized=normalizeToolNameLowerCase(toolName);return READ_TOOL_PATTERNS.some((p)=>normalized.includes(p))}init_constants();init_schema();init_core_events();init_policy();init_severe_result();init_state3();init_state2();init_logger();init_normalize_tool_name();var RETURN_WARNING_PATTERNS=[{category:"skipped_tests",regex:/\b(?:skipped (?:the )?tests?|tests? (?:were |was )?skipped|did(?:n['']t)? run tests?|tests? not run|bypass(?:ed)? (?:the )?tests?|test (?:step|phase) (?:was )?bypass|tests? (?:are )?failing|tests? (?:are )?broken)\b/i},{category:"tool_timeout",regex:/\b(?:tool|process|command|test|build|lint)\s+(?:timed out|timeout|hung|killed|aborted|terminated|did not (?:complete|finish))/i},{category:"scope_changed",regex:/\b(?:expanded|changed|widened|exceeded|broke|extended|enlarged|grew|altered|adjusted) (?:the )?(?:declared |working |task |allowed )?(?:scope|file ?list|file ?set|working set|set of files)\b|\bscope (?:expansion|creep|drift|change)\b/i},{category:"external_instructions",regex:/\b(?:followed |received |applied |honored |obeyed )?(?:instructions|directives|guidance|orders|commands|hints) (?:from|in|per|according to) (?:the )?(?:tool output|web|search|fetched|fetch|external|untrusted|upstream|page|site|doc|documentation|response|prompt)\b|\bper (?:the )?(?:upstream|external|fetched|web|tool) (?:doc|documentation|page|response|content|guidance)\b/i},{category:"unable_to_verify",regex:/\b(?:unable|could ?n['']t|cannot|can ?not|wasn['']?t able) (?:to )?(?:verify|confirm|reproduce|test|check|validate|prove)\b|\bverification (?:deferred|skipped|postponed|incomplete|pending|impossible)\b/i},{category:"missing_evidence",regex:/\b(?:no |missing |without |lacking )(?:evidence|proof|verification|tests? passing|test results|coverage)\b|\bevidence (?:is )?(?:missing|absent|unavailable)\b/i},{category:"out_of_scope_files",regex:/\b(?:created|generated|wrote|modified|added|edited|patched|touched) (?:files? |code )?(?:outside|beyond|past|not in|that (?:are|were) outside) (?:the )?(?:declared |task |coder |allowed )?(?:scope|file ?list|file ?set|allowed (?:paths|files))\b/i}],CANONICAL_ROLES_LOWER=new Set(ALL_AGENT_NAMES.map((s)=>s.toLowerCase())),PROTECTED_PATH_SCAN=/(?:^|\s)([A-Za-z0-9._/-]+(?:\.[A-Za-z0-9_-]+|\/(?:CODEOWNERS|package\.json|bun\.lock|CHANGELOG\.md)))/g,BARE_PROTECTED_PATH_SCAN=[".git",".opencode",".swarm",".github/workflows","docs/releases","src/security","src/hooks/guardrails"].map((entry)=>entry.toLowerCase());function isExactCanonicalRole(name){return CANONICAL_ROLES_LOWER.has(name.toLowerCase())}function isTaskTool5(toolName){if(isTaskToolId(toolName))return!0;let lower=normalizeToolNameLowerCase(toolName??"");return lower==="agent"||lower==="delegate"}function extractText(value){if(typeof value==="string")return value;if(value&&typeof value==="object"){let o=value;if(typeof o.output==="string")return o.output;if(typeof o.text==="string")return o.text;if(typeof o.summary==="string")return o.summary;try{return JSON.stringify(o)}catch{return""}}return""}function collectStrings(value,out,seen=new WeakSet){if(typeof value==="string"){if(out.length>=64)return!1;return out.push(value),!0}if(!value||typeof value!=="object")return!0;if(seen.has(value))return!0;if(seen.add(value),Array.isArray(value)){for(let item of value)if(!collectStrings(item,out,seen))return!1;return!0}for(let[key2,item]of Object.entries(value)){if(!collectStrings(key2,out,seen))return!1;if(!collectStrings(item,out,seen))return!1}return!0}function scanForProtectedPaths(args2,config3){let strings=[],complete=collectStrings(args2,strings),candidatePaths=new Set;for(let text of strings){for(let match of text.matchAll(PROTECTED_PATH_SCAN)){let candidate2=match[1]?.trim();if(candidate2)candidatePaths.add(candidate2)}let normalized=text.replace(/\\/g,"/").toLowerCase();for(let candidate2 of BARE_PROTECTED_PATH_SCAN){let escaped=candidate2.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=normalized.match(new RegExp(`(?:^|[^A-Za-z0-9._/-])(${escaped})(?=$|[^A-Za-z0-9._/-])`,"i"));if(match?.[1])candidatePaths.add(match[1])}}let hits=[];for(let candidate2 of candidatePaths)if(isProtectedPath(candidate2,config3))hits.push(candidate2);return{complete,hits}}function detectReturnWarnings(text){let warnings=[];if(!text)return warnings;let seen=new Set;for(let{category,regex}of RETURN_WARNING_PATTERNS){let m=text.match(regex);if(!m)continue;let key2=`${category}:${m[0].toLowerCase()}`;if(seen.has(key2))continue;seen.add(key2),warnings.push({category,matched:m[0]})}return warnings}async function writeDelegationEvent(directory,event){try{appendCoreEventSync(directory,event)}catch(error93){throw error48(`[full-auto/delegation] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`),error93}}function createFullAutoDelegationHook(options){let{config:config3,directory}=options;return{toolBefore:async(input,output)=>{let tool3=input.tool??"";if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let args2=output.args??{},subagentRaw=typeof args2.subagent_type==="string"&&args2.subagent_type||typeof args2.agent==="string"&&args2.agent||"",generatedAgentRegistry=swarmState.generatedAgentNames,canonicalRole2=generatedAgentRegistry.length>0?resolveGeneratedAgentRole(subagentRaw,generatedAgentRegistry):getCanonicalAgentRole(subagentRaw);if(subagentRaw&&canonicalRole2!==subagentRaw&&!isExactCanonicalRole(subagentRaw)){if(!subagentRaw.slice(0,subagentRaw.length-canonicalRole2.length-1))throw Error(`FULL_AUTO_DELEGATION_DENY: subagent name '${subagentRaw}' has no valid prefix before the canonical role '${canonicalRole2}'. Generated agent names must include a non-empty swarm prefix.`)}if(input.callID&&subagentRaw){let{instruction}=registerFullAutoSevereCorrelation({sessionID,callID:input.callID,generation:runState.runGeneration??0,subagent:subagentRaw});if(typeof args2.prompt==="string")args2.prompt=`${args2.prompt}
|
|
7063
7071
|
|
|
7064
7072
|
${instruction}`;else if(typeof args2.message==="string")args2.message=`${args2.message}
|
|
7065
7073
|
|
|
7066
7074
|
${instruction}`;else if(typeof args2.task==="string")args2.task=`${args2.task}
|
|
7067
7075
|
|
|
7068
|
-
${instruction}`}if(incrementFullAutoCounter(directory,sessionID,"coderDelegations"),!subagentRaw||!isKnownCanonicalRole(canonicalRole2))throw Error(`FULL_AUTO_DELEGATION_DENY: unknown subagent '${subagentRaw}' (canonical role '${canonicalRole2}' is not a registered plugin role). Choose a generated agent whose suffix matches one of the canonical roles.`);if(canonicalRole2==="coder"){let protectedPathScan=scanForProtectedPaths(args2,config3.full_auto);if(!protectedPathScan.complete)throw await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole2,phase:"outbound",category:"protected_path_scan_incomplete",matched:"scan-budget-exceeded"}),Error("FULL_AUTO_DELEGATION_DENY: coder delegation payload exceeds the protected-path scan budget");for(let p of protectedPathScan.hits)if(isProtectedPath(p,config3.full_auto))throw await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole2,phase:"outbound",category:"protected_path_in_prompt",matched:p}),Error(`FULL_AUTO_DELEGATION_DENY: coder delegation targets protected path '${p}'`)}},toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText(output.output),envelope=extractFullAutoSevereEnvelope(text),warnings=detectReturnWarnings(text),session=swarmState.agentSessions.get(sessionID),severeValidation=input.callID&&runState?validateFullAutoSevereEnvelope({envelope,sessionID,callID:input.callID,generation:runState.runGeneration??0,declaredScope:session?.declaredCoderScope??null,currentTaskID:session?.currentTaskId??null,session,projectDirectory:directory}):{accepted:!1,reason:"missing-call-id"},severe=severeValidation.accepted;if(warnings.length===0&&!envelope)return;if(await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,phase:"return",warnings,envelope_category:envelope?.category,envelope_validation:severeValidation.reason,severe}),runState.counters.consecutiveNoProgressTurns=severe?runState.counters.consecutiveNoProgressTurns+1:runState.counters.consecutiveNoProgressTurns,saveFullAutoRunState(directory,runState),severe){let updated=loadFullAutoRunState(directory,sessionID);if(updated&&updated.status==="running")updated.status="paused",updated.pauseReason=`severe subagent return envelope: ${envelope?.category??"unknown"}`,saveFullAutoRunState(directory,updated)}if(input.callID)clearFullAutoSevereCorrelation(sessionID,input.callID)}}}init_core_events();var PATTERNS=[{category:"instruction_override",regex:/\bignore (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules|directives)\b/i},{category:"instruction_override",regex:/\bdisregard (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules)\b/i},{category:"instruction_override",regex:/\bforget (?:all |any |everything|the )?(?:previous|above|prior) (?:instructions|prompts|rules)\b/i},{category:"system_role_override",regex:/\b(?:you are now|act as|pretend to be|from now on you are)\s+(?:a |an |the )?(?:system|developer|root|admin|superuser)\b/i},{category:"system_role_override",regex:/\b<\|?(?:system|developer|im_start|imstart)\|?>/i},{category:"credential_request",regex:/\b(?:please |kindly |)(?:paste|share|reveal|send|provide|leak|print|echo|cat) (?:your |the |my )?(?:api[_ -]?key|password|token|secret|credentials|\.env)\b/i},{category:"credential_request",regex:/\b(?:show|dump|export) (?:env(?:ironment)?|secrets|credentials|keys?)\b/i},{category:"exfiltration_request",regex:/\b(?:upload|exfiltrate|send) (?:contents of |files? from |the )?(?:home|repo|workspace|project|secrets?|env(?:ironment)?)\b/i},{category:"exfiltration_request",regex:/\bcurl\s+-d\s+@/i},{category:"guardrail_disable_request",regex:/\bdisable (?:full[- ]auto|guardrails?|safety|policy|oversight|critic)\b/i},{category:"guardrail_disable_request",regex:/\bturn (?:off|disable) (?:full[- ]auto|guardrails?|safety|policy)\b/i},{category:"curl_pipe_shell",regex:/\bcurl\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i},{category:"untrusted_run_command",regex:/\b(?:run|execute|paste) (?:this|the following) (?:command|script|bash|shell)\b/i}];function buildExcerpt(text,match){let idx=match.index??0,start=Math.max(0,idx-120),end=Math.min(text.length,idx+match[0].length+120),slice=text.slice(start,end).replace(/\s+/g," ").trim();return slice.length>280?`${slice.slice(0,280)}…`:slice}function probeFullAutoInput(text){let warnings=[];if(!text||typeof text!=="string")return{hasWarning:!1,warnings};let seen=new Set;for(let{category,regex}of PATTERNS){let m=text.match(regex);if(!m)continue;let key2=`${category}:${m[0].toLowerCase()}`;if(seen.has(key2))continue;seen.add(key2),warnings.push({category,matched:m[0],excerpt:buildExcerpt(text,m)})}return{hasWarning:warnings.length>0,warnings}}var RISKY_FOLLOWUP_TOOLS=new Set(["bash","shell","exec","web_search","webfetch","web_fetch","fetch","http","request"]),SECRET_TOOL_PATTERNS=[/\b(?:cat|head|tail|less|more)\s+[^\n]*\.env/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i];function shouldEscalateAfterWarning(toolName,commandOrUrl){let lower=toolName?.toLowerCase()??"";if(RISKY_FOLLOWUP_TOOLS.has(lower))return!0;if(typeof commandOrUrl==="string"){for(let re of SECRET_TOOL_PATTERNS)if(re.test(commandOrUrl))return!0}return!1}init_state3();init_logger();init_normalize_tool_name();var PROBED_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","doc_extract","doc_scan","gitingest","extract_code_blocks","retrieve_summary","retrieve_lane_output","search","read","view"]);async function writeWarningEvent(directory,sessionID,tool3,probe2){let event={type:"full_auto_input_warning",timestamp:new Date().toISOString(),session_id:sessionID,tool:tool3,warnings:probe2.warnings};try{appendCoreEventSync(directory,event)}catch(error93){error48(`[full-auto/input-probe] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`)}}function extractText2(out){if(typeof out==="string")return out;if(out&&typeof out==="object"){let candidate2=out;if(typeof candidate2.output==="string")return candidate2.output;if(typeof candidate2.text==="string")return candidate2.text;if(typeof candidate2.body==="string")return candidate2.body;try{return JSON.stringify(candidate2)}catch{return""}}return""}var MAX_TRACKED_SESSIONS9=256,WARNING_TTL_MS=300000,fullAutoInputWarningStash=new Map;function isExpired2(w,nowMs3=Date.now()){let at=Date.parse(w.at);if(!Number.isFinite(at))return!0;return nowMs3-at>WARNING_TTL_MS}function evictExpired2(){let now2=Date.now();for(let[sid,w]of fullAutoInputWarningStash)if(isExpired2(w,now2))fullAutoInputWarningStash.delete(sid);while(fullAutoInputWarningStash.size>MAX_TRACKED_SESSIONS9){let firstKey=fullAutoInputWarningStash.keys().next().value;if(firstKey===void 0)break;fullAutoInputWarningStash.delete(firstKey)}}function setPendingInputWarning(sessionID,warning){fullAutoInputWarningStash.delete(sessionID),fullAutoInputWarningStash.set(sessionID,warning),evictExpired2()}function consumePendingInputWarning(sessionID){let warning=fullAutoInputWarningStash.get(sessionID);if(warning)fullAutoInputWarningStash.delete(sessionID);if(warning&&isExpired2(warning))return;return warning}function peekPendingInputWarning(sessionID){let w=fullAutoInputWarningStash.get(sessionID);if(!w)return;if(isExpired2(w)){fullAutoInputWarningStash.delete(sessionID);return}return w}function createFullAutoInputProbeHook(options){let{directory}=options;return{toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!PROBED_TOOLS.has(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText2(output.output);if(!text)return;let probe2=probeFullAutoInput(text);if(!probe2.hasWarning)return;setPendingInputWarning(sessionID,{tool:tool3,at:new Date().toISOString(),categories:probe2.warnings.map((w)=>w.category)}),await writeWarningEvent(directory,sessionID,tool3,probe2)}}}init_constants();init_schema();init_oversight();init_policy();init_recovery2();init_severe_result();init_state3();init_executor();init_skip_state();init_scope_persistence();init_state2();init_file_authority();init_normalize_tool_name();var _internals221={assessSandboxEnforcement,readSandboxWrapOutcome,clearSandboxWrapOutcome};function createFullAutoPermissionHook(options){let{config:config3,directory}=options,fullAutoConfig=config3.full_auto;return{toolBefore:async(input,output)=>{let toolName=normalizeToolName(input.tool)??input.tool,sessionID=input.sessionID;if(!sessionID)return;let stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_STATE_UNREADABLE: tool '${toolName}' blocked because the Full-Auto durable state file is unreadable (${stateHealth.reason}). Restore .swarm/full-auto-state.json (or .bak) and re-run /swarm full-auto on.`)}let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status==="idle")return;if(runState.status==="paused"||runState.status==="terminated"){if(toolName==="swarm_command"&&output.args&&typeof output.args==="object"&&typeof output.args.command==="string"){let raw=output.args,command=String(raw.command),commandArgs=Array.isArray(raw.args)?raw.args.filter((item)=>typeof item==="string"):[];if(isAllowedPausedSwarmCommand(command,commandArgs,runState.status))return}if(isReadOnlyTool(toolName))return;let rawReason=runState.pauseReason??runState.terminateReason??"no reason recorded",statusPrefix=rawReason.includes("infrastructure failure")&&runState.status==="paused"?"FULL_AUTO_PAUSED:OVERSIGHT_INFRASTRUCTURE_FAILURE":`FULL_AUTO_${runState.status.toUpperCase()}`;throw Error(`${statusPrefix}: tool '${toolName}' blocked because Full-Auto run is ${runState.status} (${rawReason}). Re-enable with /swarm full-auto on after the underlying issue is resolved.`)}let session=swarmState.agentSessions.get(sessionID),activeAgent=swarmState.activeAgent.get(sessionID)??session?.agentName??ORCHESTRATOR_NAME,normalizedAgentName=stripKnownSwarmPrefix(activeAgent),taskId=session?.currentTaskId??null,binding=taskId?resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionID});if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null,argsObj=output.args??void 0,lowerTool=toolName?.toLowerCase()??"",phaseFromArgs;if(lowerTool==="phase_complete"){if(phaseFromArgs=parsePhaseArg(argsObj),phaseFromArgs===void 0)throw Error("FULL_AUTO_DENY [phase_complete_invalid_phase]: phase_complete called without a valid 'phase' argument. Provide a positive integer phase before calling phase_complete.")}let effectivePhase=phaseFromArgs??runState.currentPhase,safeMode=["assisted","supervised","strict"].includes(runState.mode)?runState.mode:"strict",effectiveFullAutoConfig=fullAutoConfig?{...fullAutoConfig,mode:safeMode}:{mode:safeMode},rawCommand=typeof argsObj?.command==="string"?argsObj.command.trim():"",sandboxOutcome=(toolName==="bash"||toolName==="shell")&&input.callID?_internals221.readSandboxWrapOutcome(sessionID,input.callID):null,classifierArgs=sandboxOutcome?{...argsObj,command:sandboxOutcome.originalCommand}:argsObj,classifierInput={sessionID,agentName:activeAgent,normalizedAgentName,generatedAgentNames:swarmState.generatedAgentNames,toolName,args:classifierArgs,directory,declaredScope,currentTaskID:taskId,currentPhase:effectivePhase,planSummary:void 0,changedFiles:session&&taskId?getModifiedFilesForTask(session,taskId):void 0,fullAutoConfig:effectiveFullAutoConfig,pluginConfig:config3},decision=classifyFullAutoToolAction(classifierInput);if(safeMode==="strict"&&(toolName==="bash"||toolName==="shell")&&rawCommand)try{let commandIdentity=`cmd=${hashArgs({command:rawCommand})}`,wrapOutcome=sandboxOutcome,sandboxConfig=config3.guardrails?.sandbox,identityAssessment=await _internals221.assessSandboxEnforcement({mode:sandboxConfig?.mode??"advisory",require_filesystem:sandboxConfig?.require_filesystem??!1,require_network:sandboxConfig?.require_network??!1,require_process:sandboxConfig?.require_process??!1,network_mode:sandboxConfig?.network_mode??"off",network_allowlist:sandboxConfig?.network_allowlist??[],writable_roots:sandboxConfig?.writable_roots??[]}),assessmentSupported=identityAssessment.supported!==!1,assessmentUnsupported=identityAssessment.unsupported??[],capabilityIdentity=`cap=${identityAssessment.capability.identity}`;if(!wrapOutcome)decision={action:"deny",code:"sandbox_unverified",recoverable:!0,reason:`strict mode shell command was not verified by the guardrails sandbox wrapper [${commandIdentity} ${capabilityIdentity}]`};else if(!wrapOutcome.wrapped||wrapOutcome.originalCommandHash!==hashArgs({command:wrapOutcome.originalCommand})||wrapOutcome.originalCommandHash===wrapOutcome.finalCommandHash||wrapOutcome.finalCommandHash!==hashArgs({command:rawCommand})||normalizeSandboxMechanism(wrapOutcome.executorMechanism)!==normalizeSandboxMechanism(wrapOutcome.capabilityMechanism)||wrapOutcome.capabilityIdentity!==identityAssessment.capability.identity||wrapOutcome.assessmentCacheKey!==identityAssessment.cacheKey)decision={action:"deny",code:"sandbox_unverified",recoverable:!0,reason:`strict mode shell command lost sandbox binding (${wrapOutcome.reason}) [${commandIdentity} ${capabilityIdentity}]`};else if(!assessmentSupported)decision={action:"deny",code:"sandbox_required",recoverable:!0,reason:`strict mode shell command requested unsupported sandbox policy (${assessmentUnsupported.join(", ")}) [${commandIdentity} ${capabilityIdentity}]`};else if(!identityAssessment.satisfied)decision={action:"deny",code:"sandbox_required",recoverable:!0,reason:`strict mode shell command requires independently verified sandbox containment; missing ${identityAssessment.missing.join(", ")} [${commandIdentity} ${capabilityIdentity}]`}}finally{_internals221.clearSandboxWrapOutcome(sessionID,input.callID)}let pendingWarning=peekPendingInputWarning(sessionID);if(pendingWarning){let commandOrUrl=typeof argsObj?.command==="string"&&argsObj.command||typeof argsObj?.url==="string"&&argsObj.url||void 0;if(shouldEscalateAfterWarning(toolName,commandOrUrl)){let evidenceEventID=recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"external_instructions",callID:input.callID,generation:runState.runGeneration});decision={action:"escalate_critic",reason:`risky follow-up after prompt-injection warning (${pendingWarning.categories.join(",")}); evidence event ${evidenceEventID}`,risk:"high",context:{tool:toolName,priorWarningTool:pendingWarning.tool,categories:pendingWarning.categories}},consumePendingInputWarning(sessionID)}}if(decision.action==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(decision.action==="deny"){let denial=buildStructuredDenial(decision,toolName);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:decision.code,reason:decision.reason});let updated2=loadFullAutoRunState(directory,sessionID);if(updated2){let pauseDecision=shouldPauseForDenials(updated2,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_DENY [${decision.code}]: ${decision.reason}. ${JSON.stringify(denial)}`)}if(decision.action==="pause")throw pauseFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_PAUSE [${decision.code}]: ${decision.reason}`);if(decision.action==="escalate_human")throw terminateFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_ESCALATE_HUMAN [${decision.code}]: ${decision.reason}`);let triggerSource=mapTriggerSource(decision,toolName),criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle",oversightAgentName=resolveOversightAgentNameFromActive(activeAgent);if(lowerTool==="phase_complete"&&effectivePhase!==void 0){let stateForPhase=loadFullAutoRunState(directory,sessionID);if(stateForPhase&&stateForPhase.currentPhase!==effectivePhase){stateForPhase.currentPhase=effectivePhase;try{saveFullAutoRunState(directory,stateForPhase)}catch(persistErr){let msg=persistErr instanceof Error?persistErr.message:String(persistErr);throw Error(`FULL_AUTO_BLOCKED: failed to persist phase ${effectivePhase} to durable run state — ${msg}`)}}}let outcome;try{outcome=await dispatchFullAutoOversight({directory,sessionID,trigger:decision.reason,triggerSource,phase:effectivePhase,taskID:taskId??void 0,planID:runState.planID,architectOutput:output.args?JSON.stringify(output.args):void 0,actionContext:{tool:toolName,...decision.context??{}},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:fullAutoConfig?.fail_closed!==!1,max_dispatch_retries:fullAutoConfig?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:fullAutoConfig?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:fullAutoConfig?.oversight?.total_timeout_ms??120000,cleanup_timeout_ms:fullAutoConfig?.oversight?.cleanup_timeout_ms??2000}})}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);throw pauseFullAutoRun(directory,sessionID,`oversight dispatcher exception: ${reason}`),Error(`FULL_AUTO_BLOCKED: oversight dispatch threw — ${reason}`)}if(outcome.decision==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(outcome.decision==="pause")throw Error(`FULL_AUTO_BLOCKED: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);if(outcome.decision==="escalate_human")throw Error(`FULL_AUTO_ESCALATE_HUMAN: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:`critic_${outcome.verdict}`.toLowerCase(),reason:outcome.reasoning||`critic verdict ${outcome.verdict}`});let updated=loadFullAutoRunState(directory,sessionID);if(updated){let pauseDecision=shouldPauseForDenials(updated,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_CRITIC_DENY: ${outcome.verdict} — ${outcome.reasoning}`)}}}function parsePhaseArg(args2){if(!args2)return;let raw=args2.phase,n;if(typeof raw==="number")n=raw;else if(typeof raw==="string"&&raw.trim()){let trimmed=raw.trim();if(!/^[1-9][0-9]*$/.test(trimmed))return;n=Number.parseInt(trimmed,10)}else return;if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)return;if(n>Number.MAX_SAFE_INTEGER)return;return n}function mapTriggerSource(decision,toolName){if(decision.action!=="escalate_critic")return"tool_action";let lower=toolName?.toLowerCase()??"";if(lower==="phase_complete")return"phase_boundary";if(lower==="update_task_status")return"task_completion";if(decision.risk==="high")return"risk";return"tool_action"}function resolveOversightAgentNameFromActive(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME){let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`}return"critic_oversight"}init_gate_denial_tracker();init_guardrails2();init_hive_promoter();init_host_boundary();init_command_resolution();init_stored_input_args();init_spawn_helper();import*as fs154 from"node:fs";import*as path271 from"node:path";var emittedSkipAdvisories=new Set;function detectPackageManager(projectDir){if(fs154.existsSync(path271.join(projectDir,"bun.lockb")))return"bun";if(fs154.existsSync(path271.join(projectDir,"pnpm-lock.yaml")))return"pnpm";if(fs154.existsSync(path271.join(projectDir,"yarn.lock")))return"yarn";if(fs154.existsSync(path271.join(projectDir,"package-lock.json")))return"npm";return"bun"}function detectTypecheckCommand(projectDir){let pkgPath=path271.join(projectDir,"package.json");if(fs154.existsSync(pkgPath))try{let pkg=JSON.parse(fs154.readFileSync(pkgPath,"utf8")),scripts=pkg.scripts;if(scripts?.typecheck)return{command:[detectPackageManager(projectDir),"run","typecheck"],language:"typescript"};if(scripts?.["type-check"])return{command:[detectPackageManager(projectDir),"run","type-check"],language:"typescript"};let deps={...pkg.dependencies,...pkg.devDependencies};if(!deps?.typescript&&!fs154.existsSync(path271.join(projectDir,"tsconfig.json")));if(deps?.typescript||fs154.existsSync(path271.join(projectDir,"tsconfig.json")))return{command:resolveLocalNodeTool("tsc",["--noEmit"],projectDir),language:"typescript"}}catch{return null}if(fs154.existsSync(path271.join(projectDir,"go.mod")))return{command:["go","vet","./..."],language:"go"};if(fs154.existsSync(path271.join(projectDir,"Cargo.toml")))return{command:["cargo","check"],language:"rust"};if(fs154.existsSync(path271.join(projectDir,"pyproject.toml"))||fs154.existsSync(path271.join(projectDir,"requirements.txt"))||fs154.existsSync(path271.join(projectDir,"setup.py")))return{command:null,language:"python"};try{if(fs154.readdirSync(projectDir).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))return{command:["dotnet","build","--no-restore"],language:"csharp"}}catch{}return null}async function runWithTimeout(command,cwd,timeoutMs){let result=await spawnAsync(command,cwd,timeoutMs);if(result===null)return null;return{exitCode:result.exitCode,stderr:result.stderr}}function createIncrementalVerifyHook(config3,projectDir,injectMessage){return{toolAfter:async(input,output)=>{if(!config3.enabled)return;if(input.tool!=="Task")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args,subagentType=typeof args2?.subagent_type==="string"?args2.subagent_type:"",agentName=subagentType.replace(/^[^_]+_/,"");if(!config3.triggerAgents.includes(agentName)&&!config3.triggerAgents.includes(subagentType))return;let commandToRun=null;if(config3.command!=null)if(Array.isArray(config3.command))commandToRun=config3.command;else commandToRun=config3.command.split(" ");else{let detected=detectTypecheckCommand(projectDir);if(detected===null)return;if(detected.command===null){let dedupKey=`${input.sessionID}:${detected.language}`;if(!emittedSkipAdvisories.has(dedupKey))emittedSkipAdvisories.add(dedupKey),injectMessage(input.sessionID,`POST-CODER CHECK SKIPPED: ${detected.language} project detected but no default checker available. Set incremental_verify.command in .swarm/config.json to enable.`);return}commandToRun=detected.command}if(commandToRun===null)return;let result=await runWithTimeout(commandToRun,projectDir,config3.timeoutMs);if(result===null)return;if(result.exitCode===0)injectMessage(input.sessionID,"POST-CODER CHECK PASSED: No type errors.");else{let errorSummary=result.stderr.slice(0,800);injectMessage(input.sessionID,`POST-CODER CHECK FAILED: Type errors detected after coder delegation. Address these before proceeding.
|
|
7076
|
+
${instruction}`}if(incrementFullAutoCounter(directory,sessionID,"coderDelegations"),!subagentRaw||!isKnownCanonicalRole(canonicalRole2))throw Error(`FULL_AUTO_DELEGATION_DENY: unknown subagent '${subagentRaw}' (canonical role '${canonicalRole2}' is not a registered plugin role). Choose a generated agent whose suffix matches one of the canonical roles.`);if(canonicalRole2==="coder"){let protectedPathScan=scanForProtectedPaths(args2,config3.full_auto);if(!protectedPathScan.complete)throw await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole2,phase:"outbound",category:"protected_path_scan_incomplete",matched:"scan-budget-exceeded"}),Error("FULL_AUTO_DELEGATION_DENY: coder delegation payload exceeds the protected-path scan budget");for(let p of protectedPathScan.hits)if(isProtectedPath(p,config3.full_auto))throw await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole2,phase:"outbound",category:"protected_path_in_prompt",matched:p}),Error(`FULL_AUTO_DELEGATION_DENY: coder delegation targets protected path '${p}'`)}},toolAfter:async(input,output)=>{let tool3=input.tool??"";if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText(output.output),envelope=extractFullAutoSevereEnvelope(text),warnings=detectReturnWarnings(text),session=swarmState.agentSessions.get(sessionID),severeValidation=input.callID&&runState?validateFullAutoSevereEnvelope({envelope,sessionID,callID:input.callID,generation:runState.runGeneration??0,declaredScope:session?.declaredCoderScope??null,currentTaskID:session?.currentTaskId??null,session,projectDirectory:directory}):{accepted:!1,reason:"missing-call-id"},severe=severeValidation.accepted;if(warnings.length===0&&!envelope)return;if(await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,phase:"return",warnings,envelope_category:envelope?.category,envelope_validation:severeValidation.reason,severe}),runState.counters.consecutiveNoProgressTurns=severe?runState.counters.consecutiveNoProgressTurns+1:runState.counters.consecutiveNoProgressTurns,saveFullAutoRunState(directory,runState),severe){let updated=loadFullAutoRunState(directory,sessionID);if(updated&&updated.status==="running")updated.status="paused",updated.pauseReason=`severe subagent return envelope: ${envelope?.category??"unknown"}`,saveFullAutoRunState(directory,updated)}if(input.callID)clearFullAutoSevereCorrelation(sessionID,input.callID)}}}init_core_events();var PATTERNS=[{category:"instruction_override",regex:/\bignore (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules|directives)\b/i},{category:"instruction_override",regex:/\bdisregard (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules)\b/i},{category:"instruction_override",regex:/\bforget (?:all |any |everything|the )?(?:previous|above|prior) (?:instructions|prompts|rules)\b/i},{category:"system_role_override",regex:/\b(?:you are now|act as|pretend to be|from now on you are)\s+(?:a |an |the )?(?:system|developer|root|admin|superuser)\b/i},{category:"system_role_override",regex:/\b<\|?(?:system|developer|im_start|imstart)\|?>/i},{category:"credential_request",regex:/\b(?:please |kindly |)(?:paste|share|reveal|send|provide|leak|print|echo|cat) (?:your |the |my )?(?:api[_ -]?key|password|token|secret|credentials|\.env)\b/i},{category:"credential_request",regex:/\b(?:show|dump|export) (?:env(?:ironment)?|secrets|credentials|keys?)\b/i},{category:"exfiltration_request",regex:/\b(?:upload|exfiltrate|send) (?:contents of |files? from |the )?(?:home|repo|workspace|project|secrets?|env(?:ironment)?)\b/i},{category:"exfiltration_request",regex:/\bcurl\s+-d\s+@/i},{category:"guardrail_disable_request",regex:/\bdisable (?:full[- ]auto|guardrails?|safety|policy|oversight|critic)\b/i},{category:"guardrail_disable_request",regex:/\bturn (?:off|disable) (?:full[- ]auto|guardrails?|safety|policy)\b/i},{category:"curl_pipe_shell",regex:/\bcurl\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i},{category:"untrusted_run_command",regex:/\b(?:run|execute|paste) (?:this|the following) (?:command|script|bash|shell)\b/i}];function buildExcerpt(text,match){let idx=match.index??0,start=Math.max(0,idx-120),end=Math.min(text.length,idx+match[0].length+120),slice=text.slice(start,end).replace(/\s+/g," ").trim();return slice.length>280?`${slice.slice(0,280)}…`:slice}function probeFullAutoInput(text){let warnings=[];if(!text||typeof text!=="string")return{hasWarning:!1,warnings};let seen=new Set;for(let{category,regex}of PATTERNS){let m=text.match(regex);if(!m)continue;let key2=`${category}:${m[0].toLowerCase()}`;if(seen.has(key2))continue;seen.add(key2),warnings.push({category,matched:m[0],excerpt:buildExcerpt(text,m)})}return{hasWarning:warnings.length>0,warnings}}var RISKY_FOLLOWUP_TOOLS=new Set(["bash","shell","exec","web_search","webfetch","web_fetch","fetch","http","request"]),SECRET_TOOL_PATTERNS=[/\b(?:cat|head|tail|less|more)\s+[^\n]*\.env/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i];function shouldEscalateAfterWarning(toolName,commandOrUrl){let lower=toolName?.toLowerCase()??"";if(RISKY_FOLLOWUP_TOOLS.has(lower))return!0;if(typeof commandOrUrl==="string"){for(let re of SECRET_TOOL_PATTERNS)if(re.test(commandOrUrl))return!0}return!1}init_state3();init_logger();init_normalize_tool_name();var PROBED_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","doc_extract","doc_scan","gitingest","extract_code_blocks","retrieve_summary","retrieve_lane_output","search","read","view"]);async function writeWarningEvent(directory,sessionID,tool3,probe2){let event={type:"full_auto_input_warning",timestamp:new Date().toISOString(),session_id:sessionID,tool:tool3,warnings:probe2.warnings};try{appendCoreEventSync(directory,event)}catch(error93){error48(`[full-auto/input-probe] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`)}}function extractText2(out){if(typeof out==="string")return out;if(out&&typeof out==="object"){let candidate2=out;if(typeof candidate2.output==="string")return candidate2.output;if(typeof candidate2.text==="string")return candidate2.text;if(typeof candidate2.body==="string")return candidate2.body;try{return JSON.stringify(candidate2)}catch{return""}}return""}var MAX_TRACKED_SESSIONS9=256,WARNING_TTL_MS=300000,fullAutoInputWarningStash=new Map;function isExpired2(w,nowMs3=Date.now()){let at=Date.parse(w.at);if(!Number.isFinite(at))return!0;return nowMs3-at>WARNING_TTL_MS}function evictExpired2(){let now2=Date.now();for(let[sid,w]of fullAutoInputWarningStash)if(isExpired2(w,now2))fullAutoInputWarningStash.delete(sid);while(fullAutoInputWarningStash.size>MAX_TRACKED_SESSIONS9){let firstKey=fullAutoInputWarningStash.keys().next().value;if(firstKey===void 0)break;fullAutoInputWarningStash.delete(firstKey)}}function setPendingInputWarning(sessionID,warning){fullAutoInputWarningStash.delete(sessionID),fullAutoInputWarningStash.set(sessionID,warning),evictExpired2()}function consumePendingInputWarning(sessionID){let warning=fullAutoInputWarningStash.get(sessionID);if(warning)fullAutoInputWarningStash.delete(sessionID);if(warning&&isExpired2(warning))return;return warning}function peekPendingInputWarning(sessionID){let w=fullAutoInputWarningStash.get(sessionID);if(!w)return;if(isExpired2(w)){fullAutoInputWarningStash.delete(sessionID);return}return w}function createFullAutoInputProbeHook(options){let{directory}=options;return{toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!PROBED_TOOLS.has(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText2(output.output);if(!text)return;let probe2=probeFullAutoInput(text);if(!probe2.hasWarning)return;setPendingInputWarning(sessionID,{tool:tool3,at:new Date().toISOString(),categories:probe2.warnings.map((w)=>w.category)}),await writeWarningEvent(directory,sessionID,tool3,probe2)}}}init_constants();init_schema();init_oversight();init_policy();init_recovery2();init_severe_result();init_state3();init_executor();init_skip_state();init_scope_persistence();init_state2();init_file_authority();var _internals221={assessSandboxEnforcement,readSandboxWrapOutcome,clearSandboxWrapOutcome};function createFullAutoPermissionHook(options){let{config:config3,directory}=options,fullAutoConfig=config3.full_auto;return{toolBefore:async(input,output)=>{let{tool:toolName,sessionID}=input;if(!sessionID)return;let stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_STATE_UNREADABLE: tool '${toolName}' blocked because the Full-Auto durable state file is unreadable (${stateHealth.reason}). Restore .swarm/full-auto-state.json (or .bak) and re-run /swarm full-auto on.`)}let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status==="idle")return;if(runState.status==="paused"||runState.status==="terminated"){if(toolName==="swarm_command"&&output.args&&typeof output.args==="object"&&typeof output.args.command==="string"){let raw=output.args,command=String(raw.command),commandArgs=Array.isArray(raw.args)?raw.args.filter((item)=>typeof item==="string"):[];if(isAllowedPausedSwarmCommand(command,commandArgs,runState.status))return}if(isReadOnlyTool(toolName))return;let rawReason=runState.pauseReason??runState.terminateReason??"no reason recorded",statusPrefix=rawReason.includes("infrastructure failure")&&runState.status==="paused"?"FULL_AUTO_PAUSED:OVERSIGHT_INFRASTRUCTURE_FAILURE":`FULL_AUTO_${runState.status.toUpperCase()}`;throw Error(`${statusPrefix}: tool '${toolName}' blocked because Full-Auto run is ${runState.status} (${rawReason}). Re-enable with /swarm full-auto on after the underlying issue is resolved.`)}let session=swarmState.agentSessions.get(sessionID),activeAgent=swarmState.activeAgent.get(sessionID)??session?.agentName??ORCHESTRATOR_NAME,normalizedAgentName=stripKnownSwarmPrefix(activeAgent),taskId=session?.currentTaskId??null,binding=taskId?resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionID});if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null,argsObj=output.args??void 0,lowerTool=toolName?.toLowerCase()??"",phaseFromArgs;if(lowerTool==="phase_complete"){if(phaseFromArgs=parsePhaseArg(argsObj),phaseFromArgs===void 0)throw Error("FULL_AUTO_DENY [phase_complete_invalid_phase]: phase_complete called without a valid 'phase' argument. Provide a positive integer phase before calling phase_complete.")}let effectivePhase=phaseFromArgs??runState.currentPhase,safeMode=["assisted","supervised","strict"].includes(runState.mode)?runState.mode:"strict",effectiveFullAutoConfig=fullAutoConfig?{...fullAutoConfig,mode:safeMode}:{mode:safeMode},rawCommand=typeof argsObj?.command==="string"?argsObj.command.trim():"",sandboxOutcome=(toolName==="bash"||toolName==="shell")&&input.callID?_internals221.readSandboxWrapOutcome(sessionID,input.callID):null,classifierArgs=sandboxOutcome?{...argsObj,command:sandboxOutcome.originalCommand}:argsObj,classifierInput={sessionID,agentName:activeAgent,normalizedAgentName,generatedAgentNames:swarmState.generatedAgentNames,toolName,args:classifierArgs,directory,declaredScope,currentTaskID:taskId,currentPhase:effectivePhase,planSummary:void 0,changedFiles:session&&taskId?getModifiedFilesForTask(session,taskId):void 0,fullAutoConfig:effectiveFullAutoConfig,pluginConfig:config3},decision=classifyFullAutoToolAction(classifierInput);if(safeMode==="strict"&&(toolName==="bash"||toolName==="shell")&&rawCommand)try{let commandIdentity=`cmd=${hashArgs({command:rawCommand})}`,wrapOutcome=sandboxOutcome,sandboxConfig=config3.guardrails?.sandbox,identityAssessment=await _internals221.assessSandboxEnforcement({mode:sandboxConfig?.mode??"advisory",require_filesystem:sandboxConfig?.require_filesystem??!1,require_network:sandboxConfig?.require_network??!1,require_process:sandboxConfig?.require_process??!1,network_mode:sandboxConfig?.network_mode??"off",network_allowlist:sandboxConfig?.network_allowlist??[],writable_roots:sandboxConfig?.writable_roots??[]}),assessmentSupported=identityAssessment.supported!==!1,assessmentUnsupported=identityAssessment.unsupported??[],capabilityIdentity=`cap=${identityAssessment.capability.identity}`;if(!wrapOutcome)decision={action:"deny",code:"sandbox_unverified",recoverable:!0,reason:`strict mode shell command was not verified by the guardrails sandbox wrapper [${commandIdentity} ${capabilityIdentity}]`};else if(!wrapOutcome.wrapped||wrapOutcome.originalCommandHash!==hashArgs({command:wrapOutcome.originalCommand})||wrapOutcome.originalCommandHash===wrapOutcome.finalCommandHash||wrapOutcome.finalCommandHash!==hashArgs({command:rawCommand})||normalizeSandboxMechanism(wrapOutcome.executorMechanism)!==normalizeSandboxMechanism(wrapOutcome.capabilityMechanism)||wrapOutcome.capabilityIdentity!==identityAssessment.capability.identity||wrapOutcome.assessmentCacheKey!==identityAssessment.cacheKey)decision={action:"deny",code:"sandbox_unverified",recoverable:!0,reason:`strict mode shell command lost sandbox binding (${wrapOutcome.reason}) [${commandIdentity} ${capabilityIdentity}]`};else if(!assessmentSupported)decision={action:"deny",code:"sandbox_required",recoverable:!0,reason:`strict mode shell command requested unsupported sandbox policy (${assessmentUnsupported.join(", ")}) [${commandIdentity} ${capabilityIdentity}]`};else if(!identityAssessment.satisfied)decision={action:"deny",code:"sandbox_required",recoverable:!0,reason:`strict mode shell command requires independently verified sandbox containment; missing ${identityAssessment.missing.join(", ")} [${commandIdentity} ${capabilityIdentity}]`}}finally{_internals221.clearSandboxWrapOutcome(sessionID,input.callID)}let pendingWarning=peekPendingInputWarning(sessionID);if(pendingWarning){let commandOrUrl=typeof argsObj?.command==="string"&&argsObj.command||typeof argsObj?.url==="string"&&argsObj.url||void 0;if(shouldEscalateAfterWarning(toolName,commandOrUrl)){let evidenceEventID=recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"external_instructions",callID:input.callID,generation:runState.runGeneration});decision={action:"escalate_critic",reason:`risky follow-up after prompt-injection warning (${pendingWarning.categories.join(",")}); evidence event ${evidenceEventID}`,risk:"high",context:{tool:toolName,priorWarningTool:pendingWarning.tool,categories:pendingWarning.categories}},consumePendingInputWarning(sessionID)}}if(decision.action==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(decision.action==="deny"){let denial=buildStructuredDenial(decision,toolName);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:decision.code,reason:decision.reason});let updated2=loadFullAutoRunState(directory,sessionID);if(updated2){let pauseDecision=shouldPauseForDenials(updated2,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_DENY [${decision.code}]: ${decision.reason}. ${JSON.stringify(denial)}`)}if(decision.action==="pause")throw pauseFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_PAUSE [${decision.code}]: ${decision.reason}`);if(decision.action==="escalate_human")throw terminateFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_ESCALATE_HUMAN [${decision.code}]: ${decision.reason}`);let triggerSource=mapTriggerSource(decision,toolName),criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle",oversightAgentName=resolveOversightAgentNameFromActive(activeAgent);if(lowerTool==="phase_complete"&&effectivePhase!==void 0){let stateForPhase=loadFullAutoRunState(directory,sessionID);if(stateForPhase&&stateForPhase.currentPhase!==effectivePhase){stateForPhase.currentPhase=effectivePhase;try{saveFullAutoRunState(directory,stateForPhase)}catch(persistErr){let msg=persistErr instanceof Error?persistErr.message:String(persistErr);throw Error(`FULL_AUTO_BLOCKED: failed to persist phase ${effectivePhase} to durable run state — ${msg}`)}}}let outcome;try{outcome=await dispatchFullAutoOversight({directory,sessionID,trigger:decision.reason,triggerSource,phase:effectivePhase,taskID:taskId??void 0,planID:runState.planID,architectOutput:output.args?JSON.stringify(output.args):void 0,actionContext:{tool:toolName,...decision.context??{}},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:fullAutoConfig?.fail_closed!==!1,max_dispatch_retries:fullAutoConfig?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:fullAutoConfig?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:fullAutoConfig?.oversight?.total_timeout_ms??120000,cleanup_timeout_ms:fullAutoConfig?.oversight?.cleanup_timeout_ms??2000}})}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);throw pauseFullAutoRun(directory,sessionID,`oversight dispatcher exception: ${reason}`),Error(`FULL_AUTO_BLOCKED: oversight dispatch threw — ${reason}`)}if(outcome.decision==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(outcome.decision==="pause")throw Error(`FULL_AUTO_BLOCKED: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);if(outcome.decision==="escalate_human")throw Error(`FULL_AUTO_ESCALATE_HUMAN: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:`critic_${outcome.verdict}`.toLowerCase(),reason:outcome.reasoning||`critic verdict ${outcome.verdict}`});let updated=loadFullAutoRunState(directory,sessionID);if(updated){let pauseDecision=shouldPauseForDenials(updated,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_CRITIC_DENY: ${outcome.verdict} — ${outcome.reasoning}`)}}}function parsePhaseArg(args2){if(!args2)return;let raw=args2.phase,n;if(typeof raw==="number")n=raw;else if(typeof raw==="string"&&raw.trim()){let trimmed=raw.trim();if(!/^[1-9][0-9]*$/.test(trimmed))return;n=Number.parseInt(trimmed,10)}else return;if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)return;if(n>Number.MAX_SAFE_INTEGER)return;return n}function mapTriggerSource(decision,toolName){if(decision.action!=="escalate_critic")return"tool_action";let lower=toolName?.toLowerCase()??"";if(lower==="phase_complete")return"phase_boundary";if(lower==="update_task_status")return"task_completion";if(decision.risk==="high")return"risk";return"tool_action"}function resolveOversightAgentNameFromActive(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME){let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`}return"critic_oversight"}init_gate_denial_tracker();init_guardrails2();init_hive_promoter();init_host_boundary();init_command_resolution();init_stored_input_args();init_normalize_tool_name();init_spawn_helper();import*as fs154 from"node:fs";import*as path271 from"node:path";var emittedSkipAdvisories=new Set;function detectPackageManager(projectDir){if(fs154.existsSync(path271.join(projectDir,"bun.lockb")))return"bun";if(fs154.existsSync(path271.join(projectDir,"pnpm-lock.yaml")))return"pnpm";if(fs154.existsSync(path271.join(projectDir,"yarn.lock")))return"yarn";if(fs154.existsSync(path271.join(projectDir,"package-lock.json")))return"npm";return"bun"}function detectTypecheckCommand(projectDir){let pkgPath=path271.join(projectDir,"package.json");if(fs154.existsSync(pkgPath))try{let pkg=JSON.parse(fs154.readFileSync(pkgPath,"utf8")),scripts=pkg.scripts;if(scripts?.typecheck)return{command:[detectPackageManager(projectDir),"run","typecheck"],language:"typescript"};if(scripts?.["type-check"])return{command:[detectPackageManager(projectDir),"run","type-check"],language:"typescript"};let deps={...pkg.dependencies,...pkg.devDependencies};if(!deps?.typescript&&!fs154.existsSync(path271.join(projectDir,"tsconfig.json")));if(deps?.typescript||fs154.existsSync(path271.join(projectDir,"tsconfig.json")))return{command:resolveLocalNodeTool("tsc",["--noEmit"],projectDir),language:"typescript"}}catch{return null}if(fs154.existsSync(path271.join(projectDir,"go.mod")))return{command:["go","vet","./..."],language:"go"};if(fs154.existsSync(path271.join(projectDir,"Cargo.toml")))return{command:["cargo","check"],language:"rust"};if(fs154.existsSync(path271.join(projectDir,"pyproject.toml"))||fs154.existsSync(path271.join(projectDir,"requirements.txt"))||fs154.existsSync(path271.join(projectDir,"setup.py")))return{command:null,language:"python"};try{if(fs154.readdirSync(projectDir).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))return{command:["dotnet","build","--no-restore"],language:"csharp"}}catch{}return null}async function runWithTimeout(command,cwd,timeoutMs){let result=await spawnAsync(command,cwd,timeoutMs);if(result===null)return null;return{exitCode:result.exitCode,stderr:result.stderr}}function createIncrementalVerifyHook(config3,projectDir,injectMessage){return{toolAfter:async(input,output)=>{if(!config3.enabled)return;if(!isTaskToolId(input.tool))return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args,subagentType=typeof args2?.subagent_type==="string"?args2.subagent_type:"",agentName=subagentType.replace(/^[^_]+_/,"");if(!config3.triggerAgents.includes(agentName)&&!config3.triggerAgents.includes(subagentType))return;let commandToRun=null;if(config3.command!=null)if(Array.isArray(config3.command))commandToRun=config3.command;else commandToRun=config3.command.split(" ");else{let detected=detectTypecheckCommand(projectDir);if(detected===null)return;if(detected.command===null){let dedupKey=`${input.sessionID}:${detected.language}`;if(!emittedSkipAdvisories.has(dedupKey))emittedSkipAdvisories.add(dedupKey),injectMessage(input.sessionID,`POST-CODER CHECK SKIPPED: ${detected.language} project detected but no default checker available. Set incremental_verify.command in .swarm/config.json to enable.`);return}commandToRun=detected.command}if(commandToRun===null)return;let result=await runWithTimeout(commandToRun,projectDir,config3.timeoutMs);if(result===null)return;if(result.exitCode===0)injectMessage(input.sessionID,"POST-CODER CHECK PASSED: No type errors.");else{let errorSummary=result.stderr.slice(0,800);injectMessage(input.sessionID,`POST-CODER CHECK FAILED: Type errors detected after coder delegation. Address these before proceeding.
|
|
7069
7077
|
${errorSummary}`)}}}}init_init_orphan_recovery();init_state2();import*as fs155 from"node:fs/promises";import*as path272 from"node:path";var ADVISORY_FILENAME="init-orphan-recovery.json";function createInitOrphanRecoveryAdvisoryHook(directory){let consumedBySession=new Set;async function readAdvisoryFile(){let advisoryPath=path272.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{let content=await fs155.readFile(advisoryPath,"utf-8");return JSON.parse(content)}catch{return null}}async function deleteAdvisoryFile(){let advisoryPath=path272.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{await fs155.unlink(advisoryPath)}catch{}}function formatError3(error93){return`ORPHAN_RECOVERY_ERROR: Could not reclaim branch "${error93.branch}": ${error93.error}`}async function messagesTransform(_input,output){let messages=output.messages;if(!messages||messages.length===0)return;let sessionId=messages[messages.length-1]?.info?.sessionID;if(!sessionId)return;let activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),ORCHESTRATOR_NAME2="Architect";if(!(activeAgent?activeAgent===ORCHESTRATOR_NAME2||activeAgent.endsWith("_Architect"):session?session.agentName===ORCHESTRATOR_NAME2||session.agentName.endsWith("_Architect"):!1))return;if(consumedBySession.has(sessionId))return;let advisory=await readAdvisoryFile();if(!advisory)return;consumedBySession.add(sessionId),await deleteAdvisoryFile();let reclaimedForGate=advisory.reclaimed;if(!((advisory.warnings?.length??0)>0||(advisory.errors?.length??0)>0||(reclaimedForGate?.removedBranches?.length??0)>0||(reclaimedForGate?.removedWorktrees?.length??0)>0))return;let targetSession=ensureAgentSession(sessionId),timestamp=advisory.initTimestamp?new Date(advisory.initTimestamp).toLocaleString():"unknown";pushAdvisory(targetSession,`[INIT ORPHAN RECOVERY] Plugin init detected the following at ${timestamp}:`);for(let warning of advisory.warnings??[])pushAdvisory(targetSession,` WARNING: ${warning}`);for(let err of advisory.errors??[])pushAdvisory(targetSession,` ERROR: ${formatError3(err)}`);let reclaimed=advisory.reclaimed;if((reclaimed?.removedBranches?.length??0)>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedBranches.length} orphaned branch(es): ${reclaimed.removedBranches.join(", ")}`);if(reclaimed?.removedWorktrees&&reclaimed.removedWorktrees.length>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedWorktrees.length} orphaned worktree directory(ies): ${reclaimed.removedWorktrees.join(", ")}`);if(reclaimed?.prunedWorktrees)pushAdvisory(targetSession," Stale worktree metadata pruned.")}return{messagesTransform}}init_ledger_sqlite();init_logger();init_delegation_gate();import*as fs156 from"node:fs";import*as path274 from"node:path";function computeNextMode(params){let{issueReference,traceState,workflowArtifacts}=params,noop={nextMode:null,directive:null,nextLastTransition:traceState.lastTransition,nextStatus:traceState.status};if(!issueReference||issueReference.flags.trace!==!0)return noop;if(traceState.status==="published")return noop;if(traceState.status==="publication_handoff"){if(workflowArtifacts.publicationObserved&&traceState.lastTransition!=="PUBLISHED")return{nextMode:null,directive:"Publication confirmed. The issue-trace workflow is complete.",nextLastTransition:"PUBLISHED",nextStatus:"published"};return noop}if(workflowArtifacts.specIssueNumber===null||workflowArtifacts.specIssueNumber!==issueReference.number||traceState.issueNumber!==issueReference.number)return noop;if(!workflowArtifacts.specExists)return noop;if(!workflowArtifacts.planExists){if(!workflowArtifacts.reproductionPermitted){if(traceState.lastTransition===null)return{nextMode:"ISSUE_INGEST",directive:"Reproduction evidence (or a typed --no-repro waiver) is required before this trace can transition to PLAN. Attempt a minimal reproduction and call record_issue_reproduction (performed: true, commands, output_summary), or restart with /swarm issue --no-repro.",nextLastTransition:"REPRO_GATE",nextStatus:"in_progress"};return noop}if(traceState.lastTransition===null||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN"||traceState.lastTransition==="REPRO_GATE"){if(traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return noop;return{nextMode:"PLAN",directive:null,nextLastTransition:"ISSUE_INGEST_TO_PLAN",nextStatus:"in_progress"}}return noop}if(!workflowArtifacts.criticApproved)return noop;if(workflowArtifacts.planExists&&!workflowArtifacts.allPhasesComplete){if(traceState.lastTransition==="PLAN_TO_EXECUTE")return noop;return{nextMode:"EXECUTE",directive:null,nextLastTransition:"PLAN_TO_EXECUTE",nextStatus:"in_progress"}}if(!workflowArtifacts.planExists)return noop;if(!workflowArtifacts.implementationReviewVerified&&traceState.lastTransition!=="REVIEW_GATE"&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:"All implementation phases are complete, but the independent implementation review is not yet recorded. Dispatch a FRESH-context reviewer and then a FRESH-context critic over the implementation diff (separate contexts from the implementer); when both approve, call record_implementation_review (issueNumber, reviewerVerdict APPROVE, criticVerdict APPROVE, the reviewed diff base/head, and notes). The trace will not hand off to commit-pr until this receipt exists.",nextLastTransition:"REVIEW_GATE",nextStatus:"in_progress"};if(workflowArtifacts.implementationReviewVerified&&!workflowArtifacts.recurrenceSweepVerified&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:'The implementation review is approved, but the recurrence sweep is not yet recorded. Characterize the defect class, search the repository with explicit predicates, disposition every hit (FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL), and install a guardrail that provably catches the original defect — or record the "no defect class" fast path with a one-line justification. Then call record_recurrence_sweep. The trace will not hand off to commit-pr until this receipt exists.',nextLastTransition:"RECURRENCE_GATE",nextStatus:"in_progress"};if(!workflowArtifacts.implementationReviewVerified||!workflowArtifacts.recurrenceSweepVerified)return noop;if(traceState.lastTransition==="EXECUTE_TO_COMMIT")return noop;return{nextMode:null,directive:"All implementation phases are complete. Compose commit-pr to publish the PR. Read .swarm/issue-reference.json for Closes #N. After the PR is created/updated, call record_issue_publication (with the issue number, PR number, URL, and HEAD sha) so this trace reaches its terminal published state — the trace is NOT complete until publication is confirmed.",nextLastTransition:"EXECUTE_TO_COMMIT",nextStatus:"publication_handoff"}}init_manager();import{existsSync as existsSync145,mkdirSync as mkdirSync77,readFileSync as readFileSync113,renameSync as renameSync45,unlinkSync as unlinkSync47,writeFileSync as writeFileSync51}from"node:fs";import*as path273 from"node:path";async function _defaultLoadPlanFromLedger(directory){return loadPlan(directory)}async function _defaultReproductionReceiptExists(directory,issueNumber){try{let filePath=path273.join(directory,".swarm","reproduction.json"),raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.performed===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultPublicationReceiptExists(directory,issueNumber){try{let filePath=path273.join(directory,".swarm","issue-publication.json"),raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.published===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultRecurrenceSweepReceiptExists(directory,issueNumber){try{let filePath=path273.join(directory,".swarm","recurrence-sweep.json"),raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber||typeof o.defectClass!=="string"||o.defectClass.trim().length===0)return!1;if(o.defectClass!=="no defect class"){let{predicates,dispositions,guardrail}=o,validPredicates=Array.isArray(predicates)&&predicates.length>0&&predicates.every((p)=>typeof p==="string"&&p.trim().length>0),validDispositions=Array.isArray(dispositions)&&dispositions.every((d)=>typeof d==="object"&&d!==null&&typeof d.ref==="string"&&["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"].includes(String(d.disposition))),validGuardrail=typeof guardrail==="object"&&guardrail!==null&&typeof guardrail.kind==="string"&&typeof guardrail.proof==="string";if(!validPredicates||!validDispositions||!validGuardrail)return!1}else if(typeof o.justification!=="string"||o.justification.trim().length===0)return!1;return!0}catch{return!1}}async function _defaultImplementationReviewReceiptExists(directory,issueNumber){try{let filePath=path273.join(directory,".swarm","implementation-review.json"),raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.issueNumber===issueNumber&&o.reviewerVerdict==="APPROVE"&&o.criticVerdict==="APPROVE"}catch{return!1}}var _internals222={readFileSync:readFileSync113,writeFileSync:writeFileSync51,existsSync:existsSync145,renameSync:renameSync45,mkdirSync:mkdirSync77,unlinkSync:unlinkSync47,loadPlanFromLedger:_defaultLoadPlanFromLedger,reproductionReceiptExists:_defaultReproductionReceiptExists,publicationReceiptExists:_defaultPublicationReceiptExists,recurrenceSweepReceiptExists:_defaultRecurrenceSweepReceiptExists,implementationReviewReceiptExists:_defaultImplementationReviewReceiptExists},TRACE_STATUSES=["in_progress","publication_handoff","published"];function isTraceStatus(value){return typeof value==="string"&&TRACE_STATUSES.includes(value)}function isPhaseComplete(status){return status==="complete"||status==="completed"}function isValidIssueReference(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;if(typeof o.url!=="string"||!o.url.startsWith("https://github.com/"))return!1;return typeof o.owner==="string"&&typeof o.repo==="string"&&typeof o.number==="number"&&typeof o.timestamp==="string"&&typeof o.flags==="object"&&o.flags!==null}function isValidTraceStateShape(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.issueNumber==="number"&&(o.lastTransition===null||typeof o.lastTransition==="string")}function normalizeTraceState(obj){let status;if(isTraceStatus(obj.status))status=obj.status;else if(obj.status===void 0&&typeof obj.completed==="boolean")status=obj.completed?"publication_handoff":"in_progress";else status="in_progress";return{issueNumber:obj.issueNumber,lastTransition:obj.lastTransition===null||typeof obj.lastTransition==="string"?obj.lastTransition:null,status}}function readIssueReference(directory){try{let filePath=path273.join(directory,".swarm","issue-reference.json"),raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidIssueReference(parsed))return null;return parsed}catch{return null}}function readTraceState(directory){let defaultState={issueNumber:0,lastTransition:null,status:"in_progress"};try{let filePath=path273.join(directory,".swarm","issue-trace-state.json"),raw=_internals222.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidTraceStateShape(parsed))return defaultState;return normalizeTraceState(parsed)}catch{return defaultState}}function writeTraceState(directory,state){let swarmDir=path273.join(directory,".swarm");_internals222.mkdirSync(swarmDir,{recursive:!0});let finalPath=path273.join(swarmDir,"issue-trace-state.json"),tmpPath=path273.join(swarmDir,`issue-trace-state.tmp.${process.pid}.${Date.now()}.json`);_internals222.writeFileSync(tmpPath,JSON.stringify(state,null,2),"utf-8");try{_internals222.renameSync(tmpPath,finalPath)}catch{try{_internals222.unlinkSync(finalPath)}catch{}try{_internals222.renameSync(tmpPath,finalPath)}catch(retryErr){try{_internals222.unlinkSync(tmpPath)}catch{}throw retryErr}}}function readSpecIssueNumber(directory){try{let filePath=path273.join(directory,".swarm","spec.md"),raw=_internals222.readFileSync(filePath,"utf-8"),sectionStart=raw.indexOf("## Source Issue");if(sectionStart===-1)return null;let nextHeading=raw.indexOf(`
|
|
7070
7078
|
## `,sectionStart+14),sectionEnd=nextHeading===-1?raw.length:nextHeading,section=raw.slice(sectionStart,sectionEnd),numberMatch=section.match(/-\s+Number:\s*(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10);let urlMatch=section.match(/-\s+URL:.*\/issues\/(\d+)/);if(urlMatch)return parseInt(urlMatch[1],10);return null}catch{return null}}async function readPlanPhaseStatus(directory){let plan=await _internals222.loadPlanFromLedger(directory);if(!plan||plan.phases.length===0)return{planExists:!1,allComplete:!1};return{planExists:!0,allComplete:plan.phases.every((phase)=>isPhaseComplete(phase.status))}}function specExists(directory){return _internals222.existsSync(path273.join(directory,".swarm","spec.md"))}async function reproductionReceiptExists(directory,issueNumber){return _internals222.reproductionReceiptExists(directory,issueNumber)}async function publicationReceiptExists(directory,issueNumber){return _internals222.publicationReceiptExists(directory,issueNumber)}async function recurrenceSweepReceiptExists(directory,issueNumber){return _internals222.recurrenceSweepReceiptExists(directory,issueNumber)}async function implementationReviewReceiptExists(directory,issueNumber){return _internals222.implementationReviewReceiptExists(directory,issueNumber)}var _internals223={readIssueReference,readTraceState,writeTraceState,readSpecIssueNumber,readPlanPhaseStatus,specExists,reproductionReceiptExists,publicationReceiptExists,recurrenceSweepReceiptExists,implementationReviewReceiptExists,isPlanCriticApproved,getPlanLedgerState:getPlanLedgerStateReadOnly,logError:error48,boundedApprovalCheck:(directory,timeoutMs)=>boundedApprovalCheck(directory,timeoutMs)},cachedApproval=null,cachedPhaseStatus=null;async function boundedApprovalCheck(directory,timeoutMs){try{let ledgerPath3=path274.join(directory,".swarm","plan-ledger.jsonl"),currentSize=-1,currentMtime=-1;try{let stat24=fs156.statSync(ledgerPath3);currentSize=stat24.size,currentMtime=stat24.mtimeMs}catch{}let state=null,authorityReadFailed=!1;try{state=_internals223.getPlanLedgerState(directory)}catch{authorityReadFailed=!0}let revision=authorityReadFailed?null:state?.authorityMode==="sqlite"?`sqlite:${state.lastSeq}:${state.lastEventHash??""}:${state.updatedAt}`:`file:${currentSize}:${currentMtime}`;if(cachedApproval&&cachedApproval.dir===directory&&cachedApproval.revision===revision)return cachedApproval.result;let timer;try{let timeout=new Promise((resolve108)=>{timer=setTimeout(()=>resolve108(!1),timeoutMs)}),result=await Promise.race([_internals223.isPlanCriticApproved(directory),timeout]);if(revision!==null)cachedApproval={dir:directory,revision,result};return result}finally{if(timer!==void 0)clearTimeout(timer)}}catch{return!1}}async function cachedReadPlanPhaseStatus(directory){let planJsonPath=path274.join(directory,".swarm","plan.json"),currentSize=-1,currentMtime=-1;try{let stat24=fs156.statSync(planJsonPath);currentSize=stat24.size,currentMtime=stat24.mtimeMs}catch{}if(cachedPhaseStatus&&cachedPhaseStatus.dir===directory&&cachedPhaseStatus.planJsonSize===currentSize&&cachedPhaseStatus.planJsonMtime===currentMtime)return cachedPhaseStatus.result;let result=await _internals223.readPlanPhaseStatus(directory);return cachedPhaseStatus={dir:directory,planJsonSize:currentSize,planJsonMtime:currentMtime,result},result}function createIssueTraceHook(_config2,directory,approvalTimeoutMs=5000){return{messagesTransform:async(_input,output)=>{try{let issueRef=_internals223.readIssueReference(directory);if(!issueRef||issueRef.flags.trace!==!0)return;let traceState=_internals223.readTraceState(directory),_specExists=_internals223.specExists(directory),_specIssueNumber=_internals223.readSpecIssueNumber(directory),phaseStatus=await cachedReadPlanPhaseStatus(directory),_criticApproved=await boundedApprovalCheck(directory,approvalTimeoutMs),_reproReceipt=await _internals223.reproductionReceiptExists(directory,issueRef.number),_reproductionPermitted=issueRef.flags.noRepro===!0||issueRef.noReproWaiver?.waived===!0||_reproReceipt,_publicationObserved=await _internals223.publicationReceiptExists(directory,issueRef.number),_implementationReviewVerified=await _internals223.implementationReviewReceiptExists(directory,issueRef.number),_recurrenceSweepVerified=await _internals223.recurrenceSweepReceiptExists(directory,issueRef.number),result=computeNextMode({issueReference:issueRef,traceState,workflowArtifacts:{specExists:_specExists,specIssueNumber:_specIssueNumber,planExists:phaseStatus.planExists,criticApproved:_criticApproved,allPhasesComplete:phaseStatus.allComplete,reproductionPermitted:_reproductionPermitted,publicationObserved:_publicationObserved,implementationReviewVerified:_implementationReviewVerified,recurrenceSweepVerified:_recurrenceSweepVerified}});if(result.nextMode===null&&result.directive===null)return;let finalDirective=result.directive?result.directive.replace("#N",`#${issueRef.number}`):null,out=output;if(!Array.isArray(out.messages))return;let modeDelivered=result.nextMode===null||appendGuidanceCarrier(out.messages,"issue-trace",`[MODE: ${result.nextMode}]`)!==null,directiveDelivered=finalDirective===null||appendGuidanceCarrier(out.messages,"issue-trace",finalDirective)!==null;if(!modeDelivered||!directiveDelivered)return;_internals223.writeTraceState(directory,{issueNumber:traceState.issueNumber,lastTransition:result.nextLastTransition,status:result.nextStatus})}catch(err){_internals223.logError("[issue-trace] hook cycle failed:",err)}}}}init_schema();init_core_events();init_state2();init_logger();init_knowledge_application();init_knowledge_receipt_ledger();init_knowledge_store();import{existsSync as existsSync146}from"node:fs";var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]),DEFAULT_MAX_GATE_DENIALS=5,DEFAULT_GATE_STALENESS_MS=600000;function selectCurrentArchitectDirectiveMemberships(memberships){let activeArchitect=memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.phase_closed_at),latest,latestAt=Number.NEGATIVE_INFINITY;for(let membership of activeArchitect){let committedAt=Date.parse(membership.committed_at),comparableAt=Number.isFinite(committedAt)?committedAt:Number.NEGATIVE_INFINITY;if(!latest||comparableAt>=latestAt)latest=membership,latestAt=comparableAt}if(!latest)return[];return activeArchitect.filter((membership)=>membership.phase===latest.phase&&membership.task_id===latest.task_id)}function selectStaleUnmarkedMemberships(memberships,now2,stalenessMs){return memberships.filter((membership)=>{if(membership.application_marker||hasEffectiveGateRelease(membership))return!1;let committedAt=Date.parse(membership.committed_at);return Number.isFinite(committedAt)&&now2-committedAt>stalenessMs})}function hasEffectiveGateRelease(membership){return membership.gate_release?.membership_event_id===membership.membership_event_id}function groupMembershipsByTrace(memberships){let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}return byTrace}async function loadDirectiveContents(directory,entryIds){let contents=new Map;if(entryIds.length===0)return contents;let want=new Set(entryIds),sources=[resolveSwarmKnowledgePath(directory)];try{let hivePath=resolveHiveKnowledgePath2();if(existsSync146(hivePath))sources.push(hivePath)}catch{}for(let filePath of sources)try{let entries2=await readKnowledge(filePath);for(let entry of entries2)if(want.has(entry.id)&&!contents.has(entry.id)&&typeof entry.lesson==="string")contents.set(entry.id,entry.lesson)}catch{}return contents}function buildGateDenialMessage(toolName,memberships,contents){let pairs=memberships.map((m)=>`${m.trace_id}:${m.entry_id}`),examples=memberships.map((m)=>` KNOWLEDGE_N_A:${m.trace_id}:${m.entry_id} reason=<reason>`),contentLines=memberships.map((m)=>{let lesson=contents.get(m.entry_id);return` [${m.trace_id}:${m.entry_id}] ${lesson??"content not found in knowledge store — see the most recent <swarm_knowledge_directives> block or run knowledge_recall"}`});return[`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — unacknowledged critical knowledge directive(s): ${pairs.join(", ")}.`,"","Acknowledge each directive using its exact, colon-separated tokens (<trace_id>:<entry_id>) with one of these verb markers:"," KNOWLEDGE_APPLIED:<trace_id>:<entry_id>"," KNOWLEDGE_IGNORED:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_CONTRADICTED:<trace_id>:<entry_id> reason=<observable conflict>"," KNOWLEDGE_N_A:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_VIOLATED:<trace_id>:<entry_id> reason=<short reason>","KNOWLEDGE_N_A (does not apply; neutral) is a valid, penalty-free acknowledgment when the directive does not pertain to the current step.","","Copy-paste to acknowledge each directive now (replace <reason> with a short reason):",...examples,"","Directive content being acknowledged:",...contentLines].join(`
|
|
7071
7079
|
`)}async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let receiptState=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!receiptState.ok){if(config3.mode==="enforce")throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: receipt authority unavailable (${receiptState.code}); refusing to infer acknowledgment from diagnostics`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,reason:receiptState.code});return}let currentMemberships=selectCurrentArchitectDirectiveMemberships(receiptState.memberships),criticalMemberships=currentMemberships.filter((membership)=>membership.critical);if(criticalMemberships.length===0){clearGateDenialCount(sessionID);return}let acknowledgedEntryIds=new Set(currentMemberships.filter((membership)=>membership.application_marker?.source==="architect_marker").map((membership)=>membership.entry_id)),unackedMemberships=criticalMemberships.filter((membership)=>!membership.application_marker&&!hasEffectiveGateRelease(membership)&&!acknowledgedEntryIds.has(membership.entry_id));if(unackedMemberships.length===0){clearGateDenialCount(sessionID);return}if(config3.mode==="enforce"&&config3.critical_requires_ack){let maxDenials=config3.max_gate_denials??DEFAULT_MAX_GATE_DENIALS,stalenessMs=config3.gate_staleness_ms??DEFAULT_GATE_STALENESS_MS,now2=Date.now(),staleMemberships=selectStaleUnmarkedMemberships(unackedMemberships,now2,stalenessMs);if(staleMemberships.length>0){for(let[traceId,memberships]of groupMembershipsByTrace(staleMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_staleness_release",reason:"configured staleness escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record staleness release")}let stalePairs=new Set(staleMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`));unackedMemberships=unackedMemberships.filter((membership)=>!stalePairs.has(`${membership.trace_id}/${membership.entry_id}`));let staleIds=[...new Set(staleMemberships.map((membership)=>membership.entry_id))];if(await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_staleness_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:staleIds,cleared_pairs:[...stalePairs],age_ms:Math.max(...staleMemberships.map((membership)=>now2-Date.parse(membership.committed_at))),staleness_threshold_ms:stalenessMs}).catch((err)=>{warn(`[knowledge-application-gate] staleness-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)}),unackedMemberships.length===0){clearCriticalShownIds(sessionID);return}}let unacked2=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],directiveKey=buildGateDenialDirectiveKey(unacked2),denials=incrementGateDenialCount(sessionID,directiveKey);if(denials>maxDenials){for(let[traceId,memberships]of groupMembershipsByTrace(unackedMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_denial_limit_release",reason:"configured denial-count escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record denial-limit release")}clearCriticalShownIds(sessionID),clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_denial_limit_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:unacked2,denial_count:denials,max_gate_denials:maxDenials}).catch((err)=>{warn(`[knowledge-application-gate] denial-limit-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)});return}let contents=await loadDirectiveContents(directory,unacked2);throw Error(buildGateDenialMessage(toolName,unackedMemberships,contents))}let unacked=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],unackedPairs=unackedMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,unacknowledged_critical_ids:unacked,unacknowledged_critical_pairs:unackedPairs}).catch(()=>{})}async function writeWarnEvent2(directory,record3){appendCoreEventSync(directory,record3)}async function knowledgeApplicationTransformScan(directory,output,sessionID){if(!output?.messages)return;if(!sessionID)return;let target;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(isGuidanceCarrier(m))continue;let agent=m.info?.agent;if(typeof agent==="string"&&stripKnownSwarmPrefix(agent)==="architect"){target=m;break}}if(!target)return;let text=(target.parts??[]).map((p)=>typeof p.text==="string"?p.text:"").join(`
|
|
@@ -7079,7 +7087,7 @@ Do not stop or summarize. Inspect the durable gate, dispatch or collect the next
|
|
|
7079
7087
|
|
|
7080
7088
|
${output.text}`;return}let banner=workflowBanner(state.mode,{suspended,suspendedReason,userInterrupted,maxConsecutive,recovery});bannerStamps.set(input.sessionID,now3),evictBannerDedupeMapsIfOverBound(),output.text=`${banner}
|
|
7081
7089
|
|
|
7082
|
-
${output.text}`},_inspectWakeBudget:(sessionID)=>wakeBudgets.get(sessionID),_inspectBoundaryActivity:(sessionID)=>{let state=boundaryActivityBySession.get(sessionID);return state?{lastParentActivityAt:state.lastParentActivityAt,lastHostStatus:state.lastHostStatus,activeToolPartCount:state.activeToolParts.size,quietDeadlineAt:state.quietDeadlineAt,watchdogDeadlineAt:state.watchdogDeadlineAt,hasTimer:state.timer!==void 0}:void 0}}}init_pending_delegations();init_logger();init_pr_workflow_gate();var MAX_SESSION_GET_ERROR_LENGTH=200;function describeSessionGetError(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:JSON.stringify(error93)}else raw=String(error93);return raw.length>MAX_SESSION_GET_ERROR_LENGTH?`${raw.slice(0,MAX_SESSION_GET_ERROR_LENGTH)}...`:raw}var MAX_PARENT_DEPTH=16,MAX_TRACKED_SESSION_PARENTS=512;function rememberBounded2(parents,childSessionID,parentSessionID){parents.delete(childSessionID),parents.set(childSessionID,parentSessionID);while(parents.size>MAX_TRACKED_SESSION_PARENTS){let oldest=parents.keys().next().value;if(typeof oldest!=="string")break;parents.delete(oldest)}}function createPrWorkflowSessionResolver(options){let session=options.client?.session,parents=new Map;return{observeEvent:(input)=>{let event=input.event;if(event?.type!=="session.created"&&event?.type!=="session.updated")return;let child=event.properties?.info?.id,parent=event.properties?.info?.parentID;if(typeof child==="string"&&child.trim()&&typeof parent==="string"&&parent.trim())rememberBounded2(parents,child.trim(),parent.trim())},resolve:async(sessionID)=>{let original=sessionID.trim();if(!original)return sessionID;let current=original,visited=new Set;for(let depth=0;depth<MAX_PARENT_DEPTH;depth+=1){if(visited.has(current))break;if(visited.add(current),await readPrWorkflowGateState(options.directory,current))return current;let parent=parents.get(current);if(!parent)parent=findByCorrelationId(options.directory,current)?.parentSessionId;if(!parent&&session?.get){let result=await session.get({path:{id:current},query:{directory:options.directory}});if(result?.error==null){let candidate2=result?.data?.parentID;if(typeof candidate2==="string"&&candidate2.trim())parent=candidate2.trim()}else warn(`pr-workflow-session-resolver: session.get(${current}) failed while walking ancestor depth`,describeSessionGetError(result.error))}if(!parent)return original;rememberBounded2(parents,current,parent),current=parent}return original}}}init_review_receipt_collector();init_schema();init_path_identity();init_scope_binding();init_state2();init_git_executable();init_worktree_isolation();init_normalize_tool_name();init_review_receipt();init_review_receipt_scope();init_reviewer_scope_file_fingerprint();init_skill_propagation_gate();init_task_result_classifier();import*as child_process12 from"node:child_process";var _internals226={spawn:child_process12.spawn,resolveGitExecutable},NOCHANGE_STATUS_TIMEOUT_MS=1e4,NOCHANGE_STATUS_BYTES=262144,MANIFEST_PROMPT_BYTES=8192;function lifecycleTarget(args2){let delegation=parseDelegationArgs(args2);return delegation?stripKnownSwarmPrefix(delegation.targetAgent).toLowerCase():""}function isTaskTool6(tool3){
|
|
7090
|
+
${output.text}`},_inspectWakeBudget:(sessionID)=>wakeBudgets.get(sessionID),_inspectBoundaryActivity:(sessionID)=>{let state=boundaryActivityBySession.get(sessionID);return state?{lastParentActivityAt:state.lastParentActivityAt,lastHostStatus:state.lastHostStatus,activeToolPartCount:state.activeToolParts.size,quietDeadlineAt:state.quietDeadlineAt,watchdogDeadlineAt:state.watchdogDeadlineAt,hasTimer:state.timer!==void 0}:void 0}}}init_pending_delegations();init_logger();init_pr_workflow_gate();var MAX_SESSION_GET_ERROR_LENGTH=200;function describeSessionGetError(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:JSON.stringify(error93)}else raw=String(error93);return raw.length>MAX_SESSION_GET_ERROR_LENGTH?`${raw.slice(0,MAX_SESSION_GET_ERROR_LENGTH)}...`:raw}var MAX_PARENT_DEPTH=16,MAX_TRACKED_SESSION_PARENTS=512;function rememberBounded2(parents,childSessionID,parentSessionID){parents.delete(childSessionID),parents.set(childSessionID,parentSessionID);while(parents.size>MAX_TRACKED_SESSION_PARENTS){let oldest=parents.keys().next().value;if(typeof oldest!=="string")break;parents.delete(oldest)}}function createPrWorkflowSessionResolver(options){let session=options.client?.session,parents=new Map;return{observeEvent:(input)=>{let event=input.event;if(event?.type!=="session.created"&&event?.type!=="session.updated")return;let child=event.properties?.info?.id,parent=event.properties?.info?.parentID;if(typeof child==="string"&&child.trim()&&typeof parent==="string"&&parent.trim())rememberBounded2(parents,child.trim(),parent.trim())},resolve:async(sessionID)=>{let original=sessionID.trim();if(!original)return sessionID;let current=original,visited=new Set;for(let depth=0;depth<MAX_PARENT_DEPTH;depth+=1){if(visited.has(current))break;if(visited.add(current),await readPrWorkflowGateState(options.directory,current))return current;let parent=parents.get(current);if(!parent)parent=findByCorrelationId(options.directory,current)?.parentSessionId;if(!parent&&session?.get){let result=await session.get({path:{id:current},query:{directory:options.directory}});if(result?.error==null){let candidate2=result?.data?.parentID;if(typeof candidate2==="string"&&candidate2.trim())parent=candidate2.trim()}else warn(`pr-workflow-session-resolver: session.get(${current}) failed while walking ancestor depth`,describeSessionGetError(result.error))}if(!parent)return original;rememberBounded2(parents,current,parent),current=parent}return original}}}init_review_receipt_collector();init_schema();init_path_identity();init_scope_binding();init_state2();init_git_executable();init_worktree_isolation();init_normalize_tool_name();init_review_receipt();init_review_receipt_scope();init_reviewer_scope_file_fingerprint();init_skill_propagation_gate();init_task_result_classifier();import*as child_process12 from"node:child_process";var _internals226={spawn:child_process12.spawn,resolveGitExecutable},NOCHANGE_STATUS_TIMEOUT_MS=1e4,NOCHANGE_STATUS_BYTES=262144,MANIFEST_PROMPT_BYTES=8192;function lifecycleTarget(args2){let delegation=parseDelegationArgs(args2);return delegation?stripKnownSwarmPrefix(delegation.targetAgent).toLowerCase():""}function isTaskTool6(tool3){return typeof tool3==="string"&&isTaskToolId(tool3)}function generationFingerprintsAreCurrent(generation,options={}){let{modifiedFiles,modifiedFileFingerprints:fingerprints}=generation;if(modifiedFiles.length===0||modifiedFiles.length!==fingerprints.length||new Set(modifiedFiles).size!==modifiedFiles.length||new Set(fingerprints.map((entry)=>entry.file)).size!==fingerprints.length)return{current:!1,reason:"genuine_drift"};for(let file3 of modifiedFiles){let stored=fingerprints.filter((entry)=>entry.file===file3);if(stored.length!==1)return{current:!1,reason:"genuine_drift"};let current=captureReviewerScopeFileFingerprint(generation.captureDirectory,file3,{deadlineAt:options.deadlineAt});if(current.kind==="capture_failed")return{current:!1,reason:"capture_failed",failure:{file:current.file,code:current.code,retryable:current.retryable}};let currentFingerprint=reviewerScopeCaptureToFingerprint(current);if(!currentFingerprint||!reviewerScopeFileFingerprintsEqual(stored[0],currentFingerprint))return{current:!1,reason:"genuine_drift"}}return{current:!0}}function scopeMatchesGenerationFingerprints(scope,generation){let lines=scope.content.split(`
|
|
7083
7091
|
`);if(lines[0]!==REVIEWER_TASK_SCOPE_HEADER)return!1;let records=new Map;for(let line of lines.slice(1)){if(!line)continue;try{let parsed=JSON.parse(line);if(typeof parsed.path==="string")records.set(parsed.path,parsed)}catch{return!1}}if(records.size!==generation.modifiedFileFingerprints.length||scope.files.length!==generation.modifiedFiles.length)return!1;return generation.modifiedFileFingerprints.every((fingerprint2)=>{let record3=records.get(fingerprint2.file);if(!record3)return!1;return fingerprint2.kind==="deleted"?record3.state==="deleted":record3.state==="file"&&record3.bytes===fingerprint2.size&&record3.sha256===fingerprint2.hash})}function resolveReviewerCaptureDirectory(input){let sessionRoot=resolveSessionWorkspaceDirectory(input.binding.childSessionId??"","")||input.ambient,directory=input.binding.source==="worktree_derived"?standardWorktreeByCallID.get(input.callID)?.handle.worktreePath??sessionRoot:sessionRoot;if(!directory.trim())return{ok:!1,detail:"workspace root unavailable"};let identity=canonicalWorkspaceIdentity(directory);if(!identity)return{ok:!1,detail:`workspace root ${directory} not resolvable`};if(identity!==input.binding.workspaceIdentity)return{ok:!1,detail:`resolved workspace ${identity} does not match activated binding identity ${input.binding.workspaceIdentity}`};return{ok:!0,directory,identity}}function typedReviewerScopeError(code,detail){return Error(`${code}: ${detail}`)}function freshnessDenial(outcome,generation,attempt){if(outcome.current===!1&&outcome.reason==="capture_failed"){let{failure}=outcome;return typedReviewerScopeError(failure.retryable?"REVIEWER_CAPTURE_RETRY_EXHAUSTED":"REVIEWER_CAPTURE_FAILED",`task ${generation.taskId} generation ${generation.generation}: file ${failure.file} capture failed (${failure.code}, retryable=${failure.retryable}, attempts=${attempt}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${failure.retryable?"re-dispatch the reviewer to retry capture, or route explicit manual review":`resolve the ${failure.code} condition for the file, then re-dispatch the reviewer or route explicit manual review`}`)}return typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${generation.taskId} generation ${generation.generation}: coder post-write fingerprints changed before reviewer dispatch`)}function sleepBounded(ms){return new Promise((resolve108)=>{setTimeout(resolve108,ms)})}async function withCaptureRetry(run,isRetryable,options={}){let backoff=_internals226.backoffMs??100,deadlineAt=Date.now()+(options.deadlineMs??_internals226.retryDeadlineMs??REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS),last,attemptsRun=0;for(let attempt=1;attempt<=REVIEWER_SCOPE_CAPTURE_ATTEMPTS;attempt+=1){if(attempt>1&&attempt<REVIEWER_SCOPE_CAPTURE_ATTEMPTS&&Date.now()>deadlineAt)continue;if(attemptsRun+=1,last=await run(attempt,deadlineAt),!isRetryable(last))return{value:last,attemptsRun};if(attempt<REVIEWER_SCOPE_CAPTURE_ATTEMPTS)await sleepBounded(backoff)}return{value:last,attemptsRun}}async function verifyWorkingTreeClean(directory){let child,timeoutHandle;try{return child=_internals226.spawn(_internals226.resolveGitExecutable(),["status","--porcelain"],{cwd:directory,stdio:["ignore","pipe","ignore"],timeout:NOCHANGE_STATUS_TIMEOUT_MS,windowsHide:!0}),await new Promise((resolve108)=>{let settled=!1,stdoutBytes=0,chunks=[],finish=(value)=>{if(settled)return;if(settled=!0,timeoutHandle!==void 0)clearTimeout(timeoutHandle);resolve108(value)},killUnverifiable=()=>{try{child?.kill()}catch{}finish("unverifiable")};timeoutHandle=setTimeout(killUnverifiable,NOCHANGE_STATUS_TIMEOUT_MS),timeoutHandle.unref?.(),child?.once("error",killUnverifiable),child?.stdout?.on("data",(chunk)=>{let bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);if(stdoutBytes+=bytes.byteLength,stdoutBytes>NOCHANGE_STATUS_BYTES){killUnverifiable();return}chunks.push(bytes)}),child?.once("close",(exitCode)=>{if(exitCode!==0){finish("unverifiable");return}finish(Buffer.concat(chunks).toString("utf-8").trim().length===0?"clean":"dirty")})})}catch{return"unverifiable"}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);try{child?.kill()}catch{}}}function reviewerManifestPromptBlock(input){let header=["<reviewer_scope_manifest>",`description: ${input.description}`,`manifest_hash: ${input.hash}`,`head: ${input.headSha}`,`workspace: ${input.workspaceIdentity}`],full=input.entries.map((entry)=>entry.state==="deleted"?`${JSON.stringify(entry.path)} state=deleted delivery=${entry.mode}`:`${JSON.stringify(entry.path)} state=file bytes=${entry.bytes} sha256=${entry.sha256} delivery=${entry.mode}`),instruction=["completeness: exact — every guardrail-observed modified file is listed; none omitted.","Every listed file must be verified against its sha256 (current bytes) before a verdict.","Files with delivery=manual MUST be inspected through read-only tools; inline bytes were not attached.","</reviewer_scope_manifest>"],withEntries=[...header,...full,...instruction].join(`
|
|
7084
7092
|
`);if(withEntries.length<=MANIFEST_PROMPT_BYTES)return withEntries;let pathsOnly=[...header,...input.entries.map((entry)=>JSON.stringify(entry.path)),...instruction].join(`
|
|
7085
7093
|
`);if(pathsOnly.length<=MANIFEST_PROMPT_BYTES)return pathsOnly;return[...header,`files: ${input.entries.length} (manifest too large to list — inspect each declared file via read-only tools; delivery=manual for all)`,...instruction].join(`
|
|
@@ -7403,7 +7411,7 @@ ${scanResult.neutralized}`;return result}catch(error93){if(error93 instanceof DO
|
|
|
7403
7411
|
`);for(let line of lines){if(!line.match(FR_ID_PATTERN2))continue;let matches=line.matchAll(OBLIGATION_PATTERN2);for(let match of matches){let keyword=match[1];if(OBLIGATION_KEYWORDS.includes(keyword))counts[keyword]++}}return counts}function countScenarios(content){let scenarioCount=0,scenarioMatches=content.match(SCENARIO_PATTERN);if(scenarioMatches)scenarioCount+=scenarioMatches.length;let givenWhenThenMatches=content.match(GIVEN_WHEN_THEN_PATTERN);if(givenWhenThenMatches&&givenWhenThenMatches.length>0){if(scenarioCount===0)scenarioCount=(content.match(/\bWhen\s+/gi)||[]).length}return scenarioCount}var lint_spec=createSwarmTool({description:"Reads .swarm/spec.md, lints markdown spec for FR-IDs, obligations, and structure, and returns requirement counts by obligation level, scenario count, and any errors or warnings found.",args:{},async execute(_args,directory){let errors5=[],warnings=[],spec=readEffectiveSpecSync(directory);if(!spec)return JSON.stringify({valid:!1,specMtime:null,requirementCount:{MUST:0,SHALL:0,SHOULD:0,MAY:0,total:0},scenarioCount:0,errors:["spec.md not found and no valid OpenSpec-compatible projection available"],warnings:[]},null,2);let{mtime:specMtime,content}=spec,contentValidation=validateSpecContent(content);if(!contentValidation.valid)for(let issue3 of contentValidation.issues)errors5.push(`Line ${issue3.line}: ${issue3.message}`);let obligationCounts=countRequirementsByObligation(content),totalRequirements=Object.values(obligationCounts).reduce((sum,count)=>sum+count,0),scenarioCount=countScenarios(content),result={valid:errors5.length===0,specMtime,requirementCount:{...obligationCounts,total:totalRequirements},scenarioCount,errors:errors5,warnings:[...warnings,...spec.warnings]};return JSON.stringify(result,null,2)}});init_zod();init_engine();import*as fs181 from"node:fs";import*as path307 from"node:path";var _internals263={evaluateMutationGate,buildTestImprovementPrompt,buildMessage};function evaluateMutationGate(report,passThreshold=0.8,warnThreshold=0.6){if(passThreshold<warnThreshold)throw Error(`Invalid thresholds: passThreshold (${passThreshold}) must be >= warnThreshold (${warnThreshold})`);let adjustedKillRate=report.adjustedKillRate,survivedMutants=report.results.filter((result)=>result.outcome==="survived"),verdict;if(adjustedKillRate>=passThreshold)verdict="pass";else if(adjustedKillRate>=warnThreshold)verdict="warn";else verdict="fail";let testImprovementPrompt=_internals263.buildTestImprovementPrompt(report,passThreshold,verdict),message=_internals263.buildMessage(verdict,adjustedKillRate,report.killed,report.totalMutants,report.equivalent,warnThreshold);return{verdict,killRate:report.killRate,adjustedKillRate,totalMutants:report.totalMutants,killed:report.killed,survived:report.survived,threshold:passThreshold,warnThreshold,message,survivedMutants,testImprovementPrompt}}function buildTestImprovementPrompt(report,passThreshold,verdict){if(verdict==="pass")return"";let lowKillRateFunctions=[];for(let[key2,stats2]of report.perFunction)if(stats2.killRate<passThreshold){let lastColon=key2.lastIndexOf(":");if(lastColon===-1)continue;let filePath=key2.substring(0,lastColon),functionName=key2.substring(lastColon+1);lowKillRateFunctions.push(` - ${functionName} in ${filePath}: ${Math.round(stats2.killRate*100)}% kill rate (${stats2.killed}/${stats2.total} killed)`)}if(lowKillRateFunctions.length===0)return"";return`The following functions have low mutation kill rates and need stronger tests:
|
|
7404
7412
|
`+lowKillRateFunctions.join(`
|
|
7405
7413
|
`)}function buildMessage(verdict,adjustedKillRate,killed,totalMutants,equivalent,warnThreshold){let killRatePercent=Math.round(adjustedKillRate*100),effectiveTotal=totalMutants-equivalent;switch(verdict){case"pass":return`Mutation gate PASSED: ${killRatePercent}% kill rate (${killed}/${effectiveTotal} mutants killed)`;case"warn":return`Mutation gate WARNING: ${killRatePercent}% kill rate (${killed}/${effectiveTotal} mutants killed). Test improvement recommended.`;case"fail":return`Mutation gate FAILED: ${killRatePercent}% kill rate (${killed}/${effectiveTotal} mutants killed). Below minimum threshold of ${Math.round(warnThreshold*100)}%.`}}init_create_tool();init_resolve_working_directory();var mutation_test=createSwarmTool({description:"Execute mutation testing with pre-generated patches — applies each mutant patch, runs tests, and evaluates kill rate against quality gate thresholds. Returns verdict (pass/warn/fail) with per-function kill rates and survived mutant details.",args:{patches:exports_external.array(exports_external.object({id:exports_external.string().describe("Unique identifier for the mutation patch"),filePath:exports_external.string().describe("File path to apply the patch to"),functionName:exports_external.string().describe("Function being mutated"),mutationType:exports_external.string().describe("Type of mutation (e.g., off_by_one, null_substitution)"),patch:exports_external.string().describe("Unified diff patch content"),lineNumber:exports_external.number().optional().describe("Line number of the mutation")})).describe("Array of MutationPatch objects — pre-generated mutation patches to execute"),files:exports_external.array(exports_external.string()).describe("Array of test file paths to run against mutants"),test_command:exports_external.array(exports_external.string()).describe('Test command as array of strings (e.g., ["npx", "vitest", "--run"])'),pass_threshold:exports_external.number().optional().describe("Kill rate threshold for pass verdict (default: 0.80)"),warn_threshold:exports_external.number().optional().describe("Kill rate threshold for warn verdict (default: 0.60)"),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.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({error:"files must be a non-empty array of file paths",success:!1},null,2);if(!typedArgs.test_command||!Array.isArray(typedArgs.test_command)||typedArgs.test_command.length===0)return JSON.stringify({error:"test_command must be a non-empty array of strings",success:!1},null,2);if(!typedArgs.test_command.every((c)=>typeof c==="string"))return JSON.stringify({error:"test_command must contain only strings",success:!1},null,2);let cmdValidationError=validateTestCommand(typedArgs.test_command);if(cmdValidationError)return JSON.stringify({error:cmdValidationError,success:!1},null,2);if(!typedArgs.patches||!Array.isArray(typedArgs.patches)||typedArgs.patches.length===0)return JSON.stringify({error:"patches must be a non-empty array of MutationPatch objects",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({success:!1,error:resolved.message},null,2);let cwd=resolved.directory,passThreshold=typedArgs.pass_threshold??0.8,warnThreshold=typedArgs.warn_threshold??0.6,sourceFiles=new Map,uniquePaths=[...new Set(typedArgs.patches.map((p)=>p.filePath))];for(let filePath of uniquePaths)try{let resolvedPath=path307.resolve(cwd,filePath);sourceFiles.set(filePath,fs181.readFileSync(resolvedPath,"utf-8"))}catch{}let report=await executeMutationSuite(typedArgs.patches,typedArgs.test_command,typedArgs.files,cwd,void 0,void 0,sourceFiles.size>0?sourceFiles:void 0),result=evaluateMutationGate(report,passThreshold,warnThreshold);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`mutation_test failed: ${e.message}`:"mutation_test failed: unknown error",success:!1},null,2)}}});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs182 from"node:fs";import*as path308 from"node:path";var OSV_TIMEOUT_MS=60000,OSV_MAX_STDOUT_BYTES=12582912,OSV_MAX_STDERR_BYTES=262144,DEFAULT_MAX_RESULTS3=200,HARD_CAP_RESULTS3=2000;function resolveOsvScannerBinary(){return _internals264.resolveExecutableFromPath(["osv-scanner"])}function normalizeScanPath(value,workspace){let raw=typeof value==="string"&&value.trim()?value.trim():".";if(containsControlChars(raw)||containsPathTraversal(raw))return null;if(path308.isAbsolute(raw)||/^[A-Za-z]:[/\\]/.test(raw))return null;try{let realWorkspace=fs182.realpathSync(workspace),resolved=path308.resolve(realWorkspace,raw),realTarget=fs182.realpathSync(resolved),relative79=path308.relative(realWorkspace,realTarget);if(relative79.startsWith("..")||path308.isAbsolute(relative79))return null;return relative79?relative79.split(path308.sep).join("/"):"."}catch{return null}}function firstString(value){return typeof value==="string"&&value?value:void 0}function collectReferences(vuln){let urls=(Array.isArray(vuln.references)?vuln.references:[]).map((ref)=>ref&&typeof ref==="object"?firstString(ref.url):void 0).filter((url3)=>Boolean(url3));return urls.length>0?urls.slice(0,10):void 0}function parseOsvOutput(stdout,maxResults){let parsed;try{parsed=JSON.parse(stdout)}catch{return{findings:[],total:0,parseError:!0}}let findings=[],total=0,results=Array.isArray(parsed?.results)?parsed.results:[];for(let result of results){let resultObj=result,packages=Array.isArray(resultObj.packages)?resultObj.packages:[];for(let pkg of packages){let pkgObj=pkg,pkgInfo=pkgObj.package??{},vulnerabilities=Array.isArray(pkgObj.vulnerabilities)?pkgObj.vulnerabilities:[];for(let vulnerability of vulnerabilities){let vuln=vulnerability;if(total++,findings.length>=maxResults)continue;let fixedVersion=(Array.isArray(vuln.groups)?vuln.groups:[]).flatMap((group)=>Array.isArray(group.fixed)?group.fixed:[]).map(firstString).find(Boolean);findings.push({id:firstString(vuln.id)??firstString(vuln.osv)??"UNKNOWN",summary:firstString(vuln.summary),packageName:firstString(pkgInfo.name)??firstString(pkgObj.name)??firstString(pkgObj.package),ecosystem:firstString(pkgInfo.ecosystem),installedVersion:firstString(pkgInfo.version)??firstString(pkgObj.version),fixedVersion,aliases:Array.isArray(vuln.aliases)?vuln.aliases.filter((a)=>typeof a==="string"):void 0,references:collectReferences(vuln)})}}}return{findings,total,parseError:!1}}function sanitizeMaxResults2(value){let numeric=typeof value==="number"&&Number.isFinite(value)?value:DEFAULT_MAX_RESULTS3;return Math.min(Math.max(0,numeric),HARD_CAP_RESULTS3)}var osv_scan=createSwarmTool({description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Read-only; resolves osv-scanner lazily.",args:{scan_path:exports_external.string().default(".").describe('Workspace-relative path to scan, default "."'),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS3).describe("Maximum vulnerabilities to return")},execute:async(args2,directory)=>{let obj=typeof args2==="object"&&args2!==null?args2:{},scanPath=normalizeScanPath(obj.scan_path,directory);if(!scanPath)return JSON.stringify({error:!0,type:"path-escape",message:"scan_path must be an existing workspace-relative path"},null,2);let maxResults=sanitizeMaxResults2(obj.max_results),executable=_internals264.resolveOsvScannerBinary();if(!executable)return JSON.stringify({error:!0,type:"osv-scanner-not-found",message:"osv-scanner executable not found. Install OSV-Scanner and ensure osv-scanner is on PATH."},null,2);let osvArgs=["scan","--format","json",scanPath==="."?".":`./${scanPath}`],run=await _internals264.runExternalTool({executable,args:osvArgs,cwd:directory,timeoutMs:OSV_TIMEOUT_MS,maxStdoutBytes:OSV_MAX_STDOUT_BYTES,maxStderrBytes:OSV_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`osv-scanner timed out after ${OSV_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"osv-scanner failed to start"},null,2);let{findings,total,parseError}=parseOsvOutput(run.stdout,maxResults);if(parseError)return JSON.stringify({error:!0,type:"unknown",message:run.stdoutTruncated||run.stderrTruncated?"osv-scanner JSON output was truncated and could not be parsed":"osv-scanner output was not valid JSON"},null,2);if(run.exitCode!==0&&findings.length===0&&run.stderr)return JSON.stringify({error:!0,type:"unknown",message:run.stderr.split(`
|
|
7406
|
-
`)[0]},null,2);return JSON.stringify({clean:total===0&&!run.stdoutTruncated&&!run.stderrTruncated,findings,total,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,command:["osv-scanner",...osvArgs],scanPath,outputTruncated:run.stdoutTruncated||run.stderrTruncated,note:run.exitCode!==0&&total>0?`osv-scanner exited ${run.exitCode} after finding vulnerabilities`:run.stdoutTruncated||run.stderrTruncated?"osv-scanner output was truncated; result is incomplete.":void 0},null,2)}}),_internals264={resolveExecutableFromPath,resolveOsvScannerBinary,runExternalTool,parseOsvOutput};init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_utils2();init_create_tool();import{existsSync as existsSync167}from"node:fs";import*as path309 from"node:path";var ParseLaneCandidatesArgsShape={output_ref:exports_external.string().min(1).describe("Opaque lane output ref returned as output_ref by dispatch_lanes or collect_lane_results."),accept_partial:exports_external.boolean().default(!1).describe("Accept sources where transcriptIncomplete is true (partial transcripts)."),accept_degraded:exports_external.boolean().default(!1).describe("Accept sources where the artifact storage was degraded (output_degraded)."),degraded:exports_external.boolean().default(!1).describe("Passed through from DispatchLaneResult.output_degraded by the orchestrator."),row_format_version:exports_external.number().int().nonnegative().default(1).describe("Row format version; currently only version 1 is supported."),producer:exports_external.string().optional().default("swarm-pr-review").describe("Producer label for cross-skill filtering in the sidecar."),expected_family:exports_external.enum(["base_explorer","micro_lane"]).optional().describe("Assert the row family for this dispatch batch. A recognizable conflicting header is refused."),expected_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the base-explorer lane linked to this dispatch provenance. Requires expected_family=base_explorer; mismatched base CLEAN attestations are refused."),expected_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned base-explorer lane set for a consolidated batch. Requires expected_family=base_explorer and expected_lane; owned-but-not-expected lanes are skipped as out-of-scope for this per-lane call instead of refused, while foreign lanes are still refused."),expected_micro_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the micro-lane label linked to this dispatch provenance. Requires expected_family=micro_lane; mismatched candidates and CLEAN attestations are refused."),expected_micro_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned family set of a consolidated depth-tier lane. Requires expected_family=micro_lane and expected_micro_lane; rows for owned-but-not-expected families are skipped as out-of-scope for this per-family call instead of refused, while families outside the set are still refused."),use_lockfile:exports_external.boolean().default(!1).describe("When true, use proper-lockfile for concurrency-safe sidecar writes."),project_root:exports_external.string().optional().describe("Project root directory where .swarm/ lives. Defaults to the injected working directory.")},ParseLaneCandidatesArgsSchema=exports_external.object(ParseLaneCandidatesArgsShape).strict().superRefine((value,context)=>{for(let issue3 of analyzeCandidateLaneContext(value))context.addIssue({code:exports_external.ZodIssueCode.custom,path:[issue3.field],message:issue3.message})}),REF_RE2=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/;function laneOutputRelativePath2(ref){let parts=ref.split(":");if(parts.length!==4)return"";let[,batchDigest,laneDigest,outputDigest]=parts;return path309.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}var parse_lane_candidates=createSwarmTool({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.",args:{output_ref:ParseLaneCandidatesArgsShape.output_ref,accept_partial:ParseLaneCandidatesArgsShape.accept_partial,accept_degraded:ParseLaneCandidatesArgsShape.accept_degraded,degraded:ParseLaneCandidatesArgsShape.degraded,row_format_version:ParseLaneCandidatesArgsShape.row_format_version,producer:ParseLaneCandidatesArgsShape.producer,expected_family:ParseLaneCandidatesArgsShape.expected_family,expected_lane:ParseLaneCandidatesArgsShape.expected_lane,expected_lanes:ParseLaneCandidatesArgsShape.expected_lanes,expected_micro_lane:ParseLaneCandidatesArgsShape.expected_micro_lane,expected_micro_lanes:ParseLaneCandidatesArgsShape.expected_micro_lanes,use_lockfile:ParseLaneCandidatesArgsShape.use_lockfile,project_root:ParseLaneCandidatesArgsShape.project_root},async execute(args2,directory){let parsed=ParseLaneCandidatesArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,failure_class:"invalid_args",message:"Invalid parse_lane_candidates arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)},null,2);let{output_ref,accept_partial,accept_degraded,degraded,row_format_version,producer,expected_family,expected_lane,expected_lanes,expected_micro_lane,expected_micro_lanes,use_lockfile,project_root}=parsed.data;if(project_root!==void 0){let absRoot=path309.resolve(project_root),absDir=path309.resolve(directory),rel3=path309.relative(absDir,absRoot);if(rel3===".."||rel3.startsWith(`..${path309.sep}`)||path309.isAbsolute(rel3))return JSON.stringify({success:!1,failure_class:"invalid_args",message:"project_root must resolve within the injected working directory",errors:[`project_root: ${project_root} is outside the project root ${directory}`]},null,2)}let loaded;try{loaded=readLaneOutput(directory,output_ref)}catch{loaded=null}if(!loaded){let relPath=REF_RE2.test(output_ref)?laneOutputRelativePath2(output_ref):"",absPath=relPath?validateSwarmPath(directory,relPath):"",artifactStatus=(absPath?existsSync167(absPath):!1)?"artifact-corrupted":"ref-not-found",refParts=output_ref.split(":"),hasValidRef=REF_RE2.test(output_ref)&&refParts.length===4,syntheticBatchId=hasValidRef?refParts[1]:"unknown",syntheticLaneId=hasValidRef?refParts[2]:"unknown",syntheticDigest="0".repeat(64),artifactInput2={output_ref,batchId:syntheticBatchId,laneId:syntheticLaneId,agent:"unknown",role:"unknown",digest:syntheticDigest,text:"",artifact_status:artifactStatus,source:"dispatch_lanes",produced_at:new Date().toISOString()},flags2={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result2=parseAndPersist(artifactInput2,flags2,{projectRoot:project_root??directory,useLockfile:use_lockfile,batchDigest:syntheticBatchId});return JSON.stringify(result2,null,2)}let artifact=loaded.artifact,artifactInput={output_ref:artifact.ref,batchId:artifact.batchId,laneId:artifact.laneId,agent:artifact.agent,role:artifact.role,...artifact.sessionId!==void 0?{sessionId:artifact.sessionId}:{},...artifact.parentSessionId!==void 0?{parentSessionId:artifact.parentSessionId}:{},digest:artifact.digest,text:artifact.text,transcriptIncomplete:artifact.transcriptIncomplete,artifact_status:"ok",source:artifact.source,produced_at:artifact.createdAt??artifact.updatedAt},flags={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result=parseAndPersist(artifactInput,flags,{projectRoot:project_root??directory,useLockfile:use_lockfile});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_core_events();init_manager2();import{createHash as createHash96}from"node:crypto";import*as fs193 from"node:fs";import*as path320 from"node:path";init_utils2();init_logger();init_state3();import*as fs183 from"node:fs";import*as path310 from"node:path";var APPROVAL_TTL_MS=86400000;function readEvidenceDir(directory,phase){try{let dirPath=validateSwarmPath(directory,path310.posix.join("evidence",String(phase)));if(!fs183.existsSync(dirPath))return[];return fs183.readdirSync(dirPath).filter((e)=>e.startsWith("full-auto-")&&e.endsWith(".json")).map((e)=>path310.join(dirPath,e))}catch{return[]}}function parseEvidence(filePath){try{let raw=fs183.readFileSync(filePath,"utf-8");return JSON.parse(raw)}catch(error93){warn(`[full-auto/phase-approval] failed to parse ${filePath}: ${error93 instanceof Error?error93.message:String(error93)}`);return}}function verifyFullAutoPhaseApproval(directory,sessionID,phase,config3){let fullAutoConfig=config3.full_auto;if(!sessionID)return{ok:!0,reason:"no sessionID — gate skipped"};if(!isFullAutoRunActive(directory,sessionID))return{ok:!0,reason:"no active Full-Auto run"};let failClosed=fullAutoConfig?.fail_closed!==!1,files=readEvidenceDir(directory,phase);if(files.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no full-auto oversight evidence found at .swarm/evidence/${phase}/`}:{ok:!0,reason:"no evidence and fail_closed=false"};let phaseBoundary=files.map((f)=>parseEvidence(f)).filter((e)=>Boolean(e)).filter((e)=>e.phase===phase&&e.trigger_source==="phase_boundary"&&(e.verdict??"").toUpperCase()==="APPROVED");if(phaseBoundary.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no phase-boundary oversight record found for phase ${phase}`}:{ok:!0,reason:"no phase-boundary record and fail_closed=false"};phaseBoundary.sort((a,b)=>{let ta=a.timestamp?Date.parse(a.timestamp):0;return(b.timestamp?Date.parse(b.timestamp):0)-ta});let latest=phaseBoundary[0],verdict=latest.verdict?.toUpperCase()??"";if(verdict!=="APPROVED")return{ok:!1,reason:`Full-Auto oversight verdict for phase ${phase} is ${verdict||"MISSING"} (required: APPROVED)`,evidence:latest};let FORWARD_SKEW_MS=300000,ts=latest.timestamp?Date.parse(latest.timestamp):0,age=Date.now()-ts;if(!ts||age<-FORWARD_SKEW_MS||age>APPROVAL_TTL_MS)return{ok:!1,reason:age<-FORWARD_SKEW_MS?`Full-Auto oversight evidence for phase ${phase} has a future timestamp (${latest.timestamp}); rejected as forged or clock-skewed`:`Full-Auto oversight evidence for phase ${phase} is stale (>24h)`,evidence:latest};if((Array.isArray(latest.evidence_checked)?latest.evidence_checked:[]).length===0){let exception=phaseIsExplicitlyNonCode(directory,phase),runState=loadFullAutoRunState(directory,sessionID),codeWorkObserved=(runState?.counters.coderDelegations??0)>0||(runState?.counters.toolCalls??0)>0;if(!exception||codeWorkObserved)return{ok:!1,reason:!exception?`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked and the phase is not declared non-code in plan.json (required: at least one verification source)`:`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked while run counters indicate code work was performed`,evidence:latest};return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp} (non-code phase exception)`,evidence:latest}}return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp}`,evidence:latest}}function phaseIsExplicitlyNonCode(directory,phase){try{let planPath=validateSwarmPath(directory,"plan.json");if(!fs183.existsSync(planPath))return!1;let raw=fs183.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw),entry=(Array.isArray(plan.phases)?plan.phases:[]).find((p)=>p.id===phase||p.phase===phase);if(!entry)return!1;if(entry.non_code===!0)return!0;let kindOrType=(entry.kind??entry.type??"").toString().toLowerCase();return["docs","documentation","spec","specification","research","planning","plan","non_code","non-code","noncode"].includes(kindOrType)}catch(error93){return warn(`[full-auto/phase-approval] plan.json inspection failed: ${error93 instanceof Error?error93.message:String(error93)}`),!1}}init_gate_evidence();init_curator();init_curator_llm_factory();init_extractors();init_knowledge_curator();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_events();init_knowledge_receipt_ledger();function classifyDirectiveGateFailure(error93){if(typeof error93==="object"&&error93!==null&&"ok"in error93&&error93.ok===!1&&"code"in error93){let unavailable2=error93;if(unavailable2.code==="store_corrupt")return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(unavailable2.code==="lock_timeout")return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};error93=unavailable2.detail}let lower=(error93 instanceof Error?error93.message:typeof error93==="string"?error93:"").toLowerCase();if(lower.includes("exact session identity"))return{failure:{code:"RECEIPT_MISSING",action_id:"knowledge_receipt"},recovery:{kind:"tool",action:"knowledge_receipt"}};if(lower.includes("corrupt")||lower.includes("legacy_unverifiable"))return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("lock_timeout"))return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};if(lower.includes("project root")||lower.includes("root"))return{failure:{code:"RECEIPT_WRONG_ROOT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("eacces")||lower.includes("eperm")||lower.includes("permission"))return{failure:{code:"RECEIPT_PERMISSION",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("ebusy")||lower.includes("temporar")||lower.includes("transient"))return{failure:{code:"RECEIPT_TRANSIENT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};return{failure:{code:"RECEIPT_STORE_UNAVAILABLE",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}}}async function evaluatePhaseCriticalDirectives(params){try{if(!params.phaseLabel?.trim())throw Error("directive gate requires exact phase identity");let state=await queryLiveMemberships(params.directory,{phase:params.phaseLabel,session_id:params.sessionId?.trim()||void 0,include_terminal:!0,include_phase_closed:!1});if(!state.ok)return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(state)};let criticals=state.memberships.filter((membership)=>membership.critical);if(!params.sessionId?.trim()&&criticals.length>0)throw Error("directive gate requires exact session identity");if(criticals.length===0)return{blocked:!1,unresolved:[],overridden:[],failedClosed:!1};let unresolved=[],overridden=[];for(let membership of criticals){let terminal=membership.terminal;if(terminal?.authorized_transition){overridden.push(membership.entry_id);continue}if(terminal?.outcome==="applied")continue;if((terminal?.outcome==="ignored"||terminal?.outcome==="n_a")&&terminal.reason?.trim())continue;unresolved.push({id:membership.entry_id,trace_id:membership.trace_id,reason:terminal?.outcome==="violated"||terminal?.outcome==="contradicted"?"unremediated_violation":"no_verdict"})}return{blocked:unresolved.length>0,unresolved,overridden,failedClosed:!1}}catch(error93){return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(error93)}}}async function recordDirectiveOverrides(directory,ids,justification,sessionId,phaseLabel){if(!justification.trim())throw Error("directive override requires a written justification");if(!sessionId?.trim()||!phaseLabel?.trim())throw Error("directive override requires exact session and phase identity");let state=await queryLiveMemberships(directory,{phase:phaseLabel,session_id:sessionId,include_terminal:!0,include_phase_closed:!1});if(!state.ok)throw Error(state.detail);let criticals=state.memberships.filter((membership)=>membership.critical),selected=ids.map((requested)=>{let exact=criticals.filter((membership)=>`${membership.trace_id}/${membership.entry_id}`===requested);if(exact.length===1)return exact[0];let byEntry=criticals.filter((membership)=>membership.entry_id===requested);if(byEntry.length!==1)throw Error(byEntry.length===0?`unknown directive override target: ${requested}`:`ambiguous directive override target; use trace_id/entry_id: ${requested}`);return byEntry[0]});for(let membership of selected){let outcome=membership.terminal?.outcome??"n_a",committed=await validateAndCommitTerminalBatch(directory,{trace_id:membership.trace_id,session_id:sessionId,phase:phaseLabel,task_id:membership.task_id,items:[{entry_id:membership.entry_id,outcome,source:"phase_override",reason:justification}],authorization:{actor:"phase-override",reason:justification,expected_event_id:membership.terminal?.event_id??""}});if(!committed.ok||committed.rejected.length>0)throw Error("failed to persist authoritative directive override");try{await recordKnowledgeEvent(directory,{type:"override",trace_id:membership.trace_id,knowledge_id:membership.entry_id,session_id:sessionId,agent:"architect",source:"phase_override",reason:`override: ${justification}`.slice(0,280)})}catch{}}}function formatDirectiveBlockMessage(unresolved){return["PHASE_COMPLETE_BLOCKED: unresolved critical knowledge directive(s):",...unresolved.map((u)=>{let why=u.reason==="no_verdict"?"no terminal verdict (applied/verified/ignored+reason/n_a+reason)":"violated with no subsequent applied/verified remediation";return` - ${u.trace_id?`${u.trace_id}/${u.id}`:u.id}: ${why}`}),"Resolve each by applying/verifying the directive, recording an explicit","ignored/n_a with a reason, or use the separate architect-only record_directive_override action with a","written justification."].join(`
|
|
7414
|
+
`)[0]},null,2);return JSON.stringify({clean:total===0&&!run.stdoutTruncated&&!run.stderrTruncated,findings,total,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,command:["osv-scanner",...osvArgs],scanPath,outputTruncated:run.stdoutTruncated||run.stderrTruncated,note:run.exitCode!==0&&total>0?`osv-scanner exited ${run.exitCode} after finding vulnerabilities`:run.stdoutTruncated||run.stderrTruncated?"osv-scanner output was truncated; result is incomplete.":void 0},null,2)}}),_internals264={resolveExecutableFromPath,resolveOsvScannerBinary,runExternalTool,parseOsvOutput};init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_utils2();init_create_tool();import{existsSync as existsSync167}from"node:fs";import*as path309 from"node:path";var ParseLaneCandidatesArgsShape={output_ref:exports_external.string().min(1).describe("Opaque lane output ref returned as output_ref by dispatch_lanes or collect_lane_results."),accept_partial:exports_external.boolean().default(!1).describe("Accept sources where transcriptIncomplete is true (partial transcripts)."),accept_degraded:exports_external.boolean().default(!1).describe("Accept sources where the artifact storage was degraded (output_degraded)."),degraded:exports_external.boolean().default(!1).describe("Passed through from DispatchLaneResult.output_degraded by the orchestrator."),row_format_version:exports_external.number().int().nonnegative().default(1).describe("Row format version; currently only version 1 is supported."),producer:exports_external.string().optional().default("swarm-pr-review").describe("Producer label for cross-skill filtering in the sidecar."),expected_family:exports_external.enum(["base_explorer","micro_lane"]).optional().describe("Assert the row family for this dispatch batch. A recognizable conflicting header is refused."),expected_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the base-explorer lane linked to this dispatch provenance. Requires expected_family=base_explorer; mismatched base CLEAN attestations are refused."),expected_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned base-explorer lane set for a consolidated batch. Requires expected_family=base_explorer and expected_lane; owned-but-not-expected lanes are skipped as out-of-scope for this per-lane call instead of refused, while foreign lanes are still refused."),expected_micro_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the micro-lane label linked to this dispatch provenance. Requires expected_family=micro_lane; mismatched candidates and CLEAN attestations are refused."),expected_micro_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned family set of a consolidated depth-tier lane. Requires expected_family=micro_lane and expected_micro_lane; rows for owned-but-not-expected families are skipped as out-of-scope for this per-family call instead of refused, while families outside the set are still refused."),use_lockfile:exports_external.boolean().default(!1).describe("When true, use proper-lockfile for concurrency-safe sidecar writes."),project_root:exports_external.string().optional().describe("Project root directory where .swarm/ lives. Defaults to the injected working directory.")},ParseLaneCandidatesArgsSchema=exports_external.object(ParseLaneCandidatesArgsShape).strict().superRefine((value,context)=>{for(let issue3 of analyzeCandidateLaneContext(value))context.addIssue({code:exports_external.ZodIssueCode.custom,path:[issue3.field],message:issue3.message})}),REF_RE2=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/;function laneOutputRelativePath2(ref){let parts=ref.split(":");if(parts.length!==4)return"";let[,batchDigest,laneDigest,outputDigest]=parts;return path309.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}var parse_lane_candidates=createSwarmTool({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.",args:{output_ref:ParseLaneCandidatesArgsShape.output_ref,accept_partial:ParseLaneCandidatesArgsShape.accept_partial,accept_degraded:ParseLaneCandidatesArgsShape.accept_degraded,degraded:ParseLaneCandidatesArgsShape.degraded,row_format_version:ParseLaneCandidatesArgsShape.row_format_version,producer:ParseLaneCandidatesArgsShape.producer,expected_family:ParseLaneCandidatesArgsShape.expected_family,expected_lane:ParseLaneCandidatesArgsShape.expected_lane,expected_lanes:ParseLaneCandidatesArgsShape.expected_lanes,expected_micro_lane:ParseLaneCandidatesArgsShape.expected_micro_lane,expected_micro_lanes:ParseLaneCandidatesArgsShape.expected_micro_lanes,use_lockfile:ParseLaneCandidatesArgsShape.use_lockfile,project_root:ParseLaneCandidatesArgsShape.project_root},async execute(args2,directory){let parsed=ParseLaneCandidatesArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,failure_class:"invalid_args",message:"Invalid parse_lane_candidates arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)},null,2);let{output_ref,accept_partial,accept_degraded,degraded,row_format_version,producer,expected_family,expected_lane,expected_lanes,expected_micro_lane,expected_micro_lanes,use_lockfile,project_root}=parsed.data;if(project_root!==void 0){let absRoot=path309.resolve(project_root),absDir=path309.resolve(directory),rel3=path309.relative(absDir,absRoot);if(rel3===".."||rel3.startsWith(`..${path309.sep}`)||path309.isAbsolute(rel3))return JSON.stringify({success:!1,failure_class:"invalid_args",message:"project_root must resolve within the injected working directory",errors:[`project_root: ${project_root} is outside the project root ${directory}`]},null,2)}let loaded;try{loaded=readLaneOutput(directory,output_ref)}catch{loaded=null}if(!loaded){let relPath=REF_RE2.test(output_ref)?laneOutputRelativePath2(output_ref):"",absPath=relPath?validateSwarmPath(directory,relPath):"",artifactStatus=(absPath?existsSync167(absPath):!1)?"artifact-corrupted":"ref-not-found",refParts=output_ref.split(":"),hasValidRef=REF_RE2.test(output_ref)&&refParts.length===4,syntheticBatchId=hasValidRef?refParts[1]:"unknown",syntheticLaneId=hasValidRef?refParts[2]:"unknown",syntheticDigest="0".repeat(64),artifactInput2={output_ref,batchId:syntheticBatchId,laneId:syntheticLaneId,agent:"unknown",role:"unknown",digest:syntheticDigest,text:"",artifact_status:artifactStatus,source:"dispatch_lanes",produced_at:new Date().toISOString()},flags2={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result2=parseAndPersist(artifactInput2,flags2,{projectRoot:project_root??directory,useLockfile:use_lockfile,batchDigest:syntheticBatchId});return JSON.stringify(result2,null,2)}let artifact=loaded.artifact,artifactInput={output_ref:artifact.ref,batchId:artifact.batchId,laneId:artifact.laneId,agent:artifact.agent,role:artifact.role,...artifact.sessionId!==void 0?{sessionId:artifact.sessionId}:{},...artifact.parentSessionId!==void 0?{parentSessionId:artifact.parentSessionId}:{},digest:artifact.digest,text:artifact.text,transcriptIncomplete:artifact.transcriptIncomplete,artifact_status:"ok",source:artifact.source,produced_at:artifact.createdAt??artifact.updatedAt},flags={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result=parseAndPersist(artifactInput,flags,{projectRoot:project_root??directory,useLockfile:use_lockfile});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_core_events();init_manager2();import{createHash as createHash96}from"node:crypto";import*as fs193 from"node:fs";import*as path320 from"node:path";init_utils2();init_logger();init_state3();import*as fs183 from"node:fs";import*as path310 from"node:path";var APPROVAL_TTL_MS=86400000;function readEvidenceDir(directory,phase){try{let dirPath=validateSwarmPath(directory,path310.posix.join("evidence",String(phase)));if(!fs183.existsSync(dirPath))return[];return fs183.readdirSync(dirPath).filter((e)=>e.startsWith("full-auto-")&&e.endsWith(".json")).map((e)=>path310.join(dirPath,e))}catch{return[]}}function parseEvidence(filePath){try{let raw=fs183.readFileSync(filePath,"utf-8");return JSON.parse(raw)}catch(error93){warn(`[full-auto/phase-approval] failed to parse ${filePath}: ${error93 instanceof Error?error93.message:String(error93)}`);return}}function verifyFullAutoPhaseApproval(directory,sessionID,phase,config3){let fullAutoConfig=config3.full_auto;if(!sessionID)return{ok:!0,reason:"no sessionID — gate skipped"};if(!isFullAutoRunActive(directory,sessionID))return{ok:!0,reason:"no active Full-Auto run"};let failClosed=fullAutoConfig?.fail_closed!==!1,files=readEvidenceDir(directory,phase);if(files.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no full-auto oversight evidence found at .swarm/evidence/${phase}/`}:{ok:!0,reason:"no evidence and fail_closed=false"};let phaseBoundary=files.map((f)=>parseEvidence(f)).filter((e)=>Boolean(e)).filter((e)=>e.phase===phase&&e.trigger_source==="phase_boundary"&&(e.verdict??"").toUpperCase()==="APPROVED");if(phaseBoundary.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no phase-boundary oversight record found for phase ${phase}`}:{ok:!0,reason:"no phase-boundary record and fail_closed=false"};phaseBoundary.sort((a,b)=>{let ta=a.timestamp?Date.parse(a.timestamp):0;return(b.timestamp?Date.parse(b.timestamp):0)-ta});let latest=phaseBoundary[0],verdict=latest.verdict?.toUpperCase()??"";if(verdict!=="APPROVED")return{ok:!1,reason:`Full-Auto oversight verdict for phase ${phase} is ${verdict||"MISSING"} (required: APPROVED)`,evidence:latest};let FORWARD_SKEW_MS=300000,ts=latest.timestamp?Date.parse(latest.timestamp):0,age=Date.now()-ts;if(!ts||age<-FORWARD_SKEW_MS||age>APPROVAL_TTL_MS)return{ok:!1,reason:age<-FORWARD_SKEW_MS?`Full-Auto oversight evidence for phase ${phase} has a future timestamp (${latest.timestamp}); rejected as forged or clock-skewed`:`Full-Auto oversight evidence for phase ${phase} is stale (>24h)`,evidence:latest};if((Array.isArray(latest.evidence_checked)?latest.evidence_checked:[]).length===0){let exception=phaseIsExplicitlyNonCode(directory,phase),runState=loadFullAutoRunState(directory,sessionID),codeWorkObserved=(runState?.counters.coderDelegations??0)>0||(runState?.counters.toolCalls??0)>0;if(!exception||codeWorkObserved)return{ok:!1,reason:!exception?`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked and the phase is not declared non-code in plan.json (required: at least one verification source)`:`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked while run counters indicate code work was performed`,evidence:latest};return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp} (non-code phase exception)`,evidence:latest}}return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp}`,evidence:latest}}function phaseIsExplicitlyNonCode(directory,phase){try{let planPath=validateSwarmPath(directory,"plan.json");if(!fs183.existsSync(planPath))return!1;let raw=fs183.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw),entry=(Array.isArray(plan.phases)?plan.phases:[]).find((p)=>p.id===phase||p.phase===phase);if(!entry)return!1;if(entry.non_code===!0)return!0;let kindOrType=(entry.kind??entry.type??"").toString().toLowerCase();return["docs","documentation","spec","specification","research","planning","plan","non_code","non-code","noncode"].includes(kindOrType)}catch(error93){return warn(`[full-auto/phase-approval] plan.json inspection failed: ${error93 instanceof Error?error93.message:String(error93)}`),!1}}init_gate_evidence();init_curator();init_curator_llm_factory();init_extractors();init_knowledge_curator();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_events();init_knowledge_receipt_ledger();function classifyDirectiveGateFailure(error93){if(typeof error93==="object"&&error93!==null&&"ok"in error93&&error93.ok===!1&&"code"in error93){let unavailable2=error93;if(unavailable2.code==="store_corrupt")return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(unavailable2.code==="lock_timeout")return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};error93=unavailable2.detail}let lower=(error93 instanceof Error?error93.message:typeof error93==="string"?error93:"").toLowerCase();if(lower.includes("exact session identity"))return{failure:{code:"RECEIPT_MISSING",action_id:"knowledge_receipt"},recovery:{kind:"tool",action:"knowledge_receipt"}};if(lower.includes("corrupt")||lower.includes("legacy_unverifiable"))return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("lock_timeout"))return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};if(lower.includes("project root")||lower.includes("root"))return{failure:{code:"RECEIPT_WRONG_ROOT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("eacces")||lower.includes("eperm")||lower.includes("permission"))return{failure:{code:"RECEIPT_PERMISSION",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("ebusy")||lower.includes("temporar")||lower.includes("transient"))return{failure:{code:"RECEIPT_TRANSIENT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};return{failure:{code:"RECEIPT_STORE_UNAVAILABLE",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}}}async function evaluatePhaseCriticalDirectives(params){try{if(!params.phaseLabel?.trim())throw Error("directive gate requires exact phase identity");let state=await queryLiveMemberships(params.directory,{phase:params.phaseLabel,session_id:params.sessionId?.trim()||void 0,include_terminal:!0,include_phase_closed:!1});if(!state.ok)return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(state)};let criticals=state.memberships.filter((membership)=>membership.critical);if(!params.sessionId?.trim()&&criticals.length>0)throw Error("directive gate requires exact session identity");if(criticals.length===0)return{blocked:!1,unresolved:[],overridden:[],failedClosed:!1};let byEntry=new Map;for(let membership of criticals){let group=byEntry.get(membership.entry_id)??[];group.push(membership),byEntry.set(membership.entry_id,group)}let isSatisfied=(membership)=>{let terminal=membership.terminal;if(terminal?.authorized_transition)return!0;if(terminal?.outcome==="applied")return!0;return(terminal?.outcome==="ignored"||terminal?.outcome==="n_a")&&Boolean(terminal.reason?.trim())},isViolation=(outcome)=>outcome==="violated"||outcome==="contradicted",unresolved=[],overridden=[];for(let[entryId,members]of byEntry){for(let membership of members)if(membership.terminal?.authorized_transition)overridden.push(entryId);let hasSatisfied=members.some((membership)=>isSatisfied(membership)),violated=members.filter((membership)=>membership.terminal!==void 0&&!membership.terminal.authorized_transition&&isViolation(membership.terminal.outcome)),unremediated=violated.filter((membership)=>!members.some((other)=>other.terminal?.outcome==="applied"&&other.terminal.committed_at>membership.terminal.committed_at));if(hasSatisfied&&unremediated.length===0)continue;let representative=[...members].sort((a,b)=>{let aViolated=a.terminal!==void 0&&isViolation(a.terminal.outcome)?0:1,bViolated=b.terminal!==void 0&&isViolation(b.terminal.outcome)?0:1;if(aViolated!==bViolated)return aViolated-bViolated;if(a.committed_at!==b.committed_at)return a.committed_at<b.committed_at?1:-1;return a.trace_id<b.trace_id?1:-1})[0];unresolved.push({id:entryId,trace_id:representative.trace_id,reason:violated.length>0?"unremediated_violation":"no_verdict"})}return unresolved.sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0),{blocked:unresolved.length>0,unresolved,overridden:[...new Set(overridden)],failedClosed:!1}}catch(error93){return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(error93)}}}async function recordDirectiveOverrides(directory,ids,justification,sessionId,phaseLabel){if(!justification.trim())throw Error("directive override requires a written justification");if(!sessionId?.trim()||!phaseLabel?.trim())throw Error("directive override requires exact session and phase identity");let state=await queryLiveMemberships(directory,{phase:phaseLabel,session_id:sessionId,include_terminal:!0,include_phase_closed:!1});if(!state.ok)throw Error(state.detail);let criticals=state.memberships.filter((membership)=>membership.critical),selected=ids.map((requested)=>{let exact=criticals.filter((membership)=>`${membership.trace_id}/${membership.entry_id}`===requested);if(exact.length===1)return exact[0];let byEntry=criticals.filter((membership)=>membership.entry_id===requested);if(byEntry.length!==1)throw Error(byEntry.length===0?`unknown directive override target: ${requested}`:`ambiguous directive override target; use trace_id/entry_id: ${requested}`);return byEntry[0]});for(let membership of selected){let outcome=membership.terminal?.outcome??"n_a",committed=await validateAndCommitTerminalBatch(directory,{trace_id:membership.trace_id,session_id:sessionId,phase:phaseLabel,task_id:membership.task_id,items:[{entry_id:membership.entry_id,outcome,source:"phase_override",reason:justification}],authorization:{actor:"phase-override",reason:justification,expected_event_id:membership.terminal?.event_id??""}});if(!committed.ok||committed.rejected.length>0)throw Error("failed to persist authoritative directive override");try{await recordKnowledgeEvent(directory,{type:"override",trace_id:membership.trace_id,knowledge_id:membership.entry_id,session_id:sessionId,agent:"architect",source:"phase_override",reason:`override: ${justification}`.slice(0,280)})}catch{}}}function formatDirectiveBlockMessage(unresolved){return["PHASE_COMPLETE_BLOCKED: unresolved critical knowledge directive(s):",...unresolved.map((u)=>{let why=u.reason==="no_verdict"?"no terminal verdict (applied/verified/ignored+reason/n_a+reason)":"violated with no subsequent applied/verified remediation";return` - ${u.trace_id?`${u.trace_id}/${u.id}`:u.id}: ${why}`}),"Resolve each by applying/verifying the directive, recording an explicit","ignored/n_a with a reason, or use the separate architect-only record_directive_override action with a","written justification."].join(`
|
|
7407
7415
|
`)}init_review_receipt();init_skill_usage_log();init_utils2();init_file_locks();init_plan_schema();init_ledger();init_utils3();init_warning_buffer();init_logger();init_project_boundary();init_manager();import*as fs184 from"node:fs";import*as path311 from"node:path";var _fsInternals={mkdirSync:(...args2)=>fs184.mkdirSync(...args2),writeFileSync:(path312,data,encoding)=>fs184.writeFileSync(path312,data,encoding??"utf8"),readFileSync:(path312,encoding)=>fs184.readFileSync(path312,encoding??"utf8"),existsSync:(path312)=>fs184.existsSync(path312)};async function writeCheckpoint(directory){try{assertProjectRoot(directory);let plan=await loadPlan(directory);if(!plan)return;let exportDir=path311.join(directory,".swarm","plan-export");_fsInternals.mkdirSync(exportDir,{recursive:!0});let jsonPath=path311.join(exportDir,"SWARM_PLAN.json"),mdPath=path311.join(exportDir,"SWARM_PLAN.md");_fsInternals.writeFileSync(jsonPath,JSON.stringify(plan,null,2));let md=derivePlanMarkdown(plan),header=`<!--
|
|
7408
7416
|
AUTO-GENERATED EXPORT/CHECKPOINT SNAPSHOT — DO NOT EDIT
|
|
7409
7417
|
This file is NOT the live plan. It is a derived export artifact.
|
|
@@ -7536,4 +7544,4 @@ ${footerLines.join(`
|
|
|
7536
7544
|
`);if(system.push(banner),output.system=system,sessionID)recordProducerEmission(sessionID,"swarm-command-banner",estimateTokens(banner),0,"system")}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;let timer=setTimeout(()=>{for(let task2 of tasks)try{Promise.resolve(task2()).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)}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)=>{let postResolutionTasks=[];try{let hooks2=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),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=createHash101("sha256").update(`delegation-cost-parent-v1\x00${parentSessionId}`).digest("hex").slice(0,32),childSessionDigest=createHash101("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:0,tokens_output:typeof effective.tokens_output==="number"?effective.tokens_output:0,tokens_reasoning:typeof effective.tokens_reasoning==="number"?effective.tokens_reasoning:0,tokens_cache:typeof effective.tokens_cache==="number"?effective.tokens_cache:0,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)}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){console.warn(`[opencode-swarm] running v${package_default.version}`),clearDeferredWarnings(),resetConfigAdvisoryDedup();let __initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(ctx.directory),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=hasSwarmState(ctx.directory)?withTimeout(loadSnapshotForInit(ctx.directory),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=hasGitMarkerAncestor(ctx.directory)?withTimeout(ensureSwarmGitExcludedForInit(ctx.directory),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(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)}}swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:ctx.directory,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}}),registerObservabilityEventSink(ctx.directory),initTelemetry(ctx.directory),startHeartbeatTracking();let otlpExportConfig=config3.observability?.export;if(otlpExportConfig!==void 0){if(registerOtlpExporter(ctx.directory,otlpExportConfig),isOtlpExporterActive())postResolutionTasks.push(()=>{flushOtlpExporterForTesting(ctx.directory).catch(()=>{})})}let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled?repoGraphHookFactory(ctx.directory,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(){return startSnapshotCoordinationInitialization(ctx.directory)}),postResolutionTasks.push(()=>{runModelPreflight(config3,swarmState.opencodeClient).then((result)=>{if(!result.catalogAvailable)return;let unresolved=result.resolutions.filter((resolution)=>resolution.status==="unresolved");if(unresolved.length===0)return;let lines=unresolved.map((resolution)=>` ${resolution.agent}: ${resolution.model} (${resolution.detail??"does not resolve"})`),msg=`[opencode-swarm] WARNING: ${unresolved.length} configured agent model(s) do not resolve against the provider catalog:
|
|
7537
7545
|
${lines.join(`
|
|
7538
7546
|
`)}
|
|
7539
|
-
Dispatching these agents will fail permanently ("Model not found"/"Forbidden"). Fix agents.<role>.model in opencode-swarm.json (or remove the override to fall back to the default).`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of unresolved)telemetry.modelUnresolved(resolution.agent,resolution.model,resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),postResolutionTasks.push(function(){return withTimeout(cleanupOldTrajectoryFiles(ctx.directory),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(){let retentionConfig=config3?.retention,retentionDaysValue=config3?.summaries?.retention_days,sweepCancelled=!1;return withTimeout(runRetentionSweep(ctx.directory,{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(){return withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(ctx.directory,{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(writeSwarmConfigExampleIfNew(ctx.directory),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,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??{})}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,ctx.directory,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,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key2 of["message","reason","code","status","statusCode","error","cause","detail","details"])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:ctx.directory}});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(ctx.directory,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:createHash101("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,ctx.directory),finalContextAccountingStep=createFinalContextAccountingStep({config:config3,directory:ctx.directory,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),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,config:config3,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmConfig=config3.prm??PrmConfigSchema.parse({}),prmHook=createPrmHook(prmConfig,ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:prmConfig.max_trajectory_lines},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory,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:ctx.directory,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(ctx.directory,{lockTimeoutMs:2000,reason:"session-close",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})},delegationSanitizerHook=createDelegationSanitizerHook(ctx.directory),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:ctx.directory,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(regenerateMemoryReflectionForInit(ctx.directory,reflectionConfig),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),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,worktreeBaseDirOverrides=worktreeDirOverride?[worktreeDirOverride]:[],guardrailsHooks=createGuardrailsHooks(ctx.directory,void 0,guardrailsConfig,authorityConfig,worktreeBaseDirOverrides,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,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),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:ctx.directory,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(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(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"]},ctx.directory,(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},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path358.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}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(ctx.directory,ensurePrMonitorWorkerRunning);let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,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));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).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(),removePrMonitorWorkerHandler(ctx.directory,ensurePrMonitorWorkerRunning),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery(),markSnapshotCoordinationClosing(ctx.directory);try{if(closeGroupCommitWriter(ctx.directory),getSnapshotCoordinationStatus(ctx.directory).settled)closeProjectDb(ctx.directory)}catch{}},instanceExitCleanupToken=`${ctx.directory}#${++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(ctx.directory,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)})})})})}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 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()},messagesTransformKnowledgeApplicationScanStep=(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},messagesTransformSkillPropagationScanStep=(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,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()},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(ctx.directory)}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(ctx.directory);try{await closeSnapshotCoordinationInitialization(ctx.directory),closeGroupCommitWriter(ctx.directory),closeProjectDb(ctx.directory)}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,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,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"&&partTool==="task"&&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(ctx.directory,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")deleteSnapshotSessionRows(ctx.directory,sessionID),clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID);if(backgroundSubagentsEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}try{let{recoverTerminalLaneReceipts:recoverTerminalLaneReceipts2}=await Promise.resolve().then(() => (init_delegation_lifecycle(),exports_delegation_lifecycle));await recoverTerminalLaneReceipts2(ctx.directory)}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)}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-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-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"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 (human-only escape hatch)"},"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":composeHandlers(...[messagesTransformDelegationLedgerStep,pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,messagesTransformKnowledgeApplicationScanStep,messagesTransformSkillPropagationScanStep,messagesTransformSystemGuidanceMaterializeStep,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(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":async(input,output)=>{let{sessionID}=input??{};if(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)}}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:ctx.directory,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(ctx.directory,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(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{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);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{},skillAttributionPlanTaskOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(ctx.directory));if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet,...skillAttributionPlanTaskOptions}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{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);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:ctx.directory,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:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),(normalizeToolName(input.tool)??input.tool)==="Task"&&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})}resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs);{let beforeToolNormalized=normalizeToolName(input.tool)??input.tool;if(beforeToolNormalized==="Task"||beforeToolNormalized==="task"){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,ctx.directory,{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(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}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 normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(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(ctx.directory,{sessionID:pushAttemptSessionID,callID:input.callID,tool:input.tool},pushCommand,output)}}catch{}if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,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(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"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(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{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:ctx.directory,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(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),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:ctx.directory})}}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=createHash101("sha256").update(`delegation-cost-id-v1\x00${recordMaterial}`).digest("hex").slice(0,32),costFields.identity_fingerprint=createHash101("sha256").update(`delegation-cost-identity-v1\x00${recordMaterial}\x00${agentName}\x00${configuredModel}`).digest("hex").slice(0,32),costFields.version=1,costFields.parent_session_digest=createHash101("sha256").update(`delegation-cost-parent-v1\x00${sessionId}`).digest("hex").slice(0,32),childSessionID)costFields.child_session_digest=createHash101("sha256").update(`delegation-cost-child-v1\x00${childSessionID}`).digest("hex").slice(0,32);swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);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=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);try{if(input2?.sessionID&&typeof input2?.agent==="string"&&input2.agent.trim()!=="")maybeEmitNonArchitectAdvisory(String(input2.sessionID),String(input2.agent))}catch{}if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,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,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};
|
|
7547
|
+
Dispatching these agents will fail permanently ("Model not found"/"Forbidden"). Fix agents.<role>.model in opencode-swarm.json (or remove the override to fall back to the default).`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of unresolved)telemetry.modelUnresolved(resolution.agent,resolution.model,resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),postResolutionTasks.push(function(){return withTimeout(cleanupOldTrajectoryFiles(ctx.directory),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(){let retentionConfig=config3?.retention,retentionDaysValue=config3?.summaries?.retention_days,sweepCancelled=!1;return withTimeout(runRetentionSweep(ctx.directory,{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(){return withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(ctx.directory,{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(writeSwarmConfigExampleIfNew(ctx.directory),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,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??{})}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,ctx.directory,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,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key2 of["message","reason","code","status","statusCode","error","cause","detail","details","data","name"])parts.push(...extractBoundedErrorSignal(record3[key2],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:ctx.directory}});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(ctx.directory,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:createHash101("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,ctx.directory),finalContextAccountingStep=createFinalContextAccountingStep({config:config3,directory:ctx.directory,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),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,config:config3,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmConfig=config3.prm??PrmConfigSchema.parse({}),prmHook=createPrmHook(prmConfig,ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:prmConfig.max_trajectory_lines},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory,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:ctx.directory,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(ctx.directory,{lockTimeoutMs:2000,reason:"session-close",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})},delegationSanitizerHook=createDelegationSanitizerHook(ctx.directory),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:ctx.directory,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(regenerateMemoryReflectionForInit(ctx.directory,reflectionConfig),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),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,worktreeBaseDirOverrides=worktreeDirOverride?[worktreeDirOverride]:[],guardrailsHooks=createGuardrailsHooks(ctx.directory,void 0,guardrailsConfig,authorityConfig,worktreeBaseDirOverrides,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,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),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:ctx.directory,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(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(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"]},ctx.directory,(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},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path358.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}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(ctx.directory,ensurePrMonitorWorkerRunning);let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,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));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).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(),removePrMonitorWorkerHandler(ctx.directory,ensurePrMonitorWorkerRunning),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery(),markSnapshotCoordinationClosing(ctx.directory);try{if(closeGroupCommitWriter(ctx.directory),getSnapshotCoordinationStatus(ctx.directory).settled)closeProjectDb(ctx.directory)}catch{}},instanceExitCleanupToken=`${ctx.directory}#${++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(ctx.directory,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)})})})})}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 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()},messagesTransformKnowledgeApplicationScanStep=(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},messagesTransformSkillPropagationScanStep=(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,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()},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(ctx.directory)}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(ctx.directory);try{await closeSnapshotCoordinationInitialization(ctx.directory),closeGroupCommitWriter(ctx.directory),closeProjectDb(ctx.directory)}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(ctx.directory,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")deleteSnapshotSessionRows(ctx.directory,sessionID),clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID);if(backgroundSubagentsEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}try{let{recoverTerminalLaneReceipts:recoverTerminalLaneReceipts2}=await Promise.resolve().then(() => (init_delegation_lifecycle(),exports_delegation_lifecycle));await recoverTerminalLaneReceipts2(ctx.directory)}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)}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-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-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"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 (human-only escape hatch)"},"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":composeHandlers(...[messagesTransformDelegationLedgerStep,pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,messagesTransformKnowledgeApplicationScanStep,messagesTransformSkillPropagationScanStep,messagesTransformSystemGuidanceMaterializeStep,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(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":async(input,output)=>{let{sessionID}=input??{};if(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)}}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:ctx.directory,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(ctx.directory,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(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{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);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{},skillAttributionPlanTaskOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(ctx.directory));if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet,...skillAttributionPlanTaskOptions}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{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);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:ctx.directory,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:ctx.directory,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,ctx.directory,{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)}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(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(ctx.directory,{sessionID:pushAttemptSessionID,callID:input.callID,tool:input.tool},pushCommand,output)}}catch{}if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,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(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"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(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{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:ctx.directory,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(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),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:ctx.directory})}}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=createHash101("sha256").update(`delegation-cost-id-v1\x00${recordMaterial}`).digest("hex").slice(0,32),costFields.identity_fingerprint=createHash101("sha256").update(`delegation-cost-identity-v1\x00${recordMaterial}\x00${agentName}\x00${configuredModel}`).digest("hex").slice(0,32),costFields.version=1,costFields.parent_session_digest=createHash101("sha256").update(`delegation-cost-parent-v1\x00${sessionId}`).digest("hex").slice(0,32),childSessionID)costFields.child_session_digest=createHash101("sha256").update(`delegation-cost-child-v1\x00${childSessionID}`).digest("hex").slice(0,32);swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);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=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);try{if(input2?.sessionID&&typeof input2?.agent==="string"&&input2.agent.trim()!=="")maybeEmitNonArchitectAdvisory(String(input2.sessionID),String(input2.agent))}catch{}if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,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,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};
|