opencode-swarm 7.200.10 → 7.200.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{attest-task-yx2t832n.js → attest-task-y0n69zgb.js} +26 -26
- package/dist/cli/{auto-checkpoint-15mvj9zm.js → auto-checkpoint-hyaksmtg.js} +4 -4
- package/dist/cli/{checkpoint-65whgvwa.js → checkpoint-t0p781sc.js} +8 -8
- package/dist/cli/{coder-settlement-sdg1he8p.js → coder-settlement-nh88s6es.js} +4 -4
- package/dist/cli/{config-doctor-4af2p2y4.js → config-doctor-sf7hc0q4.js} +7 -7
- package/dist/cli/{core-8swqc6kw.js → core-p168fw3r.js} +1 -1
- package/dist/cli/{curator-6ze04fz3.js → curator-5ayzhk7v.js} +26 -26
- package/dist/cli/{curator-drift-ktf137da.js → curator-drift-jx9kyndc.js} +5 -5
- package/dist/cli/{curator-llm-factory-7vq4rgg7.js → curator-llm-factory-ytfkvtxs.js} +26 -26
- package/dist/cli/{doctor-knowledge-receipt-phase-id-0smwq3ar.js → doctor-knowledge-receipt-phase-id-2gjvxndy.js} +4 -4
- package/dist/cli/{evidence-summary-service-3bhq2gef.js → evidence-summary-service-972sqht5.js} +10 -10
- package/dist/cli/{gate-evidence-gcv0xgfc.js → gate-evidence-n1m842gj.js} +3 -3
- package/dist/cli/{guardrail-explain-9t3mvm92.js → guardrail-explain-6yv78gmk.js} +27 -27
- package/dist/cli/{guardrail-log-ehgpan5n.js → guardrail-log-z5pzgkcv.js} +3 -3
- package/dist/cli/{guardrail-reset-q7m265wy.js → guardrail-reset-w0nxcs6a.js} +26 -26
- package/dist/cli/{hive-promoter-857ranjf.js → hive-promoter-3q0738xg.js} +26 -26
- package/dist/cli/{index-66b4f2qd.js → index-0an54fza.js} +3 -3
- package/dist/cli/{index-mamw83wm.js → index-0g0x9ets.js} +26 -26
- package/dist/cli/{index-vm3j8fvn.js → index-2n7a184b.js} +2 -2
- package/dist/cli/{index-8c6zshfj.js → index-2vj8d8te.js} +1 -1
- package/dist/cli/{index-fbn2mv67.js → index-5k88v1e7.js} +76 -31
- package/dist/cli/{index-06sj5bjh.js → index-814q5t5s.js} +1 -1
- package/dist/cli/{index-vqknke9n.js → index-8g9rn3rp.js} +5 -5
- package/dist/cli/{index-60m7qnds.js → index-aj41bscz.js} +3 -3
- package/dist/cli/{index-ev46f132.js → index-bnbhqvsn.js} +1 -1
- package/dist/cli/{index-rnm6c33a.js → index-bv9tqmpm.js} +1 -1
- package/dist/cli/{index-4dvqvn4k.js → index-ce6qarfq.js} +179 -75
- package/dist/cli/{index-ffm3d4cn.js → index-gkvk9et2.js} +3 -3
- package/dist/cli/{index-tm6nwe43.js → index-h1chaf63.js} +5 -5
- package/dist/cli/{index-r3wyt8za.js → index-hhzwfyd7.js} +1 -1
- package/dist/cli/{index-bt3pxs7r.js → index-jt9j02tm.js} +1 -1
- package/dist/cli/{index-6ehx0pj4.js → index-ke881z7m.js} +2 -2
- package/dist/cli/{index-3h5ztpn5.js → index-krjamprc.js} +2 -2
- package/dist/cli/{index-gsnj3a0h.js → index-kzr3nby8.js} +2 -2
- package/dist/cli/{index-ww5ne0g6.js → index-mq4eyhtf.js} +1 -1
- package/dist/cli/{index-c34tgnwm.js → index-njg8zvqe.js} +3 -3
- package/dist/cli/{index-2dey2mtg.js → index-nnc23ddw.js} +3 -3
- package/dist/cli/{index-43zgg04r.js → index-nzhfhpng.js} +1 -1
- package/dist/cli/{index-vajbtn3v.js → index-qdz6zysj.js} +4 -4
- package/dist/cli/{index-xkavxqf2.js → index-r097ettz.js} +1 -1
- package/dist/cli/{index-6e7jxxys.js → index-ra3erqpk.js} +2 -2
- package/dist/cli/{index-mx34b7bm.js → index-ssp4t8g6.js} +28 -28
- package/dist/cli/{index-h9qhy8r6.js → index-ve74c3a8.js} +6 -6
- package/dist/cli/{index-ywwazz81.js → index-x8sh8v4a.js} +1 -1
- package/dist/cli/{index-zmp1k0mb.js → index-xht6gprr.js} +35 -22
- package/dist/cli/{index-kxxy7zq4.js → index-yn6jrxen.js} +3 -3
- package/dist/cli/{index-nv8tx9v4.js → index-yq73sd3w.js} +1 -1
- package/dist/cli/index.js +27 -27
- package/dist/cli/{knowledge-escalator-6p7m6gkc.js → knowledge-escalator-2e92rdsx.js} +7 -7
- package/dist/cli/{knowledge-events-w3ep12sq.js → knowledge-events-gzqwr94e.js} +5 -5
- package/dist/cli/{knowledge-store-g4cpw0hz.js → knowledge-store-6j8d1gm4.js} +1 -1
- package/dist/cli/{knowledge-validator-zhy6mgxv.js → knowledge-validator-wt2tcfg7.js} +2 -2
- package/dist/cli/{mcp-j1dy60mx.js → mcp-ky6xn6ys.js} +1 -1
- package/dist/cli/{model-preflight-962y2z1d.js → model-preflight-ajt55s59.js} +26 -26
- package/dist/cli/{pending-delegations-erjwa1y6.js → pending-delegations-wry31649.js} +2 -2
- package/dist/cli/{pr-subscriptions-7fcawjg9.js → pr-subscriptions-dsdjbfr4.js} +1 -1
- package/dist/cli/{pr-workflow-gate-j8ee9c6g.js → pr-workflow-gate-0vcq1m95.js} +26 -26
- package/dist/cli/{scan-cursor-msz8j44s.js → scan-cursor-1zgrg7kp.js} +2 -2
- package/dist/cli/{schema-kep9t01t.js → schema-q9xbwkec.js} +1 -1
- package/dist/cli/{scope-persistence-tx71g0ac.js → scope-persistence-4wwmytwh.js} +5 -5
- package/dist/cli/{server-6enk6sfw.js → server-q8ydxk7z.js} +35 -26
- package/dist/cli/{skill-generator-p9fkx1g3.js → skill-generator-b1eqcxej.js} +8 -8
- package/dist/cli/{snapshot-coordination-init-kgftbdmq.js → snapshot-coordination-init-0yva5015.js} +26 -26
- package/dist/cli/{speckit-checkoff-jfdwsy5n.js → speckit-checkoff-sh9w7j5b.js} +3 -3
- package/dist/cli/{workflow-wal-file-xvvwcxr1.js → workflow-wal-file-a2c8e920.js} +2 -2
- package/dist/cli/{worktree-collision-ownership-hac3t2xv.js → worktree-collision-ownership-xr6crt8c.js} +2 -2
- package/dist/cli/{worktree-isolation-tjvxcsr9.js → worktree-isolation-0126b5e7.js} +26 -26
- package/dist/hooks/delegation-gate.d.ts +6 -0
- package/dist/hooks/guardrails/audit-log.d.ts +2 -0
- package/dist/hooks/guardrails/cmd-delete-grammar.d.ts +47 -0
- package/dist/hooks/guardrails/destructive-command.d.ts +11 -3
- package/dist/hooks/guardrails/shell-audit-store.d.ts +2 -0
- package/dist/hooks/guardrails/tool-before.d.ts +16 -0
- package/dist/index.js +17 -17
- 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.200.10",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run; reviewer verdicts marked `UNVERIFIED` persist to the findings ledger as `PENDING` records routed back to the reviewer — do not resubmit a row whose verdict is already recorded",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",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"]},prepare_pr_feedback_commit_message:{description:"author a PR_FEEDBACK commit message that cannot go inline (e.g. a Co-Authored-By trailer) into a file OUTSIDE the repository; returns the path for git commit -F",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},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,EPIC_TOOL_NAMES,EPIC_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.200.11",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run; reviewer verdicts marked `UNVERIFIED` persist to the findings ledger as `PENDING` records routed back to the reviewer — do not resubmit a row whose verdict is already recorded",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",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"]},prepare_pr_feedback_commit_message:{description:"author a PR_FEEDBACK commit message that cannot go inline (e.g. a Co-Authored-By trailer) into a file OUTSIDE the repository; returns the path for git commit -F",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},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,EPIC_TOOL_NAMES,EPIC_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
|
|
|
@@ -746,11 +746,11 @@ in`);return tk},In(tk,iterable){if((iterable.behind(1)||tokens.mkToken("EMPTY"))
|
|
|
746
746
|
`)}};module.exports=()=>compose(filterNonNull,map2(tokens.applyTokenizerVisitor(SkipRepeatedNewLines)),lookahead)});var require_assignment_word=__commonJS((exports,module)=>{var map2=require_map_iterable(),isValidName=require_is_valid_name();module.exports=function(){return map2((tk,idx,ctx)=>{if(tk._.maybeStartOfSimpleCommand)ctx.commandPrefixNotAllowed=!1;if(!ctx.commandPrefixNotAllowed&&tk.is("WORD")&&tk.value.indexOf("=")>0&&isValidName(tk.value.slice(0,tk.value.indexOf("="))))return tk.changeTokenType("ASSIGNMENT_WORD",tk.value);return ctx.commandPrefixNotAllowed=!0,tk})}});var require_syntaxerror_oncontinue=__commonJS((exports,module)=>{var map2=require_map_iterable();module.exports=function(){return map2((tk)=>{if(tk&&tk.is("CONTINUE"))throw SyntaxError("Unclosed "+tk.value);return tk})}});var require_rules=__commonJS((exports)=>{exports.parameterExpansion=require_parameter_expansion();exports.commandExpansion=require_command_expansion();exports.arithmeticExpansion=require_arithmetic_expansion();exports.aliasSubstitution=require_alias_substitution2();exports.defaultNodeType=require_default_node_type();exports.fieldSplitting=require_field_splitting();exports.tildeExpanding=require_tilde_expanding();exports.pathExpansion=require_path_expansion();exports.quoteRemoval=require_quote_removal();exports.identifySimpleCommandNames=require_identify_simplecommand_names();exports.identifyMaybeSimpleCommands=require_identify_maybe_simple_commands();exports.operatorTokens=require_operator_tokens();exports.reservedWords=require_reserved_words();exports.separator=require_separator();exports.linebreakIn=require_linebreak_in();exports.forNameVariable=require_for_name_variable();exports.functionName=require_function_name();exports.ioNumber=require_io_number();exports.newLineList=require_new_line_list();exports.assignmentWord=require_assignment_word();exports.syntaxerrorOnContinue=require_syntaxerror_oncontinue()});var require_grammar=__commonJS((exports,module)=>{module.exports={start:"complete_command",bnf:{complete_command:[["list separator EOF"," return yy.checkAsync($list, $separator)"],["list EOF"," return $list "],["separator list EOF"," return $list "],["separator list separator EOF"," return yy.checkAsync($list, $separator)"]],list:[["list separator and_or","$$ = yy.listAppend($list, $and_or, $separator);"],["and_or","$$ = yy.list($and_or);"]],and_or:[["pipeline","$$ = $pipeline;"],["and_or AND_IF linebreak pipeline","$$ = yy.andAndOr($and_or, $pipeline);"],["and_or OR_IF linebreak pipeline","$$ = yy.orAndOr($and_or, $pipeline);"]],pipeline:[["pipe_sequence","$$ = yy.pipeLine($pipe_sequence);"],["Bang pipe_sequence","$$ = yy.bangPipeLine($pipe_sequence);"]],pipe_sequence:[["command","$$ = yy.pipeSequence($command);"],["pipe_sequence PIPE linebreak command","$$ = yy.pipeSequenceAppend($pipe_sequence, $command);"]],command:["simple_command","compound_command",["compound_command redirect_list","$$ = yy.addRedirections($compound_command, $redirect_list)"],"function_definition"],compound_command:["brace_group","subshell","for_clause","case_clause","if_clause","while_clause","until_clause"],subshell:[["OPEN_PAREN compound_list CLOSE_PAREN","$$ = yy.subshell($compound_list, $OPEN_PAREN.loc, $CLOSE_PAREN.loc);"]],compound_list:[["term","$$ = $term;"],["NEWLINE_LIST term","$$ = $term;"],["term separator","$$ = yy.checkAsync($term, $separator);"],["NEWLINE_LIST term separator","$$ = yy.checkAsync($term, $separator);"]],term:[["term separator and_or","$$ = yy.termAppend($term, $and_or, $separator);"],["and_or","$$ = yy.term($and_or);"]],for_clause:[["For name linebreak do_group","$$ = yy.forClauseDefault($name, $do_group, $For.loc);"],["For name LINEBREAK_IN separator do_group","$$ = yy.forClauseDefault($name, $do_group, $For.loc);"],["For name In separator do_group","$$ = yy.forClauseDefault($name, $do_group, $For.loc);"],["For name in wordlist separator do_group","$$ = yy.forClause($name, $wordlist, $do_group, $For.loc);"]],name:["NAME"],in:["In"],wordlist:["wordlist_repetition_plus0"],case_clause:[["Case WORD linebreak in linebreak case_list Esac","$$ = yy.caseClause($WORD, $case_list, $Case.loc, $Esac.loc);"],["Case WORD linebreak in linebreak case_list_ns Esac","$$ = yy.caseClause($WORD, $case_list_ns, $Case.loc, $Esac.loc);"],["Case WORD linebreak in linebreak Esac","$$ = yy.caseClause($WORD, null, $Case.loc, $Esac.loc);"]],case_list_ns:[["case_list case_item_ns","$$ = yy.caseListAppend($case_list, $case_item_ns);"],["case_item_ns","$$ = yy.caseList($case_item_ns);"]],case_list:[["case_list case_item","$$ = yy.caseListAppend($case_list, $case_item);"],["case_item","$$ = yy.caseList($case_item);"]],case_item_ns:[["pattern CLOSE_PAREN linebreak","$$ = yy.caseItem($pattern, null, $pattern[0].loc, $CLOSE_PAREN.loc);"],["pattern CLOSE_PAREN compound_list linebreak","$$ = yy.caseItem($pattern, $compound_list, $pattern[0].loc, $compound_list.loc);"],["OPEN_PAREN pattern CLOSE_PAREN linebreak","$$ = yy.caseItem($pattern, null, $OPEN_PAREN.loc, $CLOSE_PAREN.loc );"],["OPEN_PAREN pattern CLOSE_PAREN compound_list linebreak","$$ = yy.caseItem($pattern, $compound_list, $OPEN_PAREN.loc, $compound_list.loc);"]],case_item:[["pattern CLOSE_PAREN linebreak DSEMI linebreak","$$ = yy.caseItem($pattern, null, $pattern[0].loc, $DSEMI.loc);"],["pattern CLOSE_PAREN compound_list DSEMI linebreak","$$ = yy.caseItem($pattern, $compound_list, $pattern[0].loc, $DSEMI.loc);"],["OPEN_PAREN pattern CLOSE_PAREN linebreak DSEMI linebreak","$$ = yy.caseItem($pattern, null, $OPEN_PAREN.loc, $DSEMI.loc );"],["OPEN_PAREN pattern CLOSE_PAREN compound_list DSEMI linebreak","$$ = yy.caseItem($pattern, $compound_list, $OPEN_PAREN.loc, $DSEMI.loc);"]],pattern:[["WORD","$$ = yy.pattern($WORD);"],["pattern PIPE WORD","$$ = yy.patternAppend($pattern, $WORD);"]],if_clause:[["If compound_list Then compound_list else_part Fi","$$ = yy.ifClause($2, $4, $else_part, $If.loc, $Fi.loc);"],["If compound_list Then compound_list Fi","$$ = yy.ifClause($2, $4, null, $If.loc, $Fi.loc);"]],else_part:[["Elif compound_list Then compound_list","$$ = yy.ifClause($2, $4, null, $Elif.loc, $4.loc);"],["Elif compound_list Then compound_list else_part","$$ = yy.ifClause($2, $4, $else_part, $Elif.loc, $else_part.loc);"],["Else compound_list","$$ = yy.elseClause($compound_list, $Else);"]],while_clause:[["While compound_list do_group","$$ = yy.while($2, $3, $While);"]],until_clause:[["Until compound_list do_group","$$ = yy.until($2, $3, $Until);"]],function_definition:[["fname OPEN_PAREN CLOSE_PAREN linebreak function_body","$$ = yy.functionDefinition($fname, $function_body);"]],function_body:[["compound_command","$$ = [$compound_command, null];"],["compound_command redirect_list","$$ = [$compound_command, $redirect_list];"]],fname:["NAME"],brace_group:[["Lbrace compound_list Rbrace","$$ = yy.braceGroup($compound_list, $Lbrace.loc, $Rbrace.loc);"]],do_group:[["Do compound_list Done","$$ = yy.doGroup($compound_list, $Do.loc, $Done.loc);"]],simple_command:[["cmd_prefix cmd_word cmd_suffix","$$ =yy.command($cmd_prefix, $cmd_word, $cmd_suffix);"],["cmd_prefix cmd_word","$$ =yy.command($cmd_prefix, $cmd_word, null);"],["cmd_prefix","$$ =yy.commandAssignment($cmd_prefix);"],["cmd_name cmd_suffix","$$ =yy.command(null, $cmd_name, $cmd_suffix);"],["cmd_name","$$ =yy.command(null, $cmd_name);"]],cmd_name:[["WORD","$$ =yy.commandName(yytext) /* Apply rule 7a */;"]],cmd_word:[["WORD","$$ = yytext\t/* Apply rule 7B */;"]],cmd_prefix:[["io_redirect","$$ = yy.prefix($io_redirect);"],["cmd_prefix io_redirect","$$ = yy.prefixAppend($1, $2);"],["ASSIGNMENT_WORD","$$ = yy.prefix($1);"],["cmd_prefix ASSIGNMENT_WORD","$$ = yy.prefixAppend($1, $2);"]],cmd_suffix:[["io_redirect","$$ = yy.suffix($io_redirect);"],["cmd_suffix io_redirect","$$ = yy.suffixAppend($cmd_suffix, $io_redirect);"],["WORD","$$ = yy.suffix($1);"],["cmd_suffix WORD","$$ = yy.suffixAppend($cmd_suffix, $2);"]],redirect_list:[["io_redirect","$$ = [$io_redirect];"],["redirect_list io_redirect","$$ = $redirect_list.concat($io_redirect);"]],io_redirect:[["io_file","$$ = $io_file;"],["IO_NUMBER io_file","$$ = yy.numberIoRedirect($io_file, $1);"],"io_here","IO_NUMBER io_here"],io_file:[["LESS filename","$$ =yy.ioRedirect($1, $filename);"],["LESSAND filename","$$ =yy.ioRedirect($1, $filename);"],["GREAT filename","$$ =yy.ioRedirect($1, $filename);"],["GREATAND filename","$$ =yy.ioRedirect($1, $filename);"],["DGREAT filename","$$ =yy.ioRedirect($1, $filename);"],["LESSGREAT filename","$$ =yy.ioRedirect($1, $filename);"],["CLOBBER filename","$$ =yy.ioRedirect($1, $filename);"]],filename:["WORD"],io_here:["DLESS here_end","DLESSDASH here_end"],here_end:["WORD"],linebreak:["NEWLINE_LIST",""],separator:["SEPARATOR_OP","NEWLINE_LIST"],wordlist_repetition_plus0:[["WORD","$$ = [$1];"],["wordlist_repetition_plus0 WORD","$1.push($2);"]]}}});var require_io_file_operators=__commonJS((exports,module)=>{var ioFileOperators=module.exports=["LESS","DLESS","DGREAT","LESSAND","GREATAND","GREAT","LESSGREAT","CLOBBER"];ioFileOperators.isOperator=function(tk){for(let op of ioFileOperators)if(tk.type===op)return!0;return!1}});var require_parameter_operators=__commonJS((exports,module)=>{var parameterOps={["^([a-zA-Z_][a-zA-Z0-9_]*):\\-(.*)$"]:{op:"useDefaultValue",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*):\\=(.*)$"]:{op:"assignDefaultValue",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*):\\?(.*)$"]:{op:"indicateErrorIfNull",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*):\\+(.*)$"]:{op:"useAlternativeValue",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\-(.*)$"]:{op:"useDefaultValueIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\=(.*)$"]:{op:"assignDefaultValueIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\?(.*)$"]:{op:"indicateErrorIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\+(.*)$"]:{op:"useAlternativeValueIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\%\\%(.*)$"]:{op:"removeLargestSuffixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\#\\#(.*)$"]:{op:"removeLargestPrefixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\%(.*)$"]:{op:"removeSmallestSuffixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\#(.*)$"]:{op:"removeSmallestPrefixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^\\#([a-zA-Z_][a-zA-Z0-9_]*)$"]:{op:"stringLength",parameter:(m)=>m[1]},["^([1-9][0-9]*)$"]:{kind:"positional",parameter:(m)=>Number(m[1])},"^!$":{kind:"last-background-pid"},"^\\@$":{kind:"positional-list"},"^\\-$":{kind:"current-option-flags"},"^\\#$":{kind:"positional-count"},"^\\?$":{kind:"last-exit-status"},"^\\*$":{kind:"positional-string"},"^\\$$":{kind:"shell-process-id"},"^0$":{kind:"shell-script-name"}};module.exports=parameterOps});var require_reserved_words2=__commonJS((exports,module)=>{module.exports={if:"If",then:"Then",else:"Else",elif:"Elif",fi:"Fi",do:"Do",done:"Done",case:"Case",esac:"Esac",while:"While",until:"Until",for:"For",in:"In","{":"Lbrace","}":"Rbrace","!":"Bang"}});var require_enums=__commonJS((exports)=>{exports.IOFileOperators=require_io_file_operators();exports.operators=require_operators();exports.parameterOperators=require_parameter_operators();exports.reservedWords=require_reserved_words2()});var require_built_grammar=__commonJS((exports,module)=>{var parser=function(){var o=function(k,v,o2,l){for(o2=o2||{},l=k.length;l--;o2[k[l]]=v);return o2},$V0=[1,9],$V1=[1,28],$V2=[1,6],$V3=[1,29],$V4=[1,34],$V5=[1,30],$V6=[1,26],$V7=[1,31],$V8=[1,32],$V9=[1,33],$Va=[1,27],$Vb=[1,25],$Vc=[1,36],$Vd=[1,38],$Ve=[1,39],$Vf=[1,40],$Vg=[1,41],$Vh=[1,42],$Vi=[1,43],$Vj=[1,44],$Vk=[1,45],$Vl=[1,46],$Vm=[1,5],$Vn=[6,31,84],$Vo=[1,50],$Vp=[1,51],$Vq=[6,13,27,29,31,32,39,41,42,44,49,50,51,53,54,55,56,57,60,61,62,63,69,71,73,75,76,77,78,79,80,81,83],$Vr=[6,9,11,29,31,44,49,51,53,54,55,61,62,63,84],$Vs=[1,52],$Vt=[6,9,11,15,29,31,44,49,51,53,54,55,61,62,63,84],$Vu=[1,62],$Vv=[6,9,11,15,29,31,44,49,51,53,54,55,61,62,63,71,73,75,76,77,78,79,80,81,83,84],$Vw=[6,9,11,15,29,31,42,44,49,51,53,54,55,61,62,63,69,71,73,75,76,77,78,79,80,81,83,84],$Vx=[6,9,11,15,29,31,42,44,49,51,53,54,55,61,62,63,71,73,75,76,77,78,79,80,81,83,84],$Vy=[1,66],$Vz=[1,78],$VA=[1,86],$VB=[13,27,32,39,41,42,50,56,57,60,69,71,73,75,76,77,78,79,80,81,83],$VC=[2,102],$VD=[1,93],$VE=[1,99],$VF=[29,44,49,51,53,54,55,61,62,63],$VG=[29,31,44,49,51,53,54,55,61,62,63,84],$VH=[1,112],$VI=[2,101],$VJ=[29,31,44,49,51,53,54,55,61,62,63],$VK=[2,37],$VL=[31,42,84],$VM=[27,42,44],$VN=[1,140],$VO=[1,141],$VP=[1,151],$VQ=[1,152],$VR=[1,161],$VS=[15,29],$VT=[44,49],$VU=[1,166],parser2={trace:function(){},yy:{},symbols_:{error:2,complete_command:3,list:4,separator:5,EOF:6,and_or:7,pipeline:8,AND_IF:9,linebreak:10,OR_IF:11,pipe_sequence:12,Bang:13,command:14,PIPE:15,simple_command:16,compound_command:17,redirect_list:18,function_definition:19,brace_group:20,subshell:21,for_clause:22,case_clause:23,if_clause:24,while_clause:25,until_clause:26,OPEN_PAREN:27,compound_list:28,CLOSE_PAREN:29,term:30,NEWLINE_LIST:31,For:32,name:33,do_group:34,LINEBREAK_IN:35,In:36,in:37,wordlist:38,NAME:39,wordlist_repetition_plus0:40,Case:41,WORD:42,case_list:43,Esac:44,case_list_ns:45,case_item_ns:46,case_item:47,pattern:48,DSEMI:49,If:50,Then:51,else_part:52,Fi:53,Elif:54,Else:55,While:56,Until:57,fname:58,function_body:59,Lbrace:60,Rbrace:61,Do:62,Done:63,cmd_prefix:64,cmd_word:65,cmd_suffix:66,cmd_name:67,io_redirect:68,ASSIGNMENT_WORD:69,io_file:70,IO_NUMBER:71,io_here:72,LESS:73,filename:74,LESSAND:75,GREAT:76,GREATAND:77,DGREAT:78,LESSGREAT:79,CLOBBER:80,DLESS:81,here_end:82,DLESSDASH:83,SEPARATOR_OP:84,$accept:0,$end:1},terminals_:{2:"error",6:"EOF",9:"AND_IF",11:"OR_IF",13:"Bang",15:"PIPE",27:"OPEN_PAREN",29:"CLOSE_PAREN",31:"NEWLINE_LIST",32:"For",35:"LINEBREAK_IN",36:"In",39:"NAME",41:"Case",42:"WORD",44:"Esac",49:"DSEMI",50:"If",51:"Then",53:"Fi",54:"Elif",55:"Else",56:"While",57:"Until",60:"Lbrace",61:"Rbrace",62:"Do",63:"Done",69:"ASSIGNMENT_WORD",71:"IO_NUMBER",73:"LESS",75:"LESSAND",76:"GREAT",77:"GREATAND",78:"DGREAT",79:"LESSGREAT",80:"CLOBBER",81:"DLESS",83:"DLESSDASH",84:"SEPARATOR_OP"},productions_:[0,[3,3],[3,2],[3,3],[3,4],[4,3],[4,1],[7,1],[7,4],[7,4],[8,1],[8,2],[12,1],[12,4],[14,1],[14,1],[14,2],[14,1],[17,1],[17,1],[17,1],[17,1],[17,1],[17,1],[17,1],[21,3],[28,1],[28,2],[28,2],[28,3],[30,3],[30,1],[22,4],[22,5],[22,5],[22,6],[33,1],[37,1],[38,1],[23,7],[23,7],[23,6],[45,2],[45,1],[43,2],[43,1],[46,3],[46,4],[46,4],[46,5],[47,5],[47,5],[47,6],[47,6],[48,1],[48,3],[24,6],[24,5],[52,4],[52,5],[52,2],[25,3],[26,3],[19,5],[59,1],[59,2],[58,1],[20,3],[34,3],[16,3],[16,2],[16,1],[16,2],[16,1],[67,1],[65,1],[64,1],[64,2],[64,1],[64,2],[66,1],[66,2],[66,1],[66,2],[18,1],[18,2],[68,1],[68,2],[68,1],[68,2],[70,2],[70,2],[70,2],[70,2],[70,2],[70,2],[70,2],[74,1],[72,2],[72,2],[82,1],[10,1],[10,0],[5,1],[5,1],[40,1],[40,2]],performAction:function(yytext,yyleng,yylineno,yy,yystate,$$,_$){var $0=$$.length-1;switch(yystate){case 1:return yy.checkAsync($$[$0-2],$$[$0-1]);case 2:case 3:return $$[$0-1];case 4:return yy.checkAsync($$[$0-2],$$[$0-3]);case 5:this.$=yy.listAppend($$[$0-2],$$[$0],$$[$0-1]);break;case 6:this.$=yy.list($$[$0]);break;case 7:case 26:case 27:case 86:this.$=$$[$0];break;case 8:this.$=yy.andAndOr($$[$0-3],$$[$0]);break;case 9:this.$=yy.orAndOr($$[$0-3],$$[$0]);break;case 10:this.$=yy.pipeLine($$[$0]);break;case 11:this.$=yy.bangPipeLine($$[$0]);break;case 12:this.$=yy.pipeSequence($$[$0]);break;case 13:this.$=yy.pipeSequenceAppend($$[$0-3],$$[$0]);break;case 16:this.$=yy.addRedirections($$[$0-1],$$[$0]);break;case 25:this.$=yy.subshell($$[$0-1],$$[$0-2].loc,$$[$0].loc);break;case 28:case 29:this.$=yy.checkAsync($$[$0-1],$$[$0]);break;case 30:this.$=yy.termAppend($$[$0-2],$$[$0],$$[$0-1]);break;case 31:this.$=yy.term($$[$0]);break;case 32:this.$=yy.forClauseDefault($$[$0-2],$$[$0],$$[$0-3].loc);break;case 33:case 34:this.$=yy.forClauseDefault($$[$0-3],$$[$0],$$[$0-4].loc);break;case 35:this.$=yy.forClause($$[$0-4],$$[$0-2],$$[$0],$$[$0-5].loc);break;case 39:case 40:this.$=yy.caseClause($$[$0-5],$$[$0-1],$$[$0-6].loc,$$[$0].loc);break;case 41:this.$=yy.caseClause($$[$0-4],null,$$[$0-5].loc,$$[$0].loc);break;case 42:case 44:this.$=yy.caseListAppend($$[$0-1],$$[$0]);break;case 43:case 45:this.$=yy.caseList($$[$0]);break;case 46:this.$=yy.caseItem($$[$0-2],null,$$[$0-2][0].loc,$$[$0-1].loc);break;case 47:this.$=yy.caseItem($$[$0-3],$$[$0-1],$$[$0-3][0].loc,$$[$0-1].loc);break;case 48:this.$=yy.caseItem($$[$0-2],null,$$[$0-3].loc,$$[$0-1].loc);break;case 49:this.$=yy.caseItem($$[$0-3],$$[$0-1],$$[$0-4].loc,$$[$0-1].loc);break;case 50:this.$=yy.caseItem($$[$0-4],null,$$[$0-4][0].loc,$$[$0-1].loc);break;case 51:this.$=yy.caseItem($$[$0-4],$$[$0-2],$$[$0-4][0].loc,$$[$0-1].loc);break;case 52:this.$=yy.caseItem($$[$0-4],null,$$[$0-5].loc,$$[$0-1].loc);break;case 53:this.$=yy.caseItem($$[$0-4],$$[$0-2],$$[$0-5].loc,$$[$0-1].loc);break;case 54:this.$=yy.pattern($$[$0]);break;case 55:this.$=yy.patternAppend($$[$0-2],$$[$0]);break;case 56:this.$=yy.ifClause($$[$0-4],$$[$0-2],$$[$0-1],$$[$0-5].loc,$$[$0].loc);break;case 57:this.$=yy.ifClause($$[$0-3],$$[$0-1],null,$$[$0-4].loc,$$[$0].loc);break;case 58:this.$=yy.ifClause($$[$0-2],$$[$0],null,$$[$0-3].loc,$$[$0].loc);break;case 59:this.$=yy.ifClause($$[$0-3],$$[$0-1],$$[$0],$$[$0-4].loc,$$[$0].loc);break;case 60:this.$=yy.elseClause($$[$0],$$[$0-1]);break;case 61:this.$=yy.while($$[$0-1],$$[$0],$$[$0-2]);break;case 62:this.$=yy.until($$[$0-1],$$[$0],$$[$0-2]);break;case 63:this.$=yy.functionDefinition($$[$0-4],$$[$0]);break;case 64:this.$=[$$[$0],null];break;case 65:this.$=[$$[$0-1],$$[$0]];break;case 67:this.$=yy.braceGroup($$[$0-1],$$[$0-2].loc,$$[$0].loc);break;case 68:this.$=yy.doGroup($$[$0-1],$$[$0-2].loc,$$[$0].loc);break;case 69:this.$=yy.command($$[$0-2],$$[$0-1],$$[$0]);break;case 70:this.$=yy.command($$[$0-1],$$[$0],null);break;case 71:this.$=yy.commandAssignment($$[$0]);break;case 72:this.$=yy.command(null,$$[$0-1],$$[$0]);break;case 73:this.$=yy.command(null,$$[$0]);break;case 74:this.$=yy.commandName(yytext);break;case 75:this.$=yytext;break;case 76:case 78:this.$=yy.prefix($$[$0]);break;case 77:case 79:this.$=yy.prefixAppend($$[$0-1],$$[$0]);break;case 80:case 82:this.$=yy.suffix($$[$0]);break;case 81:case 83:this.$=yy.suffixAppend($$[$0-1],$$[$0]);break;case 84:case 105:this.$=[$$[$0]];break;case 85:this.$=$$[$0-1].concat($$[$0]);break;case 87:this.$=yy.numberIoRedirect($$[$0],$$[$0-1]);break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:this.$=yy.ioRedirect($$[$0-1],$$[$0]);break;case 106:$$[$0-1].push($$[$0]);break}},table:[{3:1,4:2,5:3,7:4,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,31:$V2,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl,84:$Vm},{1:[3]},{5:47,6:[1,48],31:$V2,84:$Vm},{4:49,7:4,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vn,[2,6],{9:$Vo,11:$Vp}),o($Vq,[2,103]),o($Vq,[2,104]),o($Vr,[2,7]),o($Vr,[2,10],{15:$Vs}),{12:53,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vt,[2,12]),o($Vt,[2,14]),o($Vt,[2,15],{70:35,72:37,18:54,68:55,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vt,[2,17]),o($Vt,[2,71],{70:35,72:37,65:56,68:57,42:[1,59],69:[1,58],71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vt,[2,73],{70:35,72:37,66:60,68:61,42:$Vu,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,18]),o($Vv,[2,19]),o($Vv,[2,20]),o($Vv,[2,21]),o($Vv,[2,22]),o($Vv,[2,23]),o($Vv,[2,24]),{27:[1,63]},o($Vw,[2,76]),o($Vw,[2,78]),o($Vx,[2,74]),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:64,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:68,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{33:69,39:[1,70]},{42:[1,71]},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:72,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:73,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:74,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{27:[2,66]},o($Vw,[2,86]),{70:75,72:76,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vw,[2,88]),{42:$Vz,74:77},{42:$Vz,74:79},{42:$Vz,74:80},{42:$Vz,74:81},{42:$Vz,74:82},{42:$Vz,74:83},{42:$Vz,74:84},{42:$VA,82:85},{42:$VA,82:87},{6:[1,88],7:89,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{1:[2,2]},{5:91,6:[1,90],31:$V2,84:$Vm},o($VB,$VC,{10:92,31:$VD}),o($VB,$VC,{10:94,31:$VD}),o([27,32,39,41,42,50,56,57,60,69,71,73,75,76,77,78,79,80,81,83],$VC,{10:95,31:$VD}),o($Vr,[2,11],{15:$Vs}),o($Vt,[2,16],{70:35,72:37,68:96,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,84]),o($Vt,[2,70],{70:35,72:37,68:61,66:97,42:$Vu,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vw,[2,77]),o($Vw,[2,79]),o($Vx,[2,75]),o($Vt,[2,72],{70:35,72:37,68:98,42:$VE,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vx,[2,80]),o($Vx,[2,82]),{29:[1,100]},{61:[1,101]},o($VF,[2,26],{5:102,31:$V2,84:$Vm}),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,30:103,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($VG,[2,31],{9:$Vo,11:$Vp}),{29:[1,104]},{10:105,31:$VD,35:[1,106],36:[1,107],37:108,62:$VC},o([31,35,36,62],[2,36]),{10:109,31:$VD,36:$VC},{51:[1,110]},{34:111,62:$VH},{34:113,62:$VH},o($Vw,[2,87]),o($Vw,[2,89]),o($Vw,[2,90]),o($Vw,[2,97]),o($Vw,[2,91]),o($Vw,[2,92]),o($Vw,[2,93]),o($Vw,[2,94]),o($Vw,[2,95]),o($Vw,[2,96]),o($Vw,[2,98]),o($Vw,[2,100]),o($Vw,[2,99]),{1:[2,1]},o($Vn,[2,5],{9:$Vo,11:$Vp}),{1:[2,3]},{6:[1,114],7:89,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{8:115,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o([13,27,32,36,39,41,42,44,50,56,57,60,62,69,71,73,75,76,77,78,79,80,81,83],$VI),{8:116,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{14:117,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,85]),o($Vt,[2,69],{70:35,72:37,68:98,42:$VE,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vx,[2,81]),o($Vx,[2,83]),o([27,32,41,50,56,57,60],$VC,{10:118,31:$VD}),o($Vv,[2,67]),o($VJ,[2,28],{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,7:119,13:$V0,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($VF,[2,27],{5:120,31:$V2,84:$Vm}),o($Vv,[2,25]),{34:121,62:$VH},{5:122,31:$V2,84:$Vm},{5:123,31:$V2,42:$VK,84:$Vm},{38:124,40:125,42:[1,126]},{36:[1,128],37:127},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:129,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,61]),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:130,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,62]),{1:[2,4]},o($Vr,[2,8]),o($Vr,[2,9]),o($Vt,[2,13]),{17:132,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,41:$V5,50:$V7,56:$V8,57:$V9,59:131,60:$Va},o($VG,[2,30],{9:$Vo,11:$Vp}),o($VJ,[2,29],{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,7:119,13:$V0,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,32]),{34:133,62:$VH},{34:134,62:$VH},{5:135,31:$V2,84:$Vm},o([31,84],[2,38],{42:[1,136]}),o($VL,[2,105]),o($VM,$VC,{10:137,31:$VD}),o([27,31,42,44],$VK),{52:138,53:[1,139],54:$VN,55:$VO},{63:[1,142]},o($Vt,[2,63]),o($Vt,[2,64],{70:35,72:37,68:55,18:143,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,33]),o($Vv,[2,34]),{34:144,62:$VH},o($VL,[2,106]),{27:$VP,42:$VQ,43:145,44:[1,147],45:146,46:149,47:148,48:150},{53:[1,153]},o($Vv,[2,57]),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:154,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:155,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,68]),o($Vt,[2,65],{70:35,72:37,68:96,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,35]),{27:$VP,42:$VQ,44:[1,156],46:158,47:157,48:150},{44:[1,159]},o($Vv,[2,41]),o($VM,[2,45]),{44:[2,43]},{15:$VR,29:[1,160]},{42:$VQ,48:162},o($VS,[2,54]),o($Vv,[2,56]),{51:[1,163]},{53:[2,60]},o($Vv,[2,39]),o($VM,[2,44]),{44:[2,42]},o($Vv,[2,40]),o($VT,$VC,{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,30:65,7:67,10:164,28:165,13:$V0,27:$V1,31:$VU,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),{42:[1,167]},{15:$VR,29:[1,168]},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:169,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{44:[2,46],49:[1,170]},{10:172,31:$VD,44:$VC,49:[1,171]},o($VT,$VI,{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,7:67,30:103,13:$V0,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($VS,[2,55]),o($VT,$VC,{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,30:65,7:67,10:173,28:174,13:$V0,27:$V1,31:$VU,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),{52:175,53:[2,58],54:$VN,55:$VO},o($VM,$VC,{10:176,31:$VD}),o($VM,$VC,{10:177,31:$VD}),{44:[2,47]},{44:[2,48],49:[1,178]},{10:180,31:$VD,44:$VC,49:[1,179]},{53:[2,59]},o($VM,[2,50]),o($VM,[2,51]),o($VM,$VC,{10:181,31:$VD}),o($VM,$VC,{10:182,31:$VD}),{44:[2,49]},o($VM,[2,52]),o($VM,[2,53])],defaultActions:{34:[2,66],48:[2,2],88:[2,1],90:[2,3],114:[2,4],149:[2,43],155:[2,60],158:[2,42],172:[2,47],175:[2,59],180:[2,49]},parseError:function(str,hash2){if(hash2.recoverable)this.trace(str);else{let _parseError2=function(msg,hash3){this.message=msg,this.hash=hash3};var _parseError=_parseError2;throw _parseError2.prototype=Error,new _parseError2(str,hash2)}},parse:function(input){var self=this,stack=[0],tstack=[],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1,args2=lstack.slice.call(arguments,1),lexer=Object.create(this.lexer),sharedState={yy:{}};for(var k in this.yy)if(Object.prototype.hasOwnProperty.call(this.yy,k))sharedState.yy[k]=this.yy[k];if(lexer.setInput(input,sharedState.yy),sharedState.yy.lexer=lexer,sharedState.yy.parser=this,typeof lexer.yylloc>"u")lexer.yylloc={};var yyloc=lexer.yylloc;lstack.push(yyloc);var ranges=lexer.options&&lexer.options.ranges;if(typeof sharedState.yy.parseError==="function")this.parseError=sharedState.yy.parseError;else this.parseError=Object.getPrototypeOf(this).parseError;function popStack(n){stack.length=stack.length-2*n,vstack.length=vstack.length-n,lstack.length=lstack.length-n}_token_stack:var lex=function(){var token=lexer.lex()||EOF;if(typeof token!=="number")token=self.symbols_[token]||token;return token};var symbol2,preErrorSymbol,state2,action,a,r,yyval={},p,len,newState,expected;while(!0){if(state2=stack[stack.length-1],this.defaultActions[state2])action=this.defaultActions[state2];else{if(symbol2===null||typeof symbol2>"u")symbol2=lex();action=table[state2]&&table[state2][symbol2]}if(typeof action>"u"||!action.length||!action[0]){var errStr="";expected=[];for(p in table[state2])if(this.terminals_[p]&&p>TERROR)expected.push("'"+this.terminals_[p]+"'");if(lexer.showPosition)errStr="Parse error on line "+(yylineno+1)+`:
|
|
747
747
|
`+lexer.showPosition()+`
|
|
748
748
|
Expecting `+expected.join(", ")+", got '"+(this.terminals_[symbol2]||symbol2)+"'";else errStr="Parse error on line "+(yylineno+1)+": Unexpected "+(symbol2==EOF?"end of input":"'"+(this.terminals_[symbol2]||symbol2)+"'");this.parseError(errStr,{text:lexer.match,token:this.terminals_[symbol2]||symbol2,line:lexer.yylineno,loc:yyloc,expected})}if(action[0]instanceof Array&&action.length>1)throw Error("Parse Error: multiple actions possible at state: "+state2+", token: "+symbol2);switch(action[0]){case 1:if(stack.push(symbol2),vstack.push(lexer.yytext),lstack.push(lexer.yylloc),stack.push(action[1]),symbol2=null,!preErrorSymbol){if(yyleng=lexer.yyleng,yytext=lexer.yytext,yylineno=lexer.yylineno,yyloc=lexer.yylloc,recovering>0)recovering--}else symbol2=preErrorSymbol,preErrorSymbol=null;break;case 2:if(len=this.productions_[action[1]][1],yyval.$=vstack[vstack.length-len],yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column},ranges)yyval._$.range=[lstack[lstack.length-(len||1)].range[0],lstack[lstack.length-1].range[1]];if(r=this.performAction.apply(yyval,[yytext,yyleng,yylineno,sharedState.yy,action[1],vstack,lstack].concat(args2)),typeof r<"u")return r;if(len)stack=stack.slice(0,-1*len*2),vstack=vstack.slice(0,-1*len),lstack=lstack.slice(0,-1*len);stack.push(this.productions_[action[1]][0]),vstack.push(yyval.$),lstack.push(yyval._$),newState=table[stack[stack.length-2]][stack[stack.length-1]],stack.push(newState);break;case 3:return!0}}return!0}};function Parser(){this.yy={}}return Parser.prototype=parser2,parser2.Parser=Parser,new Parser}();if(typeof exports<"u")exports.parser=parser,exports.Parser=parser.Parser,exports.parse=function(){return parser.parse.apply(parser,arguments)},exports.main=function(args2){if(!args2[1])console.log("Usage: "+args2[0]+" FILE"),process.exit(1);var source=__require("fs").readFileSync(__require("path").normalize(args2[1]),"utf8");return exports.parser.parse(source)}});var require_posix=__commonJS((exports,module)=>{var astBuilder=require_ast_builder(),tokenizer=require_tokenizer(),phaseCatalog=require_rules(),grammarSource=require_grammar(),enums=require_enums(),lexerPhases=()=>[phaseCatalog.newLineList,phaseCatalog.operatorTokens,phaseCatalog.separator,phaseCatalog.reservedWords,phaseCatalog.linebreakIn,phaseCatalog.ioNumber,phaseCatalog.identifyMaybeSimpleCommands,phaseCatalog.assignmentWord,phaseCatalog.parameterExpansion,phaseCatalog.arithmeticExpansion,phaseCatalog.commandExpansion,phaseCatalog.forNameVariable,phaseCatalog.functionName,phaseCatalog.identifySimpleCommandNames,phaseCatalog.aliasSubstitution,phaseCatalog.tildeExpanding,phaseCatalog.parameterExpansion.resolve,phaseCatalog.commandExpansion.resolve,phaseCatalog.arithmeticExpansion.resolve,phaseCatalog.fieldSplitting.split,phaseCatalog.pathExpansion,phaseCatalog.quoteRemoval,phaseCatalog.syntaxerrorOnContinue,phaseCatalog.defaultNodeType];module.exports={inherits:null,init:(posixMode,utils)=>{let grammar=null;try{grammar=require_built_grammar()}catch(err){}return{enums,phaseCatalog,lexerPhases:lexerPhases(utils),tokenizer,grammarSource,grammar,astBuilder}}}});var require_word_expansion=__commonJS((exports,module)=>{var map2=require_map_iterable(),tokenOrEmpty=require_tokens().tokenOrEmpty,convertToWord=()=>map2((tk)=>{if(tk.is("TOKEN"))return tk.changeTokenType("WORD",tk.value);return tk});function start(state2,source,reducers){let char=source&&source.shift();if(char===void 0)return{nextReduction:reducers.end,tokensToEmit:tokenOrEmpty(state2),nextState:state2.resetCurrent().saveCurrentLocAsStart()};if(state2.escaping&&char===`
|
|
749
|
-
`)return{nextReduction:reducers.start,nextState:state2.setEscaping(!1).removeLastChar()};if(!state2.escaping&&char==="\\")return{nextReduction:reducers.start,nextState:state2.setEscaping(!0).appendChar(char)};if(!state2.escaping&&char==="'")return{nextReduction:reducers.singleQuoting,nextState:state2.appendChar(char)};if(!state2.escaping&&char==='"')return{nextReduction:reducers.doubleQuoting,nextState:state2.appendChar(char)};if(!state2.escaping&&char==="$")return{nextReduction:reducers.expansionStart,nextState:state2.appendChar(char).appendEmptyExpansion()};if(!state2.escaping&&char==="`")return{nextReduction:reducers.expansionCommandTick,nextState:state2.appendChar(char).appendEmptyExpansion()};return{nextReduction:reducers.start,nextState:state2.appendChar(char).setEscaping(!1)}}module.exports={inherits:"posix",init:(posixMode)=>{let phaseCatalog=posixMode.phaseCatalog,lexerPhases=[convertToWord,phaseCatalog.parameterExpansion,phaseCatalog.arithmeticExpansion,phaseCatalog.commandExpansion,phaseCatalog.tildeExpanding,phaseCatalog.parameterExpansion.resolve,phaseCatalog.commandExpansion.resolve,phaseCatalog.arithmeticExpansion.resolve,phaseCatalog.fieldSplitting.split,phaseCatalog.pathExpansion,phaseCatalog.quoteRemoval,phaseCatalog.defaultNodeType],reducers=Object.assign({},posixMode.tokenizer.reducers,{start});return Object.assign({},posixMode,{lexerPhases,tokenizer:()=>posixMode.tokenizer({},reducers)})}}});var require_src=__commonJS((exports,module)=>{var shellLexer=require_shell_lexer(),utils=require_utils(),modes={bash:require_bash(),posix:require_posix(),"word-expansion":require_word_expansion()};function loadPlugin(name){let modePlugin=modes[name];if(modePlugin.inherits)return modePlugin.init(loadPlugin(modePlugin.inherits),utils);return modePlugin.init(null,utils)}module.exports=function(sourceCode,options){try{options=options||{},options.mode=options.mode||"posix";let mode=loadPlugin(options.mode),Parser=mode.grammar.Parser,astBuilder=mode.astBuilder,parser=new Parser;return parser.lexer=shellLexer(mode,options),parser.yy=astBuilder(options),parser.parse(sourceCode)}catch(err){if(err instanceof SyntaxError)throw err;throw Error(err.stack||err.message)}}});import*as path58 from"node:path";function unsafeShellCommandTextReason(value){return unsafePathTextReason(value.replace(/[\r\n]/g,""))}function mergeWriteAnalyses(primary,additional,additionalIsAuthoritative=!0,wrapperDeclared=!1){if(additional.writes.length===0&&!additional.hasWrites)return primary;let posixAuthoritative=wrapperDeclared?!1:!additionalIsAuthoritative||!primary.parseError,authority=posixAuthoritative?primary:additional,supplementary=posixAuthoritative?additional:primary,authorityConstructs=new Set(authority.writes.map((write)=>`${write.category}|${write.operator}`)),authorityKeys=new Set(authority.writes.map((write)=>buildDedupeKey(write.category,write.operator,write.path))),stripQuotes=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),isQuoteArtifact=(write)=>{let stripped=stripQuotes(write.path);if(stripped===write.path)return!1;return authority.writes.some((other)=>other.category===write.category&&other.operator===write.operator&&stripQuotes(other.path)===stripped)},keptIndex=new Map,writes=[],demoteKept=(key)=>{let index=keptIndex.get(key);if(index!==void 0)writes[index]=withoutEmptyDirectoryRemoval(writes[index])};for(let write of[...authority.writes,...supplementary.writes]){let key=buildDedupeKey(write.category,write.operator,write.path);if(supplementary.writes.includes(write))if(wrapperDeclared){let construct=`${write.category}|${write.operator}`;if(authorityConstructs.has(construct))continue}else{if(authorityKeys.has(key)){demoteKept(key);continue}if(isQuoteArtifact(write))continue}if(keptIndex.has(key)){demoteKept(key);continue}keptIndex.set(key,writes.length),writes.push(write)}return{writes,hasWrites:writes.length>0||primary.hasWrites||additional.hasWrites,parseError:primary.parseError}}function buildDedupeKey(category,operator,path59){return`${category}|${operator}|${path59??"null"}`}function withoutEmptyDirectoryRemoval(write){if(write.emptyDirectoryRemoval!==!0)return write;let{emptyDirectoryRemoval:_dropped,...rest}=write;return rest}function isBareRmdirOperand(word){return BARE_RMDIR_OPERAND.test(word)&&!word.split("/").includes("..")}function unquotedWordTokens(command){let tokens=[],current="",quote=null,flush=()=>{if(current.length>0)tokens.push(current);current=""};for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote){if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"){flush(),quote=ch;continue}if(/\s/.test(ch)){flush();continue}current+=ch}return flush(),tokens.map((token)=>token.replace(/^[({]+/,"").replace(/[)}]+$/,""))}function isPowerShellShaped(command){if(!command)return!1;return unquotedWordTokens(command).some((token)=>{let lower=token.toLowerCase();return POWERSHELL_WRITE_CMDLETS.has(lower)||POWERSHELL_READ_ONLY_COMMANDS.has(lower)})}function isReadOnlyScriptBlockBody(body){if(/[()[\]=@|`;]/.test(body)||body.includes("::")||body.includes("$("))return!1;let tokens=body.match(/"[^"]*"|'[^']*'|\S+/g)?.map((token)=>token.replace(/^[({]+/,"").replace(/[)}]+$/,""))??[];if(tokens.length===0)return!1;for(let token of tokens){if(token===",")continue;if(/^(?:"[^"]*"|'[^']*')$/.test(token))continue;if(/^-?\d+(?:\.\d+)?$/.test(token))continue;if(READ_ONLY_SCRIPT_BLOCK_OPERATORS.has(token.toLowerCase()))continue;if(/^(?:\$_|\$this)(?:\.[A-Za-z_]\w*)*$/.test(token))continue;return!1}return!0}function extractScriptBlockBodies(command){let bodies=[],depth=0,start=-1,quote=null;for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote){if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch==="{"){if(depth===0)start=i+1;depth+=1;continue}if(ch==="}"){if(depth-=1,depth<0)return null;if(depth===0&&start>=0)bodies.push(command.slice(start,i)),start=-1}}if(quote!==null||depth!==0)return null;return bodies}function isPowerShellReadOnlyPipeline(command){if(!command)return!1;if(/[>;&`\r\n]/.test(command)||/\$\(/.test(command))return!1;let quote=null,braceDepth=0;for(let ch of command){if(quote){if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch==="{")braceDepth+=1;if(ch==="}")braceDepth-=1;if(braceDepth<0)return!1}if(quote!==null||braceDepth!==0)return!1;for(let token of unquotedWordTokens(command)){let lower=token.toLowerCase();if(POWERSHELL_WRITE_CMDLETS.has(lower)||AMBIGUOUS_WRITE_ALIASES.has(lower)||POSIX_WRITE_TOKENS.has(lower))return!1;if((token==="sed"||token==="perl"||token==="awk")&&/(^|[\s'"])--?[a-zA-Z-]*(?:\bi|\bin-place|\bpi)\b/.test(command))return!1}let bodies=extractScriptBlockBodies(command);if(bodies===null)return!1;for(let body of bodies)if(!isReadOnlyScriptBlockBody(body))return!1;let segments=[],current="";quote=null;for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote){if(ch===quote)quote=null;current+=ch;continue}if(ch==='"'||ch==="'"){quote=ch,current+=ch;continue}if(ch==="|"){segments.push(current),current="";continue}current+=ch}segments.push(current);for(let segment of segments){let tokens=unquotedWordTokens(segment.trim());if(tokens.length===0)return!1;if(!POWERSHELL_READ_ONLY_COMMANDS.has(tokens[0].toLowerCase()))return!1}return segments.length>0}function detectProcessSubstitutionWrites(command){let results=[],writeProcSubPattern=/>\s*\(([^)]+)\)/g;while(!0){let match=writeProcSubPattern.exec(command);if(match===null)break;let innerCommand=match[1].trim();if(!innerCommand)continue;let stages=innerCommand.split("|").map((s)=>s.trim());for(let stage of stages){let builtinResult=detectBuiltinWritesFromString(stage);if(builtinResult)results.push(builtinResult);let appendMatch=stage.match(/^\s*(.*?)\s*>>(\s*)(\S+)\s*$/);if(appendMatch){let path59=appendMatch[3];if(path59&&!isNullDevice(path59))results.push({category:"redirect",operator:">>",path:path59})}else{let writeMatch=stage.match(/^\s*(.*?)\s*>(?!>)(\s*)(\S+)\s*$/);if(writeMatch){let path59=writeMatch[3];if(path59&&!isNullDevice(path59))results.push({category:"redirect",operator:">",path:path59})}}}}return results}function detectBuiltinWritesFromString(cmd){let tokens=cmd.trim().split(/\s+/);if(tokens.length===0)return null;let leaf=detectorCommandLeafFromWords(tokens[0],tokens.slice(1)),name=detectorSetMember(leaf,BUILTIN_WRITE_COMMANDS);if(!name)return null;if(name==="rmdir"&&tokens.some((token)=>/^\/(?:s|q)$/i.test(token)))return null;for(let i=tokens.length-1;i>=1;i--)if(!tokens[i].startsWith("-"))return{category:"builtin_write",operator:name,path:tokens[i]};return null}function wordText(node){if(!node||typeof node!=="object")return null;if(isBashWord(node)){let raw=RAW_WORD_TEXT.get(node);if(raw!==void 0){let expansions=node.expansion;if(!Array.isArray(expansions)||expansions.length===0){let{projection,dequoted}=scanQuoting(raw);if(dequoted.length>node.text.length&&dequoted.startsWith(node.text)&&dequoted[node.text.length]==="#"&&projection[node.text.length]!=="\x00")return dequoted}}return node.text}return null}function isBashWord(node){return!!node&&typeof node==="object"&&node.type==="Word"&&typeof node.text==="string"}function annotateRawWordText(node,source){let unitIndex=null;if(/[\uD800-\uDFFF]/.test(source)){unitIndex=[];let u=0;for(let cp2 of source)unitIndex.push(u),u+=cp2.length;unitIndex.push(u)}let toUnit=(cp2)=>unitIndex===null?cp2:unitIndex[cp2],stack=[node],seen=new Set;while(stack.length>0){let n=stack.pop();if(!n||typeof n!=="object"||seen.has(n))continue;if(seen.add(n),isBashWord(n)){let loc=n.loc,start=loc?.start?.char,end=loc?.end?.char;if(typeof start==="number"&&typeof end==="number"&&end>=start){let from=toUnit(start),to=toUnit(end+1);if(from!==void 0&&to!==void 0)RAW_WORD_TEXT.set(n,source.slice(from,to))}}for(let value of Object.values(n))if(value&&typeof value==="object")stack.push(value)}}function hasUnquotedGlob(word){let projection=unquotedProjection(word);return projection===null||/[*?[]/.test(projection)}function hasUnquotedBraceExpansion(word,text){let projection=unquotedProjection(word);return BRACE_EXPANSION.test(projection===null?text:projection)}function unquotedProjection(word){if(!word||typeof word!=="object")return null;let raw=RAW_WORD_TEXT.get(word);if(raw===void 0)return null;let{projection,dequoted}=scanQuoting(raw),hasExpansion=Array.isArray(word.expansion)&&(word.expansion.length??0)>0,text=word.text;if(!hasExpansion&&dequoted!==text&&decodeParserEscapes(dequoted)!==text)return null;return projection}function scanQuoting(raw){let state2="none",projection="",dequoted="";for(let c=0;c<raw.length;c++){let ch=raw[c];if(state2==="single")if(ch==="'")state2="none";else dequoted+=ch,projection+="\x00";else if(ch==="\\"){let next=raw[c+1]??"";if(state2==="double"&&!/[$`"\\\n]/.test(next)){dequoted+=ch,projection+="\x00";continue}if(next!==`
|
|
750
|
-
`)dequoted+=next,projection+="\x00";c++}else if(ch==='"')state2=state2==="double"?"none":"double";else if(state2==="none"&&ch==="'")state2="single";else dequoted+=ch,projection+=state2==="none"?ch:"\x00"}return{projection,dequoted}}function decodeParserEscapes(s){return s.replace(/\\(?:x([0-9A-Fa-f]{2})|u([0-9A-Fa-f]{4})|U([0-9A-Fa-f]{8})|([0-7]{1,3})|([\\tnrbfv"']))/g,(m,x,u,big,octal,c)=>{let hex3=x??u??big;if(hex3!==void 0){let cp2=Number.parseInt(hex3,16);return cp2<=1114111?String.fromCodePoint(cp2):m}if(octal!==void 0)return String.fromCodePoint(Number.parseInt(octal,8));return PARSER_CHAR_ESCAPES[c]??c})}function collectLeafCommands(node,out){if(!node||typeof node!=="object")return;switch(node.type){case"Script":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"Pipeline":case"Sequence":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"CompoundList":if(out.push(node),Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"LogicalExpression":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"And":case"Or":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"Subshell":if(out.push(node),node.list)collectLeafCommands(node.list,out);break;case"ProcessSubstitution":{let opNode=node.op;if(opNode&&typeof opNode==="object"){if(opNode.type?.toUpperCase()==="GREAT"){if(node.command)collectLeafCommands(node.command,out)}}}break;case"If":if(out.push(node),node.clause)collectLeafCommands(node.clause,out);if(node.then)collectLeafCommands(node.then,out);if(node.else)collectLeafCommands(node.else,out);break;case"While":case"Until":if(out.push(node),node.clause)collectLeafCommands(node.clause,out);if(node.do)collectLeafCommands(node.do,out);break;case"For":if(out.push(node),node.do)collectLeafCommands(node.do,out);break;case"Case":if(out.push(node),Array.isArray(node.cases)){for(let entry of node.cases)if(entry?.body)collectLeafCommands(entry.body,out)}break;case"Function":if(out.push(node),node.body)collectLeafCommands(node.body,out);break;default:out.push(node);break}}function getCommandName(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(typeof c.name==="string")return c.name;return wordText(c.name)}function basenameAnySep(word){return basenameAnySepCase(word).toLowerCase()}function basenameAnySepCase(word){return(word.split(/[\\/]/).filter(Boolean).pop()??word).replace(/\.exe$/i,"")}function envFlagConsumesNextWord(token){if(token.startsWith("--")){if(ENV_FLAGS_WITH_ARG.has(token))return!0;if(token.length<3)return!1;return[...ENV_FLAGS_WITH_ARG].filter((flag)=>flag.startsWith("--")&&flag.startsWith(token)).length===1}if(token.startsWith("-")&&token.length>2){let chars=token.slice(1).split(""),argTaking=["u","U","C","S","a","P"];return chars.findIndex((c)=>argTaking.includes(c))===chars.length-1&&chars.slice(0,-1).every((c)=>!argTaking.includes(c))}return ENV_FLAGS_WITH_ARG.has(token)}function canonicalInterpreterName(cmd){let name=getCommandName(cmd);if(!name)return null;let words=[name,...getSuffixWords(cmd)],i=0;for(let hop=0;hop<words.length;hop++){let base=basenameAnySep(words[i]??"");if(base!=="env"&&base!=="command"&&base!=="exec")break;if(i+=1,base==="env")while(i<words.length){let token=words[i];if(token===void 0)break;if(envFlagConsumesNextWord(token)){i+=2;continue}if(token.startsWith("-")){i+=1;continue}if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){i+=1;continue}break}else while(i<words.length){let token=words[i];if(token===void 0)break;if(token==="-a"||token==="--arg0"){i+=2;continue}if(token.startsWith("-")){i+=1;continue}break}if(i>=words.length)return null}let word=words[i];if(word===void 0)return null;let full=basenameAnySep(word);if(INTERPRETER_EVAL_COMMANDS.has(full))return full;let stripped=full.replace(/\d+(\.\d+)*$/,"");if(stripped!==""&&stripped!==full&&INTERPRETER_EVAL_COMMANDS.has(stripped))return stripped;return null}function getSuffixWords(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let words=[];for(let s of suffix){let text=wordText(s);if(text!==null)words.push(text)}return words}function isQueryFlag(token){if(token==="-v"||token==="-V")return!0;return/^-[pvVP]+$/.test(token)&&/[vV]/.test(token)}function detectorCommandLeaf(cmd){return detectorCommandParts(cmd).leaf}function detectorCommandRawLeaf(cmd){return detectorCommandPartsFromWords(getCommandName(cmd),getSuffixWords(cmd)).rawLeaf}function detectorCommandParts(cmd){let suffix=getSuffixWords(cmd);return{leaf:detectorCommandLeafFromWords(getCommandName(cmd),suffix),rest:suffix}}function detectorCommandLeafFromWords(cmdName,suffix){return detectorCommandPartsFromWords(cmdName,suffix).leaf}function detectorCommandPartsFromWords(cmdName,suffix){let name=cmdName;if(!name)return{leaf:"",rest:suffix,rawLeaf:""};let cursor=0;for(let hop=0;hop<8;hop++){let base=basenameAnySep(name),rawBase=basenameAnySepCase(name);if(base!=="env"&&base!=="command"&&base!=="builtin"&&base!=="exec")return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase};if(base==="env")while(cursor<suffix.length){let token=suffix[cursor];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){cursor++;continue}if(token.startsWith("-")&&token!=="-"){if(cursor++,envFlagConsumesNextWord(token)&&cursor<suffix.length)cursor++;continue}break}else if(base==="command"){while(cursor<suffix.length&&suffix[cursor]==="-p")cursor++;if(cursor<suffix.length&&isQueryFlag(suffix[cursor]))return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase};if(cursor<suffix.length&&suffix[cursor]==="--")cursor++}else if(base==="builtin"){if(cursor<suffix.length){let wrapped=basenameAnySep(suffix[cursor]);if(!BASH_BUILTIN_COMMANDS.has(wrapped))return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase}}if(cursor<suffix.length&&suffix[cursor]==="--")cursor++}else if(base==="exec"){while(cursor<suffix.length&&/^-[cl]$/.test(suffix[cursor]))cursor++;if(cursor<suffix.length&&suffix[cursor]==="-a")cursor+=2;if(cursor<suffix.length&&/^-a\S+$/.test(suffix[cursor]))cursor++;if(cursor<suffix.length&&/^-[cl]{2,}$/.test(suffix[cursor]))cursor++;if(cursor<suffix.length&&suffix[cursor]==="--")cursor++}if(cursor>=suffix.length)return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase};if(name=suffix[cursor],cursor++,!name)return{leaf:base,rest:suffix.slice(cursor-1),rawLeaf:rawBase}}return{leaf:basenameAnySep(name),rest:suffix.slice(cursor),rawLeaf:basenameAnySepCase(name)}}function detectorSetMember(leaf,set2){if(leaf&&set2.has(leaf))return leaf;let dotted2=leaf.replace(/\.\d+(\.\d+)*$/,"");if(dotted2!==leaf&&set2.has(dotted2))return dotted2;let stripped=dotted2.replace(/\d+(\.\d+)*$/,"");if(stripped!==dotted2&&set2.has(stripped))return stripped;return null}function getSuffixWordExpansionFlags(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let flags=[];for(let s of suffix){if(!isBashWord(s))continue;let expansion=s.expansion;flags.push(Array.isArray(expansion)&&expansion.length>0)}return flags}function getSuffixWordUnquotedExpansionFlags(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let flags=[];for(let s of suffix){if(!isBashWord(s))continue;let expansion=s.expansion;if(!Array.isArray(expansion)||expansion.length===0){flags.push(!1);continue}let text=s.text,hasSubstitution=/\$\(|`/.test(text),hasListExpansion=/\$\{?[!#]?[A-Za-z0-9_]*(?:\[[@*]\]|@|\*)/.test(text)||/\$\{?[!#]?[@*]|\[[@*]\]/.test(text);if(hasSubstitution||hasListExpansion){flags.push(!0);continue}let quotedAt=[],state2="none";for(let c=0;c<text.length;c++){let ch=text[c];if(quotedAt[c]=state2!=="none",state2==="single"){if(ch==="'")state2="none"}else if(ch==="\\")quotedAt[c+1]=!0,c++;else if(ch==='"')state2=state2==="double"?"none":"double";else if(ch==="'"&&state2==="none")state2="single"}flags.push(expansion.some((e)=>{let start=e.loc?.start;return typeof start!=="number"||quotedAt[start]!==!0}))}return flags}function getRedirections(cmd){if(!cmd||typeof cmd!=="object")return[];let c=cmd;if(Array.isArray(c.redirections))return c.redirections;let results=[],suffix=c.suffix,prefix=c.prefix;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item))results.push(item)}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item))results.push(item)}return results}function isRedirectNode(node){return!!(node&&typeof node==="object"&&node.type==="Redirect")}function operatorLabel(op){if(!op||typeof op!=="object")return"unknown";let opType=op.type?.toUpperCase();switch(opType){case"GREAT":return">";case"DGREAT":return">>";case"CLOBBER":return">|";case"LESS":return"<";case"DLESS":return"<<";case"DLESSDASH":return"<<-";case"LESSAND":return"<&";case"GREATAND":return">&";case"LESSGREAT":return"<>";default:return opType||"unknown"}}function extractRedirectPath(fileNode){let text=wordText(fileNode);if(!text)return null;return text}function isNullDevice(path59){return path59==="/dev/null"||path59==="/dev/zero"||path59==="/dev/urandom"}function isNullDeviceWord(word,path59){if(!isNullDevice(path59)||!word||typeof word!=="object")return!1;let raw=RAW_WORD_TEXT.get(word);return raw!==void 0&&isNullDevice(scanQuoting(raw).dequoted)}function isNumeric(s){return/^\d+$/.test(s)}function isNonFileGreatAndTarget(path59){return path59!==null&&(isNumeric(path59)||path59==="-")}function detectRedirects(cmd){let results=[];results.push(...detectHereDocMarkers(cmd));let redirections=getRedirections(cmd);for(let redirect of redirections){if(!redirect||typeof redirect!=="object")continue;let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")continue;let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))continue;let fileNode=r.file,path59=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path59)){if(path59!==null&&isNullDeviceWord(fileNode,path59))continue;results.push({category:"redirect",operator:opLabel,path:path59})}else if(REDIRECT_HERE_TOKENS.has(opType))results.push({category:"here_doc",operator:opLabel,path:path59})}return results}function detectHereDocMarkers(cmd){let results=[];if(!cmd||typeof cmd!=="object")return results;let suffix=cmd.suffix;if(!Array.isArray(suffix))return results;for(let item of suffix){if(!item||typeof item!=="object")continue;if(isHereDocMarker(item))results.push({category:"here_doc",operator:item.text==="<<-"?"<<-":"<<",path:null})}return results}function isHereDocMarker(node){if(!node||typeof node!=="object")return!1;let type=node.type?.toLowerCase();return type==="dless"||type==="dlessdash"}function detectBuiltinWrites(cmd){let results=[];if(!getCommandName(cmd))return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,BUILTIN_WRITE_COMMANDS)??(leaf==="dd"||leaf==="tee"?leaf:null);if(!lowerName)return results;let dedupeOperator=detectorCommandRawLeaf(cmd);if(lowerName==="dd"){let suffixWords2=getSuffixWords(cmd);for(let word of suffixWords2)if(word.startsWith("of=")){let path59=word.slice(3);if(path59&&!isNullDevice(path59))results.push({category:"builtin_write",operator:"dd of=",path:path59})}return results}if(lowerName==="tee"){let suffixWords2=getSuffixWords(cmd),pastDoubleDash=!1;for(let word of suffixWords2){if(word==="--"){pastDoubleDash=!0;continue}if(!pastDoubleDash&&word.startsWith("-"))continue;if(word&&!isNullDevice(word))results.push({category:"builtin_write",operator:"tee",path:word})}return results}if(!BUILTIN_WRITE_COMMANDS.has(lowerName))return results;let suffixWords=getSuffixWords(cmd);if(lowerName==="rmdir"&&suffixWords.some((word)=>/^\/(?:s|q)$/i.test(word)))return results;if(lowerName==="rmdir"&&suffixWords.length===1&&isBareRmdirOperand(suffixWords[0]))return results.push({category:"builtin_write",operator:dedupeOperator,path:suffixWords[0],emptyDirectoryRemoval:!0}),results;if(lowerName==="truncate"){for(let word of suffixWords)if(!word.startsWith("-")&&!isNumeric(word)){results.push({category:"builtin_write",operator:"truncate",path:word});break}}else for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"builtin_write",operator:dedupeOperator,path:word});break}}return results}function looksLikeSedScript(w){if(hasParentComponent(w)||/^[A-Za-z]:[\\/]/.test(w))return!1;return/^(?:(?:[0-9]+|\$)(?:,(?:[0-9]+|\$))?!?|!)[a-zA-Z=]$/.test(w)||/[;{}]/.test(w)&&!/[\\/:]/.test(w)&&!w.startsWith(".")||/^s([^A-Za-z0-9\s\\])(?:\\.|(?!\1)[^\\])*\1(?:\\.|(?!\1)[^\\])*\1[gpiImMe0-9]*$/.test(w)||/^y([^A-Za-z0-9\s\\])(?:\\.|(?!\1)[^\\])*\1(?:\\.|(?!\1)[^\\])*\1$/.test(w)}function hasParentComponent(w){return w.split(/[\\/]/).includes("..")}function detectInplaceEdit(cmd){let results=[];if(!getCommandName(cmd))return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,INPLACE_EDIT_COMMANDS);if(!lowerName)return[];let suffixWords=getSuffixWords(cmd);if(!suffixWords.some((word)=>{if(lowerName==="sed")return word.startsWith("-i")&&word.length>1||/^--i(?:n(?:-(?:p(?:l(?:a(?:c(?:e)?)?)?)?)?)?)?(?:=|$)/.test(word);return word==="-i"||word.startsWith("-i")}))return[];let scriptPattern=/^[ssy]\/.*\/[gim]*$/,quotedScriptPattern=/^["'].*["']$/,isScriptShaped=(w)=>scriptPattern.test(w)&&!hasParentComponent(w),isScriptWord=(i)=>{let w=suffixWords[i];if(quotedScriptPattern.test(w))return unquotedExpansionFlags[i]!==!0&&isScriptShaped(w.slice(1,-1));return isScriptShaped(w)},flagArgs=lowerName==="sed"?new Set(["-e","-f","--expression","--file"]):lowerName==="perl"?new Set(["-e","-E"]):new Set(["-f","-e","-v","-F"]),combinedFlagArgs=/^-[0-9AacSlnpstTuUwWX]+[eE]$/,perlAttachedScript=/^-[0-9AacSlnpstTuUwWX]*[eE]./,sedScriptBundle=/^-[nrEszub]*[ef]$/,sedAttachedScript=/^-[nrEszub]*[ef]./,consumesNext=(w)=>flagArgs.has(w)||lowerName==="sed"&&sedScriptBundle.test(w)||lowerName==="perl"&&combinedFlagArgs.test(w),suppliesScript=(w)=>{if(lowerName==="awk")return w==="-f"||w==="-e"||/^-[fe]./.test(w)||w.startsWith("--file=")||w.startsWith("--source=");if(lowerName==="sed")return consumesNext(w)||sedAttachedScript.test(w)||/^--(?:expression|file)=/.test(w);return consumesNext(w)||perlAttachedScript.test(w)},expansionFlags=getSuffixWordExpansionFlags(cmd),unquotedExpansionFlags=getSuffixWordUnquotedExpansionFlags(cmd),suffixNodes=(Array.isArray(cmd.suffix)?cmd.suffix:[]).filter((s)=>wordText(s)!==null),mayExpandToSeveralWords=(i)=>unquotedExpansionFlags[i]===!0||hasUnquotedBraceExpansion(suffixNodes[i],suffixWords[i]),isKnownOption=(w)=>{if(w==="-"||w==="--")return!0;if(lowerName==="sed")return/^-[nrEszub]+$/.test(w)||/^-[nrEszub]*[ef]/.test(w)||/^-[nrEszub]*l/.test(w)||/^-i/.test(w)||SED_LONG_SWITCHES.has(w)||/^--(?:expression|file|line-length|in-place)(?:=|$)/.test(w);if(lowerName==="perl")return/^-[0-9AacSlnpstTuUwWX]*(?:[eE].*)?$/.test(w)||/^-i/.test(w)||/^-I./.test(w);return/^-[fevFil]/.test(w)||/^-[PcrSVh]$/.test(w)||AWK_LONG_SWITCHES.has(w)||/^--(?:file|source|lint)=/.test(w)},isOpaqueFlag=(i)=>suffixWords[i].startsWith("-")&&(mayExpandToSeveralWords(i)||!isKnownOption(suffixWords[i])),sedOptionArg=(w)=>lowerName==="sed"&&(/^-[nrEszub]*l$/.test(w)||w==="--line-length"),takesDetachedArg=(w)=>consumesNext(w)||sedOptionArg(w)||lowerName==="awk"&&w==="-i",fileArgOption=(w)=>lowerName==="sed"&&(/^-[nrEszub]*f$/.test(w)||w==="--file")||lowerName==="awk"&&(w==="-f"||w==="-i"),detachedArgMaySplit=(option,i)=>mayExpandToSeveralWords(i)||(fileArgOption(option)?/[*?[]/.test(suffixWords[i]):hasUnquotedGlob(suffixNodes[i])),permutes=lowerName==="sed",operandsFrom=suffixWords.length,optionArgs=new Set,expandingOptionArgs=new Set;for(let i=0;i<suffixWords.length;i++){let w=suffixWords[i];if(w==="--"){if(!permutes)operandsFrom=i+1;break}if(!w.startsWith("-")){if(!permutes){operandsFrom=i;break}continue}if(isOpaqueFlag(i)){if(!permutes){operandsFrom=i+1;break}continue}if(!takesDetachedArg(w))continue;if(i+1<suffixWords.length){if(optionArgs.add(i+1),detachedArgMaySplit(w,i+1)){if(expandingOptionArgs.add(i+1),!permutes){operandsFrom=i+2;break}}}i++}let inOptionArea=(i)=>i<operandsFrom,hasExplicitScript=!1;for(let i=0;i<suffixWords.length&&inOptionArea(i);i++){if(optionArgs.has(i))continue;let w=suffixWords[i];if(w==="--")break;if(!w.startsWith("-")||isOpaqueFlag(i))continue;if(expandingOptionArgs.has(i+1)){i++;continue}if(suppliesScript(w)){hasExplicitScript=!0;break}if(consumesNext(w)||lowerName==="awk"&&w==="-i")i++}let skipIndices=new Set,isDetachedSuffix=(w)=>lowerName==="sed"&&w!==void 0&&(w===""||w.startsWith(".")),isLiteralWord=(i)=>expansionFlags[i]!==!0&&!/[*?[]/.test(suffixWords[i])&&!/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(suffixWords[i]),isLiteralSedScript=(i)=>isLiteralWord(i)&&looksLikeSedScript(suffixWords[i]),isReportableWord=(i)=>suffixWords[i]!==""&&!isScriptWord(i)&&!isLiteralSedScript(i),firstPositionalFrom=(from)=>{let j=from;while(j<suffixWords.length&&(inOptionArea(j)&&suffixWords[j].startsWith("-")||optionArgs.has(j)))j++;return j},dashDash=suffixWords.findIndex((w,i)=>w==="--"&&!optionArgs.has(i)&&inOptionArea(i)),hasOpaqueFlag=suffixWords.some((_w,i)=>(dashDash<0||i<dashDash)&&inOptionArea(i)&&!optionArgs.has(i)&&isOpaqueFlag(i)),implicitScriptPlaced=hasOpaqueFlag||expandingOptionArgs.size>0;if(lowerName==="sed"&&!hasExplicitScript&&!implicitScriptPlaced)for(let i=0;i<suffixWords.length;i++){if(optionArgs.has(i))continue;let w=suffixWords[i];if(w==="--"||w.startsWith("-i")||w.startsWith("--in-place"))break;if(w.startsWith("-"))continue;if(!mayExpandToSeveralWords(i))skipIndices.add(i);implicitScriptPlaced=!0;break}let consumeImplicitScript=(from,bareInplace)=>{if(implicitScriptPlaced)return;implicitScriptPlaced=!0;let j=firstPositionalFrom(from);if(j>=suffixWords.length||mayExpandToSeveralWords(j))return;if(skipIndices.add(j),!bareInplace||!isDetachedSuffix(suffixWords[j]))return;let k=firstPositionalFrom(j+1);if(k>=suffixWords.length||!isLiteralSedScript(k))return;for(let m=firstPositionalFrom(k+1);m<suffixWords.length;){if(isReportableWord(m)){skipIndices.add(k);return}m=firstPositionalFrom(m+1)}},isConventionalBackupSuffix=(w)=>isDetachedSuffix(w)&&!w.includes("/")&&/^\.(?:bak|orig|old|save|backup|tmp|swp|~)$/i.test(w),dotWordAfterBareInplace=null,pastDoubleDash=!1,awkProgramSeen=!1;for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(optionArgs.has(i)){if(!expandingOptionArgs.has(i))skipIndices.add(i);continue}if(!pastDoubleDash&&word==="--"&&inOptionArea(i)){skipIndices.add(i),pastDoubleDash=!0;continue}if(!pastDoubleDash&&inOptionArea(i)&&word.startsWith("-")){if(isOpaqueFlag(i))continue;skipIndices.add(i);let next=suffixWords[i+1];if(lowerName==="sed"&&(word==="--in-place"||word.startsWith("--in-place="))){if(!hasExplicitScript)consumeImplicitScript(i+1,!1);continue}if(word==="-i"){if(next===void 0)continue;if(lowerName==="awk"){if(!expandingOptionArgs.has(i+1))skipIndices.add(i+1)}else if(!hasExplicitScript)consumeImplicitScript(i+1,!0);else if(isConventionalBackupSuffix(next))skipIndices.add(i+1),dotWordAfterBareInplace=next;continue}if(/^-i.+/.test(word)){if(lowerName!=="awk"&&!hasExplicitScript)consumeImplicitScript(i+1,!1);continue}if(consumesNext(word)||sedOptionArg(word)){if(next!==void 0&&!expandingOptionArgs.has(i+1))skipIndices.add(i+1)}continue}if(skipIndices.has(i))continue;if(lowerName==="awk"){if(!hasExplicitScript&&!hasOpaqueFlag&&expandingOptionArgs.size===0&&!awkProgramSeen)awkProgramSeen=!0,skipIndices.add(i);continue}if(isScriptWord(i))skipIndices.add(i)}let candidates=suffixWords.map((word,i)=>({word,i})).filter(({word,i})=>word!==""&&!skipIndices.has(i));if(candidates.length===0&&dotWordAfterBareInplace!==null)candidates.push({word:dotWordAfterBareInplace,i:-1});if(candidates.length>0)for(let{word}of candidates)results.push({category:"inplace_edit",operator:`${lowerName} -i`,path:word});return results}function classifyPipeStdinEval(node){if(!node||typeof node!=="object")return null;let pipeline=node;if(pipeline.type!=="Pipeline"||!Array.isArray(pipeline.commands))return null;if(pipeline.commands.length<2)return null;for(let pos=pipeline.commands.length-1;pos>=1;pos--){let evalWrite=classifyPipeStdinEvalAt(node,pos);if(evalWrite)return evalWrite}return null}function classifyPipeStdinEvalAt(node,pos){let pipeline=node;if(!Array.isArray(pipeline.commands))return null;let last=pipeline.commands[pos],canonical=detectorSetMember(detectorCommandLeaf(last),INTERPRETER_EVAL_COMMANDS);if(!canonical||canonical==="eval")return null;let{leaf:_leaf,rest}=detectorCommandPartsFromWords(getCommandName(last),getSuffixWords(last));if(!(rest.length===0||rest.length===1&&rest[0]==="-"))return null;for(let r of getRedirections(last)){let opType=r.op?.type;if(typeof opType==="string"&&/LESS|HEREDOC/i.test(opType))return null}let rawSuffixNodes=last.suffix;if(Array.isArray(rawSuffixNodes)){for(let node2 of rawSuffixNodes)if(node2&&typeof node2==="object"&&node2.type==="dless")return null}for(let i=0;i<pos;i++){let producer=pipeline.commands[i],leaf=detectorCommandLeaf(producer);if(leaf!=="echo"&&leaf!=="printf")return null;let expansions=getSuffixWordExpansionFlags(producer),words=getSuffixWords(producer);for(let w=0;w<words.length;w++)if(w<expansions.length&&expansions[w])return null;if(getRedirections(producer).length>0)return null}return{category:"interpreter_eval",operator:`${canonical} [eval stdin]`,path:null,capability:!0}}function collectPipeStdinEvals(node,out){if(!node||typeof node!=="object")return;if(Array.isArray(node)){for(let child of node)collectPipeStdinEvals(child,out);return}for(let value of Object.values(node))if(value&&typeof value==="object")collectPipeStdinEvals(value,out);let candidate=classifyPipeStdinEval(node);if(candidate)out.push(candidate)}function detectInterpreterEval(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let canonical=canonicalInterpreterName(cmd);if(!canonical)return[];let suffixWords=getSuffixWords(cmd),evalFlags={python:["-c"],python3:["-c"],python2:["-c"],node:["-e","-p","-pe"],bun:["-e","-p","-pe"],ruby:["-e"],perl:["-e","-E"],php:["-r","-R","-F"],bash:["-c"],sh:["-c"],dash:["-c"],zsh:["-c"],ksh:["-c"]};if(canonical==="eval")return results.push({category:"interpreter_eval",operator:"eval",path:null,capability:!0}),results;let relevantFlags=evalFlags[canonical]??[];if(!suffixWords.some((word)=>relevantFlags.some((f)=>word===f||word.startsWith(f)&&word.length>f.length)))return[];return results.push({category:"interpreter_eval",operator:`${name} [eval]`,path:null,capability:!0}),results}function detectNetworkDownloaders(cmd){let results=[];if(!getCommandName(cmd))return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,NETWORK_DOWNLOAD_COMMANDS);if(!lowerName)return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="curl")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-o"&&i+1<suffixWords.length){let path59=suffixWords[i+1];if(!path59.startsWith("-"))results.push({category:"network_download",operator:"curl -o",path:path59})}else if(word.startsWith("-o")&&word.length>2)results.push({category:"network_download",operator:"curl -o",path:word.slice(2)})}else if(lowerName==="wget")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-O"&&i+1<suffixWords.length){let path59=suffixWords[i+1];if(!path59.startsWith("-"))results.push({category:"network_download",operator:"wget -O",path:path59})}else if(word.startsWith("-O")&&word.length>2)results.push({category:"network_download",operator:"wget -O",path:word.slice(2)})}else if(lowerName==="scp")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")&&(word.includes(":")||word.startsWith("/")||word.startsWith("."))){results.push({category:"network_download",operator:"scp",path:word});break}}return results}function detectArchiveExtract(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,ARCHIVE_EXTRACT_COMMANDS);if(!lowerName)return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="tar"){if(suffixWords.some((word)=>{if(word==="--extract"||word==="--get")return!0;if(word.startsWith("-")&&word.includes("x"))return!0;return!1}))for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"tar -x",path:word});break}if(word.startsWith("--file=")&&word.length>7){results.push({category:"archive_extract",operator:"tar -x",path:word.slice(7)});break}}}else if(lowerName==="unzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"unzip",path:word});break}}else if(lowerName==="gunzip"||lowerName==="gzip"||lowerName==="bzip2"||lowerName==="xz"||lowerName==="7z"||lowerName==="rar"){if(suffixWords.includes("-d")||suffixWords.includes("--decompress")||lowerName==="gunzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:`${name} [decompress]`,path:word});break}}}return results}function detectGitDestructive(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;if(name.toLowerCase()!==GIT_COMMAND)return[];let suffixWords=getSuffixWords(cmd);if(suffixWords.length===0)return[];let first=suffixWords[0].toLowerCase();if(first==="checkout"){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length){let path59=suffixWords[dashDashIdx+1],op=path59==="."?"git checkout -- .":"git checkout --";results.push({category:"git_destructive",operator:op,path:path59})}}else if(first==="restore"){let hasHard=suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")),hasForce=suffixWords.some((w)=>w==="--force"||w==="-f"||w.startsWith("-")&&w.includes("f"));if(hasHard||hasForce){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length)results.push({category:"git_destructive",operator:"git restore",path:suffixWords[dashDashIdx+1]});else results.push({category:"git_destructive",operator:"git restore",path:null})}}else if(first==="reset"){if(suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")))results.push({category:"git_destructive",operator:"git reset --hard",path:null})}else if(first==="clean"){if(suffixWords.some((w)=>w==="-n"||w==="--dry-run"||w.startsWith("-")&&w.includes("n")))return results;let hasForce=suffixWords.some((w)=>w==="-f"||w==="--force"||w.startsWith("-")&&w.includes("f")),hasDir=suffixWords.some((w)=>w==="-d"||w==="--dir"||w.startsWith("-")&&w.includes("d"));if(hasForce&&hasDir)results.push({category:"git_destructive",operator:"git clean -fd",path:null})}return results}function splitWindowsCommands(command,shell){let commands=[],current="",inSingleQuote=!1,inDoubleQuote=!1,parenDepth=0;for(let i=0;i<command.length;i++){let ch=command[i];if(shell==="powershell"&&ch==="'"&&!inDoubleQuote)inSingleQuote=!inSingleQuote;else if(ch==='"'&&!inSingleQuote)inDoubleQuote=!inDoubleQuote;else if(ch==="("&&!inSingleQuote&&!inDoubleQuote)parenDepth++;else if(ch===")"&&!inSingleQuote&&!inDoubleQuote)parenDepth--;if(ch===`
|
|
749
|
+
`)return{nextReduction:reducers.start,nextState:state2.setEscaping(!1).removeLastChar()};if(!state2.escaping&&char==="\\")return{nextReduction:reducers.start,nextState:state2.setEscaping(!0).appendChar(char)};if(!state2.escaping&&char==="'")return{nextReduction:reducers.singleQuoting,nextState:state2.appendChar(char)};if(!state2.escaping&&char==='"')return{nextReduction:reducers.doubleQuoting,nextState:state2.appendChar(char)};if(!state2.escaping&&char==="$")return{nextReduction:reducers.expansionStart,nextState:state2.appendChar(char).appendEmptyExpansion()};if(!state2.escaping&&char==="`")return{nextReduction:reducers.expansionCommandTick,nextState:state2.appendChar(char).appendEmptyExpansion()};return{nextReduction:reducers.start,nextState:state2.appendChar(char).setEscaping(!1)}}module.exports={inherits:"posix",init:(posixMode)=>{let phaseCatalog=posixMode.phaseCatalog,lexerPhases=[convertToWord,phaseCatalog.parameterExpansion,phaseCatalog.arithmeticExpansion,phaseCatalog.commandExpansion,phaseCatalog.tildeExpanding,phaseCatalog.parameterExpansion.resolve,phaseCatalog.commandExpansion.resolve,phaseCatalog.arithmeticExpansion.resolve,phaseCatalog.fieldSplitting.split,phaseCatalog.pathExpansion,phaseCatalog.quoteRemoval,phaseCatalog.defaultNodeType],reducers=Object.assign({},posixMode.tokenizer.reducers,{start});return Object.assign({},posixMode,{lexerPhases,tokenizer:()=>posixMode.tokenizer({},reducers)})}}});var require_src=__commonJS((exports,module)=>{var shellLexer=require_shell_lexer(),utils=require_utils(),modes={bash:require_bash(),posix:require_posix(),"word-expansion":require_word_expansion()};function loadPlugin(name){let modePlugin=modes[name];if(modePlugin.inherits)return modePlugin.init(loadPlugin(modePlugin.inherits),utils);return modePlugin.init(null,utils)}module.exports=function(sourceCode,options){try{options=options||{},options.mode=options.mode||"posix";let mode=loadPlugin(options.mode),Parser=mode.grammar.Parser,astBuilder=mode.astBuilder,parser=new Parser;return parser.lexer=shellLexer(mode,options),parser.yy=astBuilder(options),parser.parse(sourceCode)}catch(err){if(err instanceof SyntaxError)throw err;throw Error(err.stack||err.message)}}});function dcIsSwitchClusterText(text){if(text.length===0)return!1;let segments=text.split("/");return segments.length>0&&segments.every((seg)=>/^[A-Za-z]{1,2}$/.test(seg))}function dcScanCmdTokens(args2){let tokens=[],current="",inQuote=!1;for(let ch of args2){if(ch==='"'){inQuote=!inQuote,current+=ch;continue}if(!inQuote&&/[\s,;=]/.test(ch)){if(current.length>0)tokens.push(current);current="";continue}current+=ch}if(current.length>0)tokens.push(current);return tokens}function dcParseWindowsRecursiveDelete(args2){let tokens=dcScanCmdTokens(args2),fires=tokens.some((token)=>{let inQuote=!1,slashIdx=-1;for(let i=0;i<token.length;i+=1){if(token[i]==='"'){inQuote=!inQuote;continue}if(!inQuote&&token[i]==="/"){slashIdx=i;break}}if(slashIdx<0)return!1;let afterSlash=token.slice(slashIdx+1),quoteIdx=afterSlash.indexOf('"'),switchText=(quoteIdx>=0?afterSlash.slice(0,quoteIdx):afterSlash).replace(/["']/g,"");return dcIsSwitchClusterText(switchText)&&switchText.replace(/\//g,"").toLowerCase().includes("s")}),targets=[];for(let token of tokens){let inQuote=!1,slashIdx=-1;for(let i=0;i<token.length;i+=1){if(token[i]==='"'){inQuote=!inQuote;continue}if(!inQuote&&token[i]==="/"){slashIdx=i;break}}if(slashIdx<0){targets.push(token.replace(/["']/g,""));continue}let afterSlash=token.slice(slashIdx+1),quoteIdx=afterSlash.indexOf('"'),switchText=(quoteIdx>=0?afterSlash.slice(0,quoteIdx):afterSlash).replace(/["']/g,""),prefix=token.slice(0,slashIdx).replace(/["']/g,"").trim();if(!dcIsSwitchClusterText(switchText)){if(fires&&prefix.length>0)targets.push(prefix);continue}if(!switchText.replace(/\//g,"").toLowerCase().includes("s")){if(fires&&prefix.length>0)targets.push(prefix);continue}if(prefix.length>0)targets.push(prefix);if(quoteIdx>=0){let rest=afterSlash.slice(quoteIdx).replace(/["']/g,"").trim();if(rest.length>0)targets.push(rest)}}return{fires,targets}}import*as path58 from"node:path";function unsafeShellCommandTextReason(value){return unsafePathTextReason(value.replace(/[\r\n]/g,""))}function mergeWriteAnalyses(primary,additional,additionalIsAuthoritative=!0,wrapperDeclared=!1){if(additional.writes.length===0&&!additional.hasWrites)return primary;let posixAuthoritative=wrapperDeclared?!1:!additionalIsAuthoritative||!primary.parseError,authority=posixAuthoritative?primary:additional,supplementary=posixAuthoritative?additional:primary,authorityConstructs=new Set(authority.writes.map((write)=>`${write.category}|${write.operator}`)),authorityKeys=new Set(authority.writes.map((write)=>buildDedupeKey(write.category,write.operator,write.path))),stripQuotes=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),isQuoteArtifact=(write)=>{let stripped=stripQuotes(write.path);if(stripped===write.path)return!1;return authority.writes.some((other)=>other.category===write.category&&other.operator===write.operator&&stripQuotes(other.path)===stripped)},keptIndex=new Map,writes=[],demoteKept=(key)=>{let index=keptIndex.get(key);if(index!==void 0)writes[index]=withoutEmptyDirectoryRemoval(writes[index])};for(let write of[...authority.writes,...supplementary.writes]){let key=buildDedupeKey(write.category,write.operator,write.path);if(supplementary.writes.includes(write))if(wrapperDeclared){let construct=`${write.category}|${write.operator}`;if(authorityConstructs.has(construct))continue}else{if(authorityKeys.has(key)){demoteKept(key);continue}if(isQuoteArtifact(write))continue}if(keptIndex.has(key)){demoteKept(key);continue}keptIndex.set(key,writes.length),writes.push(write)}return{writes,hasWrites:writes.length>0||primary.hasWrites||additional.hasWrites,parseError:primary.parseError}}function buildDedupeKey(category,operator,path59){return`${category}|${operator}|${path59??"null"}`}function withoutEmptyDirectoryRemoval(write){if(write.emptyDirectoryRemoval!==!0)return write;let{emptyDirectoryRemoval:_dropped,...rest}=write;return rest}function isBareRmdirOperand(word){return BARE_RMDIR_OPERAND.test(word)&&!word.split("/").includes("..")}function unquotedWordTokens(command){let tokens=[],current="",quote=null,flush=()=>{if(current.length>0)tokens.push(current);current=""};for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote){if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"){flush(),quote=ch;continue}if(/\s/.test(ch)){flush();continue}current+=ch}return flush(),tokens.map((token)=>token.replace(/^[({]+/,"").replace(/[)}]+$/,""))}function isPowerShellShaped(command){if(!command)return!1;return unquotedWordTokens(command).some((token)=>{let lower=token.toLowerCase();return POWERSHELL_WRITE_CMDLETS.has(lower)||POWERSHELL_READ_ONLY_COMMANDS.has(lower)})}function isReadOnlyScriptBlockBody(body){if(/[()[\]=@|`;]/.test(body)||body.includes("::")||body.includes("$("))return!1;let tokens=body.match(/"[^"]*"|'[^']*'|\S+/g)?.map((token)=>token.replace(/^[({]+/,"").replace(/[)}]+$/,""))??[];if(tokens.length===0)return!1;for(let token of tokens){if(token===",")continue;if(/^(?:"[^"]*"|'[^']*')$/.test(token))continue;if(/^-?\d+(?:\.\d+)?$/.test(token))continue;if(READ_ONLY_SCRIPT_BLOCK_OPERATORS.has(token.toLowerCase()))continue;if(/^(?:\$_|\$this)(?:\.[A-Za-z_]\w*)*$/.test(token))continue;return!1}return!0}function extractScriptBlockBodies(command){let bodies=[],depth=0,start=-1,quote=null;for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote){if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch==="{"){if(depth===0)start=i+1;depth+=1;continue}if(ch==="}"){if(depth-=1,depth<0)return null;if(depth===0&&start>=0)bodies.push(command.slice(start,i)),start=-1}}if(quote!==null||depth!==0)return null;return bodies}function isPowerShellReadOnlyPipeline(command){if(!command)return!1;if(/[>;&`\r\n]/.test(command)||/\$\(/.test(command))return!1;let quote=null,braceDepth=0;for(let ch of command){if(quote){if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch==="{")braceDepth+=1;if(ch==="}")braceDepth-=1;if(braceDepth<0)return!1}if(quote!==null||braceDepth!==0)return!1;for(let token of unquotedWordTokens(command)){let lower=token.toLowerCase();if(POWERSHELL_WRITE_CMDLETS.has(lower)||AMBIGUOUS_WRITE_ALIASES.has(lower)||POSIX_WRITE_TOKENS.has(lower))return!1;if((token==="sed"||token==="perl"||token==="awk")&&/(^|[\s'"])--?[a-zA-Z-]*(?:\bi|\bin-place|\bpi)\b/.test(command))return!1}let bodies=extractScriptBlockBodies(command);if(bodies===null)return!1;for(let body of bodies)if(!isReadOnlyScriptBlockBody(body))return!1;let segments=[],current="";quote=null;for(let i=0;i<command.length;i+=1){let ch=command[i];if(quote){if(ch===quote)quote=null;current+=ch;continue}if(ch==='"'||ch==="'"){quote=ch,current+=ch;continue}if(ch==="|"){segments.push(current),current="";continue}current+=ch}segments.push(current);for(let segment of segments){let tokens=unquotedWordTokens(segment.trim());if(tokens.length===0)return!1;if(!POWERSHELL_READ_ONLY_COMMANDS.has(tokens[0].toLowerCase()))return!1}return segments.length>0}function detectProcessSubstitutionWrites(command){let results=[],writeProcSubPattern=/>\s*\(([^)]+)\)/g;while(!0){let match=writeProcSubPattern.exec(command);if(match===null)break;let innerCommand=match[1].trim();if(!innerCommand)continue;let stages=innerCommand.split("|").map((s)=>s.trim());for(let stage of stages){let builtinResult=detectBuiltinWritesFromString(stage);if(builtinResult)results.push(builtinResult);let appendMatch=stage.match(/^\s*(.*?)\s*>>(\s*)(\S+)\s*$/);if(appendMatch){let path59=appendMatch[3];if(path59&&!isNullDevice(path59))results.push({category:"redirect",operator:">>",path:path59})}else{let writeMatch=stage.match(/^\s*(.*?)\s*>(?!>)(\s*)(\S+)\s*$/);if(writeMatch){let path59=writeMatch[3];if(path59&&!isNullDevice(path59))results.push({category:"redirect",operator:">",path:path59})}}}}return results}function detectBuiltinWritesFromString(cmd){let tokens=cmd.trim().split(/\s+/);if(tokens.length===0)return null;let leaf=detectorCommandLeafFromWords(tokens[0],tokens.slice(1)),name=detectorSetMember(leaf,BUILTIN_WRITE_COMMANDS);if(!name)return null;if(name==="rmdir"&&dcParseWindowsRecursiveDelete(cmd).fires)return null;for(let i=tokens.length-1;i>=1;i--)if(!tokens[i].startsWith("-"))return{category:"builtin_write",operator:name,path:tokens[i]};return null}function wordText(node){if(!node||typeof node!=="object")return null;if(isBashWord(node)){let raw=RAW_WORD_TEXT.get(node);if(raw!==void 0){let expansions=node.expansion;if(!Array.isArray(expansions)||expansions.length===0){let{projection,dequoted}=scanQuoting(raw);if(dequoted.length>node.text.length&&dequoted.startsWith(node.text)&&dequoted[node.text.length]==="#"&&projection[node.text.length]!=="\x00")return dequoted}}return node.text}return null}function isBashWord(node){return!!node&&typeof node==="object"&&node.type==="Word"&&typeof node.text==="string"}function annotateRawWordText(node,source){let unitIndex=null;if(/[\uD800-\uDFFF]/.test(source)){unitIndex=[];let u=0;for(let cp2 of source)unitIndex.push(u),u+=cp2.length;unitIndex.push(u)}let toUnit=(cp2)=>unitIndex===null?cp2:unitIndex[cp2],stack=[node],seen=new Set;while(stack.length>0){let n=stack.pop();if(!n||typeof n!=="object"||seen.has(n))continue;if(seen.add(n),isBashWord(n)){let loc=n.loc,start=loc?.start?.char,end=loc?.end?.char;if(typeof start==="number"&&typeof end==="number"&&end>=start){let from=toUnit(start),to=toUnit(end+1);if(from!==void 0&&to!==void 0)RAW_WORD_TEXT.set(n,source.slice(from,to))}}for(let value of Object.values(n))if(value&&typeof value==="object")stack.push(value)}}function hasUnquotedGlob(word){let projection=unquotedProjection(word);return projection===null||/[*?[]/.test(projection)}function hasUnquotedBraceExpansion(word,text){let projection=unquotedProjection(word);return BRACE_EXPANSION.test(projection===null?text:projection)}function unquotedProjection(word){if(!word||typeof word!=="object")return null;let raw=RAW_WORD_TEXT.get(word);if(raw===void 0)return null;let{projection,dequoted}=scanQuoting(raw),hasExpansion=Array.isArray(word.expansion)&&(word.expansion.length??0)>0,text=word.text;if(!hasExpansion&&dequoted!==text&&decodeParserEscapes(dequoted)!==text)return null;return projection}function scanQuoting(raw){let state2="none",projection="",dequoted="";for(let c=0;c<raw.length;c++){let ch=raw[c];if(state2==="single")if(ch==="'")state2="none";else dequoted+=ch,projection+="\x00";else if(ch==="\\"){let next=raw[c+1]??"";if(state2==="double"&&!/[$`"\\\n]/.test(next)){dequoted+=ch,projection+="\x00";continue}if(next!==`
|
|
750
|
+
`)dequoted+=next,projection+="\x00";c++}else if(ch==='"')state2=state2==="double"?"none":"double";else if(state2==="none"&&ch==="'")state2="single";else dequoted+=ch,projection+=state2==="none"?ch:"\x00"}return{projection,dequoted}}function decodeParserEscapes(s){return s.replace(/\\(?:x([0-9A-Fa-f]{2})|u([0-9A-Fa-f]{4})|U([0-9A-Fa-f]{8})|([0-7]{1,3})|([\\tnrbfv"']))/g,(m,x,u,big,octal,c)=>{let hex3=x??u??big;if(hex3!==void 0){let cp2=Number.parseInt(hex3,16);return cp2<=1114111?String.fromCodePoint(cp2):m}if(octal!==void 0)return String.fromCodePoint(Number.parseInt(octal,8));return PARSER_CHAR_ESCAPES[c]??c})}function collectLeafCommands(node,out){if(!node||typeof node!=="object")return;switch(node.type){case"Script":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"Pipeline":case"Sequence":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"CompoundList":if(out.push(node),Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"LogicalExpression":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"And":case"Or":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"Subshell":if(out.push(node),node.list)collectLeafCommands(node.list,out);break;case"ProcessSubstitution":{let opNode=node.op;if(opNode&&typeof opNode==="object"){if(opNode.type?.toUpperCase()==="GREAT"){if(node.command)collectLeafCommands(node.command,out)}}}break;case"If":if(out.push(node),node.clause)collectLeafCommands(node.clause,out);if(node.then)collectLeafCommands(node.then,out);if(node.else)collectLeafCommands(node.else,out);break;case"While":case"Until":if(out.push(node),node.clause)collectLeafCommands(node.clause,out);if(node.do)collectLeafCommands(node.do,out);break;case"For":if(out.push(node),node.do)collectLeafCommands(node.do,out);break;case"Case":if(out.push(node),Array.isArray(node.cases)){for(let entry of node.cases)if(entry?.body)collectLeafCommands(entry.body,out)}break;case"Function":if(out.push(node),node.body)collectLeafCommands(node.body,out);break;default:out.push(node);break}}function getCommandName(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(typeof c.name==="string")return c.name;return wordText(c.name)}function basenameAnySep(word){return basenameAnySepCase(word).toLowerCase()}function basenameAnySepCase(word){return(word.split(/[\\/]/).filter(Boolean).pop()??word).replace(/\.exe$/i,"")}function envFlagConsumesNextWord(token){if(token.startsWith("--")){if(ENV_FLAGS_WITH_ARG.has(token))return!0;if(token.length<3)return!1;return[...ENV_FLAGS_WITH_ARG].filter((flag)=>flag.startsWith("--")&&flag.startsWith(token)).length===1}if(token.startsWith("-")&&token.length>2){let chars=token.slice(1).split(""),argTaking=["u","U","C","S","a","P"];return chars.findIndex((c)=>argTaking.includes(c))===chars.length-1&&chars.slice(0,-1).every((c)=>!argTaking.includes(c))}return ENV_FLAGS_WITH_ARG.has(token)}function canonicalInterpreterName(cmd){let name=getCommandName(cmd);if(!name)return null;let words=[name,...getSuffixWords(cmd)],i=0;for(let hop=0;hop<words.length;hop++){let base=basenameAnySep(words[i]??"");if(base!=="env"&&base!=="command"&&base!=="exec")break;if(i+=1,base==="env")while(i<words.length){let token=words[i];if(token===void 0)break;if(envFlagConsumesNextWord(token)){i+=2;continue}if(token.startsWith("-")){i+=1;continue}if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){i+=1;continue}break}else while(i<words.length){let token=words[i];if(token===void 0)break;if(token==="-a"||token==="--arg0"){i+=2;continue}if(token.startsWith("-")){i+=1;continue}break}if(i>=words.length)return null}let word=words[i];if(word===void 0)return null;let full=basenameAnySep(word);if(INTERPRETER_EVAL_COMMANDS.has(full))return full;let stripped=full.replace(/\d+(\.\d+)*$/,"");if(stripped!==""&&stripped!==full&&INTERPRETER_EVAL_COMMANDS.has(stripped))return stripped;return null}function rawSuffixWords(cmd){let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let words=[];for(let s of suffix){if(!isBashWord(s))continue;let raw=RAW_WORD_TEXT.get(s);if(raw===void 0)return null;words.push(raw)}return words}function getSuffixWords(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let words=[];for(let s of suffix){let text=wordText(s);if(text!==null)words.push(text)}return words}function isQueryFlag(token){if(token==="-v"||token==="-V")return!0;return/^-[pvVP]+$/.test(token)&&/[vV]/.test(token)}function detectorCommandLeaf(cmd){return detectorCommandParts(cmd).leaf}function detectorCommandRawLeaf(cmd){return detectorCommandPartsFromWords(getCommandName(cmd),getSuffixWords(cmd)).rawLeaf}function detectorCommandParts(cmd){let suffix=getSuffixWords(cmd);return{leaf:detectorCommandLeafFromWords(getCommandName(cmd),suffix),rest:suffix}}function detectorCommandLeafFromWords(cmdName,suffix){return detectorCommandPartsFromWords(cmdName,suffix).leaf}function detectorCommandPartsFromWords(cmdName,suffix){let name=cmdName;if(!name)return{leaf:"",rest:suffix,rawLeaf:""};let cursor=0;for(let hop=0;hop<8;hop++){let base=basenameAnySep(name),rawBase=basenameAnySepCase(name);if(base!=="env"&&base!=="command"&&base!=="builtin"&&base!=="exec")return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase};if(base==="env")while(cursor<suffix.length){let token=suffix[cursor];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){cursor++;continue}if(token.startsWith("-")&&token!=="-"){if(cursor++,envFlagConsumesNextWord(token)&&cursor<suffix.length)cursor++;continue}break}else if(base==="command"){while(cursor<suffix.length&&suffix[cursor]==="-p")cursor++;if(cursor<suffix.length&&isQueryFlag(suffix[cursor]))return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase};if(cursor<suffix.length&&suffix[cursor]==="--")cursor++}else if(base==="builtin"){if(cursor<suffix.length){let wrapped=basenameAnySep(suffix[cursor]);if(!BASH_BUILTIN_COMMANDS.has(wrapped))return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase}}if(cursor<suffix.length&&suffix[cursor]==="--")cursor++}else if(base==="exec"){while(cursor<suffix.length&&/^-[cl]$/.test(suffix[cursor]))cursor++;if(cursor<suffix.length&&suffix[cursor]==="-a")cursor+=2;if(cursor<suffix.length&&/^-a\S+$/.test(suffix[cursor]))cursor++;if(cursor<suffix.length&&/^-[cl]{2,}$/.test(suffix[cursor]))cursor++;if(cursor<suffix.length&&suffix[cursor]==="--")cursor++}if(cursor>=suffix.length)return{leaf:base,rest:suffix.slice(cursor),rawLeaf:rawBase};if(name=suffix[cursor],cursor++,!name)return{leaf:base,rest:suffix.slice(cursor-1),rawLeaf:rawBase}}return{leaf:basenameAnySep(name),rest:suffix.slice(cursor),rawLeaf:basenameAnySepCase(name)}}function detectorSetMember(leaf,set2){if(leaf&&set2.has(leaf))return leaf;let dotted2=leaf.replace(/\.\d+(\.\d+)*$/,"");if(dotted2!==leaf&&set2.has(dotted2))return dotted2;let stripped=dotted2.replace(/\d+(\.\d+)*$/,"");if(stripped!==dotted2&&set2.has(stripped))return stripped;return null}function getSuffixWordExpansionFlags(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let flags=[];for(let s of suffix){if(!isBashWord(s))continue;let expansion=s.expansion;flags.push(Array.isArray(expansion)&&expansion.length>0)}return flags}function getSuffixWordUnquotedExpansionFlags(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];let flags=[];for(let s of suffix){if(!isBashWord(s))continue;let expansion=s.expansion;if(!Array.isArray(expansion)||expansion.length===0){flags.push(!1);continue}let text=s.text,hasSubstitution=/\$\(|`/.test(text),hasListExpansion=/\$\{?[!#]?[A-Za-z0-9_]*(?:\[[@*]\]|@|\*)/.test(text)||/\$\{?[!#]?[@*]|\[[@*]\]/.test(text);if(hasSubstitution||hasListExpansion){flags.push(!0);continue}let quotedAt=[],state2="none";for(let c=0;c<text.length;c++){let ch=text[c];if(quotedAt[c]=state2!=="none",state2==="single"){if(ch==="'")state2="none"}else if(ch==="\\")quotedAt[c+1]=!0,c++;else if(ch==='"')state2=state2==="double"?"none":"double";else if(ch==="'"&&state2==="none")state2="single"}flags.push(expansion.some((e)=>{let start=e.loc?.start;return typeof start!=="number"||quotedAt[start]!==!0}))}return flags}function getRedirections(cmd){if(!cmd||typeof cmd!=="object")return[];let c=cmd;if(Array.isArray(c.redirections))return c.redirections;let results=[],suffix=c.suffix,prefix=c.prefix;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item))results.push(item)}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item))results.push(item)}return results}function isRedirectNode(node){return!!(node&&typeof node==="object"&&node.type==="Redirect")}function operatorLabel(op){if(!op||typeof op!=="object")return"unknown";let opType=op.type?.toUpperCase();switch(opType){case"GREAT":return">";case"DGREAT":return">>";case"CLOBBER":return">|";case"LESS":return"<";case"DLESS":return"<<";case"DLESSDASH":return"<<-";case"LESSAND":return"<&";case"GREATAND":return">&";case"LESSGREAT":return"<>";default:return opType||"unknown"}}function extractRedirectPath(fileNode){let text=wordText(fileNode);if(!text)return null;return text}function isNullDevice(path59){return path59==="/dev/null"||path59==="/dev/zero"||path59==="/dev/urandom"}function isNullDeviceWord(word,path59){if(!isNullDevice(path59)||!word||typeof word!=="object")return!1;let raw=RAW_WORD_TEXT.get(word);return raw!==void 0&&isNullDevice(scanQuoting(raw).dequoted)}function isNumeric(s){return/^\d+$/.test(s)}function isNonFileGreatAndTarget(path59){return path59!==null&&(isNumeric(path59)||path59==="-")}function detectRedirects(cmd){let results=[];results.push(...detectHereDocMarkers(cmd));let redirections=getRedirections(cmd);for(let redirect of redirections){if(!redirect||typeof redirect!=="object")continue;let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")continue;let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))continue;let fileNode=r.file,path59=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path59)){if(path59!==null&&isNullDeviceWord(fileNode,path59))continue;results.push({category:"redirect",operator:opLabel,path:path59})}else if(REDIRECT_HERE_TOKENS.has(opType))results.push({category:"here_doc",operator:opLabel,path:path59})}return results}function detectHereDocMarkers(cmd){let results=[];if(!cmd||typeof cmd!=="object")return results;let suffix=cmd.suffix;if(!Array.isArray(suffix))return results;for(let item of suffix){if(!item||typeof item!=="object")continue;if(isHereDocMarker(item))results.push({category:"here_doc",operator:item.text==="<<-"?"<<-":"<<",path:null})}return results}function isHereDocMarker(node){if(!node||typeof node!=="object")return!1;let type=node.type?.toLowerCase();return type==="dless"||type==="dlessdash"}function detectBuiltinWrites(cmd){let results=[];if(!getCommandName(cmd))return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,BUILTIN_WRITE_COMMANDS)??(leaf==="dd"||leaf==="tee"?leaf:null);if(!lowerName)return results;let dedupeOperator=detectorCommandRawLeaf(cmd);if(lowerName==="dd"){let suffixWords2=getSuffixWords(cmd);for(let word of suffixWords2)if(word.startsWith("of=")){let path59=word.slice(3);if(path59&&!isNullDevice(path59))results.push({category:"builtin_write",operator:"dd of=",path:path59})}return results}if(lowerName==="tee"){let suffixWords2=getSuffixWords(cmd),pastDoubleDash=!1;for(let word of suffixWords2){if(word==="--"){pastDoubleDash=!0;continue}if(!pastDoubleDash&&word.startsWith("-"))continue;if(word&&!isNullDevice(word))results.push({category:"builtin_write",operator:"tee",path:word})}return results}if(!BUILTIN_WRITE_COMMANDS.has(lowerName))return results;let rawWords=rawSuffixWords(cmd);if(lowerName==="rmdir"&&rawWords!==null&&dcParseWindowsRecursiveDelete(rawWords.join(" ")).fires)return results;let suffixWords=getSuffixWords(cmd);if(lowerName==="rmdir"&&suffixWords.length===1&&isBareRmdirOperand(suffixWords[0]))return results.push({category:"builtin_write",operator:dedupeOperator,path:suffixWords[0],emptyDirectoryRemoval:!0}),results;if(lowerName==="truncate"){for(let word of suffixWords)if(!word.startsWith("-")&&!isNumeric(word)){results.push({category:"builtin_write",operator:"truncate",path:word});break}}else for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"builtin_write",operator:dedupeOperator,path:word});break}}return results}function looksLikeSedScript(w){if(hasParentComponent(w)||/^[A-Za-z]:[\\/]/.test(w))return!1;return/^(?:(?:[0-9]+|\$)(?:,(?:[0-9]+|\$))?!?|!)[a-zA-Z=]$/.test(w)||/[;{}]/.test(w)&&!/[\\/:]/.test(w)&&!w.startsWith(".")||/^s([^A-Za-z0-9\s\\])(?:\\.|(?!\1)[^\\])*\1(?:\\.|(?!\1)[^\\])*\1[gpiImMe0-9]*$/.test(w)||/^y([^A-Za-z0-9\s\\])(?:\\.|(?!\1)[^\\])*\1(?:\\.|(?!\1)[^\\])*\1$/.test(w)}function hasParentComponent(w){return w.split(/[\\/]/).includes("..")}function detectInplaceEdit(cmd){let results=[];if(!getCommandName(cmd))return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,INPLACE_EDIT_COMMANDS);if(!lowerName)return[];let suffixWords=getSuffixWords(cmd);if(!suffixWords.some((word)=>{if(lowerName==="sed")return word.startsWith("-i")&&word.length>1||/^--i(?:n(?:-(?:p(?:l(?:a(?:c(?:e)?)?)?)?)?)?)?(?:=|$)/.test(word);return word==="-i"||word.startsWith("-i")}))return[];let scriptPattern=/^[ssy]\/.*\/[gim]*$/,quotedScriptPattern=/^["'].*["']$/,isScriptShaped=(w)=>scriptPattern.test(w)&&!hasParentComponent(w),isScriptWord=(i)=>{let w=suffixWords[i];if(quotedScriptPattern.test(w))return unquotedExpansionFlags[i]!==!0&&isScriptShaped(w.slice(1,-1));return isScriptShaped(w)},flagArgs=lowerName==="sed"?new Set(["-e","-f","--expression","--file"]):lowerName==="perl"?new Set(["-e","-E"]):new Set(["-f","-e","-v","-F"]),combinedFlagArgs=/^-[0-9AacSlnpstTuUwWX]+[eE]$/,perlAttachedScript=/^-[0-9AacSlnpstTuUwWX]*[eE]./,sedScriptBundle=/^-[nrEszub]*[ef]$/,sedAttachedScript=/^-[nrEszub]*[ef]./,consumesNext=(w)=>flagArgs.has(w)||lowerName==="sed"&&sedScriptBundle.test(w)||lowerName==="perl"&&combinedFlagArgs.test(w),suppliesScript=(w)=>{if(lowerName==="awk")return w==="-f"||w==="-e"||/^-[fe]./.test(w)||w.startsWith("--file=")||w.startsWith("--source=");if(lowerName==="sed")return consumesNext(w)||sedAttachedScript.test(w)||/^--(?:expression|file)=/.test(w);return consumesNext(w)||perlAttachedScript.test(w)},expansionFlags=getSuffixWordExpansionFlags(cmd),unquotedExpansionFlags=getSuffixWordUnquotedExpansionFlags(cmd),suffixNodes=(Array.isArray(cmd.suffix)?cmd.suffix:[]).filter((s)=>wordText(s)!==null),mayExpandToSeveralWords=(i)=>unquotedExpansionFlags[i]===!0||hasUnquotedBraceExpansion(suffixNodes[i],suffixWords[i]),isKnownOption=(w)=>{if(w==="-"||w==="--")return!0;if(lowerName==="sed")return/^-[nrEszub]+$/.test(w)||/^-[nrEszub]*[ef]/.test(w)||/^-[nrEszub]*l/.test(w)||/^-i/.test(w)||SED_LONG_SWITCHES.has(w)||/^--(?:expression|file|line-length|in-place)(?:=|$)/.test(w);if(lowerName==="perl")return/^-[0-9AacSlnpstTuUwWX]*(?:[eE].*)?$/.test(w)||/^-i/.test(w)||/^-I./.test(w);return/^-[fevFil]/.test(w)||/^-[PcrSVh]$/.test(w)||AWK_LONG_SWITCHES.has(w)||/^--(?:file|source|lint)=/.test(w)},isOpaqueFlag=(i)=>suffixWords[i].startsWith("-")&&(mayExpandToSeveralWords(i)||!isKnownOption(suffixWords[i])),sedOptionArg=(w)=>lowerName==="sed"&&(/^-[nrEszub]*l$/.test(w)||w==="--line-length"),takesDetachedArg=(w)=>consumesNext(w)||sedOptionArg(w)||lowerName==="awk"&&w==="-i",fileArgOption=(w)=>lowerName==="sed"&&(/^-[nrEszub]*f$/.test(w)||w==="--file")||lowerName==="awk"&&(w==="-f"||w==="-i"),detachedArgMaySplit=(option,i)=>mayExpandToSeveralWords(i)||(fileArgOption(option)?/[*?[]/.test(suffixWords[i]):hasUnquotedGlob(suffixNodes[i])),permutes=lowerName==="sed",operandsFrom=suffixWords.length,optionArgs=new Set,expandingOptionArgs=new Set;for(let i=0;i<suffixWords.length;i++){let w=suffixWords[i];if(w==="--"){if(!permutes)operandsFrom=i+1;break}if(!w.startsWith("-")){if(!permutes){operandsFrom=i;break}continue}if(isOpaqueFlag(i)){if(!permutes){operandsFrom=i+1;break}continue}if(!takesDetachedArg(w))continue;if(i+1<suffixWords.length){if(optionArgs.add(i+1),detachedArgMaySplit(w,i+1)){if(expandingOptionArgs.add(i+1),!permutes){operandsFrom=i+2;break}}}i++}let inOptionArea=(i)=>i<operandsFrom,hasExplicitScript=!1;for(let i=0;i<suffixWords.length&&inOptionArea(i);i++){if(optionArgs.has(i))continue;let w=suffixWords[i];if(w==="--")break;if(!w.startsWith("-")||isOpaqueFlag(i))continue;if(expandingOptionArgs.has(i+1)){i++;continue}if(suppliesScript(w)){hasExplicitScript=!0;break}if(consumesNext(w)||lowerName==="awk"&&w==="-i")i++}let skipIndices=new Set,isDetachedSuffix=(w)=>lowerName==="sed"&&w!==void 0&&(w===""||w.startsWith(".")),isLiteralWord=(i)=>expansionFlags[i]!==!0&&!/[*?[]/.test(suffixWords[i])&&!/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(suffixWords[i]),isLiteralSedScript=(i)=>isLiteralWord(i)&&looksLikeSedScript(suffixWords[i]),isReportableWord=(i)=>suffixWords[i]!==""&&!isScriptWord(i)&&!isLiteralSedScript(i),firstPositionalFrom=(from)=>{let j=from;while(j<suffixWords.length&&(inOptionArea(j)&&suffixWords[j].startsWith("-")||optionArgs.has(j)))j++;return j},dashDash=suffixWords.findIndex((w,i)=>w==="--"&&!optionArgs.has(i)&&inOptionArea(i)),hasOpaqueFlag=suffixWords.some((_w,i)=>(dashDash<0||i<dashDash)&&inOptionArea(i)&&!optionArgs.has(i)&&isOpaqueFlag(i)),implicitScriptPlaced=hasOpaqueFlag||expandingOptionArgs.size>0;if(lowerName==="sed"&&!hasExplicitScript&&!implicitScriptPlaced)for(let i=0;i<suffixWords.length;i++){if(optionArgs.has(i))continue;let w=suffixWords[i];if(w==="--"||w.startsWith("-i")||w.startsWith("--in-place"))break;if(w.startsWith("-"))continue;if(!mayExpandToSeveralWords(i))skipIndices.add(i);implicitScriptPlaced=!0;break}let consumeImplicitScript=(from,bareInplace)=>{if(implicitScriptPlaced)return;implicitScriptPlaced=!0;let j=firstPositionalFrom(from);if(j>=suffixWords.length||mayExpandToSeveralWords(j))return;if(skipIndices.add(j),!bareInplace||!isDetachedSuffix(suffixWords[j]))return;let k=firstPositionalFrom(j+1);if(k>=suffixWords.length||!isLiteralSedScript(k))return;for(let m=firstPositionalFrom(k+1);m<suffixWords.length;){if(isReportableWord(m)){skipIndices.add(k);return}m=firstPositionalFrom(m+1)}},isConventionalBackupSuffix=(w)=>isDetachedSuffix(w)&&!w.includes("/")&&/^\.(?:bak|orig|old|save|backup|tmp|swp|~)$/i.test(w),dotWordAfterBareInplace=null,pastDoubleDash=!1,awkProgramSeen=!1;for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(optionArgs.has(i)){if(!expandingOptionArgs.has(i))skipIndices.add(i);continue}if(!pastDoubleDash&&word==="--"&&inOptionArea(i)){skipIndices.add(i),pastDoubleDash=!0;continue}if(!pastDoubleDash&&inOptionArea(i)&&word.startsWith("-")){if(isOpaqueFlag(i))continue;skipIndices.add(i);let next=suffixWords[i+1];if(lowerName==="sed"&&(word==="--in-place"||word.startsWith("--in-place="))){if(!hasExplicitScript)consumeImplicitScript(i+1,!1);continue}if(word==="-i"){if(next===void 0)continue;if(lowerName==="awk"){if(!expandingOptionArgs.has(i+1))skipIndices.add(i+1)}else if(!hasExplicitScript)consumeImplicitScript(i+1,!0);else if(isConventionalBackupSuffix(next))skipIndices.add(i+1),dotWordAfterBareInplace=next;continue}if(/^-i.+/.test(word)){if(lowerName!=="awk"&&!hasExplicitScript)consumeImplicitScript(i+1,!1);continue}if(consumesNext(word)||sedOptionArg(word)){if(next!==void 0&&!expandingOptionArgs.has(i+1))skipIndices.add(i+1)}continue}if(skipIndices.has(i))continue;if(lowerName==="awk"){if(!hasExplicitScript&&!hasOpaqueFlag&&expandingOptionArgs.size===0&&!awkProgramSeen)awkProgramSeen=!0,skipIndices.add(i);continue}if(isScriptWord(i))skipIndices.add(i)}let candidates=suffixWords.map((word,i)=>({word,i})).filter(({word,i})=>word!==""&&!skipIndices.has(i));if(candidates.length===0&&dotWordAfterBareInplace!==null)candidates.push({word:dotWordAfterBareInplace,i:-1});if(candidates.length>0)for(let{word}of candidates)results.push({category:"inplace_edit",operator:`${lowerName} -i`,path:word});return results}function classifyPipeStdinEval(node){if(!node||typeof node!=="object")return null;let pipeline=node;if(pipeline.type!=="Pipeline"||!Array.isArray(pipeline.commands))return null;if(pipeline.commands.length<2)return null;for(let pos=pipeline.commands.length-1;pos>=1;pos--){let evalWrite=classifyPipeStdinEvalAt(node,pos);if(evalWrite)return evalWrite}return null}function classifyPipeStdinEvalAt(node,pos){let pipeline=node;if(!Array.isArray(pipeline.commands))return null;let last=pipeline.commands[pos],canonical=detectorSetMember(detectorCommandLeaf(last),INTERPRETER_EVAL_COMMANDS);if(!canonical||canonical==="eval")return null;let{leaf:_leaf,rest}=detectorCommandPartsFromWords(getCommandName(last),getSuffixWords(last));if(!(rest.length===0||rest.length===1&&rest[0]==="-"))return null;for(let r of getRedirections(last)){let opType=r.op?.type;if(typeof opType==="string"&&/LESS|HEREDOC/i.test(opType))return null}let rawSuffixNodes=last.suffix;if(Array.isArray(rawSuffixNodes)){for(let node2 of rawSuffixNodes)if(node2&&typeof node2==="object"&&node2.type==="dless")return null}for(let i=0;i<pos;i++){let producer=pipeline.commands[i],leaf=detectorCommandLeaf(producer);if(leaf!=="echo"&&leaf!=="printf")return null;let expansions=getSuffixWordExpansionFlags(producer),words=getSuffixWords(producer);for(let w=0;w<words.length;w++)if(w<expansions.length&&expansions[w])return null;if(getRedirections(producer).length>0)return null}return{category:"interpreter_eval",operator:`${canonical} [eval stdin]`,path:null,capability:!0}}function collectPipeStdinEvals(node,out){if(!node||typeof node!=="object")return;if(Array.isArray(node)){for(let child of node)collectPipeStdinEvals(child,out);return}for(let value of Object.values(node))if(value&&typeof value==="object")collectPipeStdinEvals(value,out);let candidate=classifyPipeStdinEval(node);if(candidate)out.push(candidate)}function detectInterpreterEval(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let canonical=canonicalInterpreterName(cmd);if(!canonical)return[];let suffixWords=getSuffixWords(cmd),evalFlags={python:["-c"],python3:["-c"],python2:["-c"],node:["-e","-p","-pe"],bun:["-e","-p","-pe"],ruby:["-e"],perl:["-e","-E"],php:["-r","-R","-F"],bash:["-c"],sh:["-c"],dash:["-c"],zsh:["-c"],ksh:["-c"]};if(canonical==="eval")return results.push({category:"interpreter_eval",operator:"eval",path:null,capability:!0}),results;let relevantFlags=evalFlags[canonical]??[];if(!suffixWords.some((word)=>relevantFlags.some((f)=>word===f||word.startsWith(f)&&word.length>f.length)))return[];return results.push({category:"interpreter_eval",operator:`${name} [eval]`,path:null,capability:!0}),results}function detectNetworkDownloaders(cmd){let results=[];if(!getCommandName(cmd))return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,NETWORK_DOWNLOAD_COMMANDS);if(!lowerName)return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="curl")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-o"&&i+1<suffixWords.length){let path59=suffixWords[i+1];if(!path59.startsWith("-"))results.push({category:"network_download",operator:"curl -o",path:path59})}else if(word.startsWith("-o")&&word.length>2)results.push({category:"network_download",operator:"curl -o",path:word.slice(2)})}else if(lowerName==="wget")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-O"&&i+1<suffixWords.length){let path59=suffixWords[i+1];if(!path59.startsWith("-"))results.push({category:"network_download",operator:"wget -O",path:path59})}else if(word.startsWith("-O")&&word.length>2)results.push({category:"network_download",operator:"wget -O",path:word.slice(2)})}else if(lowerName==="scp")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")&&(word.includes(":")||word.startsWith("/")||word.startsWith("."))){results.push({category:"network_download",operator:"scp",path:word});break}}return results}function detectArchiveExtract(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let leaf=detectorCommandLeaf(cmd),lowerName=detectorSetMember(leaf,ARCHIVE_EXTRACT_COMMANDS);if(!lowerName)return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="tar"){if(suffixWords.some((word)=>{if(word==="--extract"||word==="--get")return!0;if(word.startsWith("-")&&word.includes("x"))return!0;return!1}))for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"tar -x",path:word});break}if(word.startsWith("--file=")&&word.length>7){results.push({category:"archive_extract",operator:"tar -x",path:word.slice(7)});break}}}else if(lowerName==="unzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"unzip",path:word});break}}else if(lowerName==="gunzip"||lowerName==="gzip"||lowerName==="bzip2"||lowerName==="xz"||lowerName==="7z"||lowerName==="rar"){if(suffixWords.includes("-d")||suffixWords.includes("--decompress")||lowerName==="gunzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:`${name} [decompress]`,path:word});break}}}return results}function detectGitDestructive(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;if(name.toLowerCase()!==GIT_COMMAND)return[];let suffixWords=getSuffixWords(cmd);if(suffixWords.length===0)return[];let first=suffixWords[0].toLowerCase();if(first==="checkout"){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length){let path59=suffixWords[dashDashIdx+1],op=path59==="."?"git checkout -- .":"git checkout --";results.push({category:"git_destructive",operator:op,path:path59})}}else if(first==="restore"){let hasHard=suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")),hasForce=suffixWords.some((w)=>w==="--force"||w==="-f"||w.startsWith("-")&&w.includes("f"));if(hasHard||hasForce){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length)results.push({category:"git_destructive",operator:"git restore",path:suffixWords[dashDashIdx+1]});else results.push({category:"git_destructive",operator:"git restore",path:null})}}else if(first==="reset"){if(suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")))results.push({category:"git_destructive",operator:"git reset --hard",path:null})}else if(first==="clean"){if(suffixWords.some((w)=>w==="-n"||w==="--dry-run"||w.startsWith("-")&&w.includes("n")))return results;let hasForce=suffixWords.some((w)=>w==="-f"||w==="--force"||w.startsWith("-")&&w.includes("f")),hasDir=suffixWords.some((w)=>w==="-d"||w==="--dir"||w.startsWith("-")&&w.includes("d"));if(hasForce&&hasDir)results.push({category:"git_destructive",operator:"git clean -fd",path:null})}return results}function splitWindowsCommands(command,shell){let commands=[],current="",inSingleQuote=!1,inDoubleQuote=!1,parenDepth=0;for(let i=0;i<command.length;i++){let ch=command[i];if(shell==="powershell"&&ch==="'"&&!inDoubleQuote)inSingleQuote=!inSingleQuote;else if(ch==='"'&&!inSingleQuote)inDoubleQuote=!inDoubleQuote;else if(ch==="("&&!inSingleQuote&&!inDoubleQuote)parenDepth++;else if(ch===")"&&!inSingleQuote&&!inDoubleQuote)parenDepth--;if(ch===`
|
|
751
751
|
`&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());current="";continue}if(shell==="powershell"&&(ch===";"||ch==="{"||ch==="}")&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());current="";continue}if(ch==="|"&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());current="";continue}if((ch==="&"||ch==="|")&&i+1<command.length&&command[i+1]===ch&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());commands.push(ch==="&"?"&&":"||"),current="",i++;continue}if(ch==="&"&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(command[i-1]===">"){current+=ch;continue}if(!(i+1<command.length&&command[i+1]==="&")){if(current.trim())commands.push(current.trim());current="";continue}}current+=ch}if(current.trim())commands.push(current.trim());return commands.filter((c)=>c!=="&&"&&c!=="||")}function detectPowerShellRedirects(command){let results=[],inSingleQuote=!1,inDoubleQuote=!1,isBoundary=(character)=>character===void 0||/[\s;|&()]/.test(character);for(let index=0;index<command.length;index++){let character=command[index];if(inSingleQuote){if(character==="'")if(command[index+1]==="'")index++;else inSingleQuote=!1;continue}if(inDoubleQuote){if(character==="`"&&index+1<command.length){index++;continue}if(character==='"')inDoubleQuote=!1;continue}if(character==="'"){inSingleQuote=!0;continue}if(character==='"'){inDoubleQuote=!0;continue}if(character===">"&&command[index-1]==="^")continue;if(character!==">")continue;let operator=command[index+1]===">"?">>":">",cursor=index+operator.length;while(/\s/.test(command[cursor]??""))cursor++;if(command[cursor]==="&"){cursor++;while(/\s/.test(command[cursor]??""))cursor++;let descriptorStart=cursor;while(/\d/.test(command[cursor]??""))cursor++;if(command.slice(descriptorStart,cursor)&&isBoundary(command[cursor])){index=Math.max(index,cursor-1);continue}results.push({category:"redirect",operator,path:null}),index=Math.max(index,cursor-1);continue}let pathValue=null;if(cursor<command.length){let quote=command[cursor];if(quote==='"'||quote==="'"){cursor++;let pathStart=cursor,closed=!1;while(cursor<command.length){if(quote==='"'&&command[cursor]==="`"){cursor+=2;continue}if(command[cursor]===quote){if(quote==="'"&&command[cursor+1]==="'"){cursor+=2;continue}pathValue=command.slice(pathStart,cursor),cursor++,closed=!0;break}cursor++}if(!closed)pathValue=null}else{let pathStart=cursor;while(cursor<command.length&&!/\s|[;|&()<>]/.test(command[cursor]??""))cursor++;if(cursor>pathStart)pathValue=command.slice(pathStart,cursor)}}results.push({category:"redirect",operator,path:pathValue}),index=Math.max(index,cursor-1)}if(inSingleQuote||inDoubleQuote)results.push({category:"redirect",operator:">",path:null});return results}function detectPowerShellWrites(command){let results=[],trimmed=command.trim();if(!trimmed)return results;if(/^(?:powershell|pwsh)(?:\.exe)?\s+/i.test(trimmed)&&/(?:^|\s)-(?:e|ec|enc|encodedcommand)(?=\s|=|$)/i.test(trimmed))return results.push({category:"interpreter_eval",operator:"PowerShell -EncodedCommand",path:null}),results;let innerCommand=trimmed,cmdMatch=trimmed.match(new RegExp(`${PS_STRIP_PREFIX.source}(.*)$`,"i"));if(cmdMatch){if(innerCommand=cmdMatch[1].trim(),innerCommand.startsWith('"')&&innerCommand.endsWith('"')||innerCommand.startsWith("'")&&innerCommand.endsWith("'"))innerCommand=innerCommand.slice(1,-1)}if(/(?:^|[;{}|&])\s*(?:Set-Location|Push-Location|Pop-Location|cd|chdir|sl)\b/i.test(innerCommand))results.push({category:"builtin_write",operator:"working-directory mutation",path:null});if(/[({]\s*(?:Out-File|Set-Content|Add-Content|Clear-Content|Copy-Item|Move-Item|Remove-Item)\b/i.test(innerCommand))results.push({category:"interpreter_eval",operator:"nested PowerShell script block",path:null});if(/(?:^|[;|])\s*&\s*(?:['"$({]|\S+\s*\()/i.test(innerCommand)||/(?:^|[;|])\s*(?:Invoke-Expression|IEX)\b/i.test(innerCommand))results.push({category:"interpreter_eval",operator:"dynamic PowerShell invocation",path:null});results.push(...detectPowerShellRedirects(innerCommand));let iwrMatch=trimmed.match(/^(?:Invoke-WebRequest|curl)\s.*?(?:-OutFile\s+(\S+)|-o\s+(\S+))/i);if(iwrMatch){let path59=iwrMatch[1]||iwrMatch[2];if(path59)results.push({category:"network_download",operator:"Invoke-WebRequest -OutFile",path:path59})}function detectPsContentCmdlet(cmd){let cmdletMatch=cmd.match(/^(Out-File|Set-Content|Add-Content|Clear-Content)\b/i);if(!cmdletMatch)return[];let cmdletName=cmdletMatch[1],rest=cmd.slice(cmdletMatch[0].length).trim(),pathFlagMatch=rest.match(/(?:-Path|-FilePath|-LiteralPath)\s+((?:"[^"]*"|'[^']*'|[^,\s]+)(?:\s*,\s*(?:"[^"]*"|'[^']*'|[^,\s]+))*)/i);if(pathFlagMatch)return pathFlagMatch[1].split(/\s*,\s*/).map((value)=>value.replace(/^(["'])|(["'])$/g,"")).map((path59)=>({category:"redirect",operator:cmdletName,path:path59||null}));if(/(?:-Path|-FilePath|-LiteralPath)(?:\s|$)/i.test(rest))return[{category:"redirect",operator:cmdletName,path:null}];let tokens=rest.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[];for(let token of tokens){if(token.startsWith("-"))continue;let path59=token.replace(/^["']|["']$/g,"");return[{category:"redirect",operator:cmdletName,path:path59}]}return[]}results.push(...detectPsContentCmdlet(innerCommand));let pipeContentMatch=innerCommand.match(/\|\s*(Out-File|Set-Content|Add-Content|Clear-Content)\b\s*(.*)$/i);if(pipeContentMatch){let cmdletName=pipeContentMatch[1],tokens=pipeContentMatch[2].trim().match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[];for(let token of tokens){if(token.startsWith("-"))continue;let path59=token.replace(/^["']|["']$/g,"");if(path59){results.push({category:"redirect",operator:cmdletName,path:path59});break}}}function detectPsFileOp(cmd){let opMatch=cmd.match(/^(Copy-Item|Move-Item|Remove-Item)\b/i);if(!opMatch)return null;let cmdletName=opMatch[1],rest=cmd.slice(opMatch[0].length).trim(),destFlagMatch=rest.match(/-Destination\s+(\S+|"[^"]+"|'[^']+')/i);if(destFlagMatch){let path59=destFlagMatch[1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path59}}let tokens=[],flagTakingValue=new Set(["-Path","-LiteralPath","-Exclude","-Include","-Filter"]),switchFlags=new Set(["-Recurse","-Force","-Confirm","-WhatIf","-PassThru","-Verbose","-Debug"]),parts=rest.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[],i=0;while(i<parts.length){let part=parts[i];if(flagTakingValue.has(part)&&i+1<parts.length){let value=parts[i+1];if(!value.startsWith("-"))tokens.push(value);i+=2}else if(switchFlags.has(part))i++;else if(part.startsWith("-"))i++;else tokens.push(part),i++}if(tokens.length>=2){let path59=tokens[tokens.length-1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path59}}else if(tokens.length===1){let path59=tokens[0].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path59}}return null}function detectPsNewItem(cmd){let opMatch=cmd.match(/^(?:New-Item|ni)\b/i);if(!opMatch)return null;let rest=cmd.slice(opMatch[0].length).trim(),SWITCH_FLAGS=new Set(["-force","-confirm","-whatif"]),VALUE_FLAGS=new Set(["-itemtype","-value","-description"]),PATH_FLAGS=new Set(["-path","-literalpath"]),tokens=rest.match(/"[^"]*"|'[^']*'|\S+/g)??[],unquote=(value)=>value.replace(/^["']|["']$/g,""),pathValue=null,nameValue=null,positional=null;for(let i=0;i<tokens.length;i+=1){let token=tokens[i],flag=token.toLowerCase();if(PATH_FLAGS.has(flag)){pathValue=unquote(tokens[i+1]??""),i+=1;continue}if(flag==="-name"){nameValue=unquote(tokens[i+1]??""),i+=1;continue}if(VALUE_FLAGS.has(flag)){i+=1;continue}if(SWITCH_FLAGS.has(flag))continue;if(flag.startsWith("-"))continue;if(positional===null)positional=unquote(token)}let basePath=(pathValue??positional)?.replace(/\/+$/,"")??null;if(basePath!==null&&nameValue){let base=basePath;return{category:"builtin_write",operator:"New-Item",path:base?`${base}/${nameValue}`:nameValue}}if(pathValue)return{category:"builtin_write",operator:"New-Item",path:pathValue};if(positional)return{category:"builtin_write",operator:"New-Item",path:positional};if(nameValue)return{category:"builtin_write",operator:"New-Item",path:nameValue};return{category:"builtin_write",operator:"New-Item",path:null}}let fileOp=detectPsFileOp(innerCommand)??detectPsNewItem(innerCommand);if(fileOp)results.push(fileOp);let pipeFileOpMatch=innerCommand.match(/\|\s*(Copy-Item|Move-Item)\b\s*(.*)$/i);if(pipeFileOpMatch){let cmdletName=pipeFileOpMatch[1],afterCmdlet=pipeFileOpMatch[2].trim(),destFlagMatch=afterCmdlet.match(/-Destination\s+(\S+|"[^"]+"|'[^']+')/i);if(destFlagMatch){let path59=destFlagMatch[1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path59})}else{let nonFlagTokens=(afterCmdlet.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[]).filter((t)=>!t.startsWith("-")&&t.length>0);if(nonFlagTokens.length>0){let path59=nonFlagTokens[nonFlagTokens.length-1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path59})}}}return results}function tokenizeCmdArguments(command){let tokens=[],current="",inDoubleQuote=!1;for(let index=0;index<command.length;index++){let character=command[index];if(character==="^"&&!inDoubleQuote){if(index+1<command.length)current+=command[++index];continue}if(character==='"'){inDoubleQuote=!inDoubleQuote;continue}if(/\s/.test(character)&&!inDoubleQuote){if(current)tokens.push(current),current="";continue}current+=character}if(current)tokens.push(current);return tokens}function detectCmdRedirects(command){let results=[],inDoubleQuote=!1,isTokenBoundary=(character)=>character===void 0||/[;\s&|()]/.test(character);for(let index=0;index<command.length;index++){let character=command[index];if(character==="^"&&!inDoubleQuote){index++;continue}if(character==='"'){inDoubleQuote=!inDoubleQuote;continue}if(inDoubleQuote||character!==">")continue;let operator=command[index+1]===">"?">>":">",cursor=index+operator.length;while(/\s/.test(command[cursor]??""))cursor++;if(command[cursor]==="&"){cursor++;while(/\s/.test(command[cursor]??""))cursor++;let descriptorStart=cursor;while(/\d/.test(command[cursor]??""))cursor++;if(command.slice(descriptorStart,cursor)&&isTokenBoundary(command[cursor])){index=Math.max(index,cursor-1);continue}results.push({category:"redirect",operator,path:null}),index=Math.max(index,cursor-1);continue}let pathValue=null;if(cursor<command.length){let quote=command[cursor];if(quote==='"'){let closingQuote=command.indexOf(quote,cursor+1);if(closingQuote!==-1)pathValue=command.slice(cursor+1,closingQuote),cursor=closingQuote+1}else{let pathStart=cursor;while(cursor<command.length&&!/[\s&|()<>]/.test(command[cursor]??""))cursor++;if(cursor>pathStart)pathValue=command.slice(pathStart,cursor)}}results.push({category:"redirect",operator,path:pathValue}),index=Math.max(index,cursor-1)}if(inDoubleQuote)results.push({category:"redirect",operator:">",path:null});return results}function detectCmdWrites(command){let results=[],trimmed=command.trim();if(!trimmed)return results;let innerCommand=trimmed,cmdWrapperMatch=trimmed.match(new RegExp(`${CMD_STRIP_PREFIX.source}(.*)$`,"i"));if(cmdWrapperMatch){if(innerCommand=cmdWrapperMatch[1].trim(),innerCommand.startsWith('"')&&innerCommand.endsWith('"')||innerCommand.startsWith("'")&&innerCommand.endsWith("'"))innerCommand=innerCommand.slice(1,-1)}if(/^(?:powershell|pwsh)(?:\.exe)?\s+/i.test(innerCommand))results.push(...detectPowerShellWrites(innerCommand));results.push(...detectCmdRedirects(innerCommand));function detectCmdCopy(cmd){let commandMatch=cmd.match(new RegExp(`^${CMD_BUILTIN_PREFIX.source}copy(?=\\s|$)`,"i"));if(commandMatch){let start=(commandMatch.index??0)+commandMatch[0].length,positional=tokenizeCmdArguments(cmd.slice(start)).filter((token)=>!_CMD_COPY_MOVE_SWITCHES.has(token.toLowerCase()));if(positional.length<2)return null;return{category:"builtin_write",operator:"copy",path:positional[positional.length-1]}}return null}function detectCmdMove(cmd){let commandMatch=cmd.match(new RegExp(`^${CMD_BUILTIN_PREFIX.source}move(?=\\s|$)`,"i"));if(commandMatch){let start=(commandMatch.index??0)+commandMatch[0].length,positional=tokenizeCmdArguments(cmd.slice(start)).filter((token)=>!_CMD_COPY_MOVE_SWITCHES.has(token.toLowerCase()));if(positional.length<2)return null;return{category:"builtin_write",operator:"move",path:positional[positional.length-1]}}return null}let copyResult=detectCmdCopy(innerCommand);if(copyResult)results.push(copyResult);let moveResult=detectCmdMove(innerCommand);if(moveResult)results.push(moveResult);let renMatch=innerCommand.match(/^ren\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(renMatch){let dest=(renMatch[2]||"").replace(/^["']|["']$/g,"");if(dest)results.push({category:"builtin_write",operator:"ren",path:dest})}function detectCmdDel(cmd){let delMatch=cmd.match(/^del\s+/i);if(!delMatch)return null;let tokens=(cmd.slice(delMatch[0].length).trim().match(/(\/?[^\s]+|"[^"]*"|'[^']*')/g)??[]).filter((t)=>!t.startsWith("/"));if(tokens.length>0)return{category:"builtin_write",operator:"del",path:tokens[0].replace(/^["']|["']$/g,"")};return null}let delResult=detectCmdDel(innerCommand);if(delResult)results.push(delResult);let rdMatch=innerCommand.match(/^rd\s+(?:\/s\s+|\/q\s+)*(\S+)/i);if(rdMatch){let path59=rdMatch[1].replace(/^["']|["']$/g,"");if(!path59.startsWith("/"))results.push({category:"builtin_write",operator:"rd",path:path59})}let mdMatch=trimmed.match(/^md\s+(\S+)/i);if(mdMatch){let path59=mdMatch[1].replace(/^["']|["']$/g,"");if(!path59.startsWith("/"))results.push({category:"builtin_write",operator:"md",path:path59})}return results}function detectInteractiveSession(command,shell){if(!command||typeof command!=="string")return!1;let trimmed=command.trim();if(shell==="posix"){let lower=trimmed.toLowerCase();if(/^watch(\s|$)/.test(lower))return!0;if(/^screen(\s|$)/.test(lower))return!0;if(/^tmux(\s+new-session(\s+.*)?)?$/.test(lower))return!0}else if(shell==="powershell"){if(/^Start-Process\s/i.test(trimmed))return!0}return!1}function detectPosixWrites(command){if(!command||typeof command!=="string")return{writes:[],hasWrites:!1};if(unsafeShellCommandTextReason(command))return{writes:[{category:"interpreter_eval",operator:"unsafe command text",path:null}],hasWrites:!0,parseError:!0};let ast,parseFailed=!1;try{ast=import_bash_parser.default(command,{mode:"posix",insertLOC:!0}),annotateRawWordText(ast,command)}catch{parseFailed=!0}let allWrites=[],cwdNeutral=!1;if(!parseFailed&&ast&&typeof ast==="object"){let leafCommands=[];collectLeafCommands(ast,leafCommands),cwdNeutral=leafCommands.every(isCwdNeutralLeaf);for(let cmd of leafCommands)allWrites.push(...detectRedirects(cmd)),allWrites.push(...detectBuiltinWrites(cmd)),allWrites.push(...detectInplaceEdit(cmd)),allWrites.push(...detectInterpreterEval(cmd)),allWrites.push(...detectNetworkDownloaders(cmd)),allWrites.push(...detectArchiveExtract(cmd)),allWrites.push(...detectGitDestructive(cmd));collectPipeStdinEvals(ast,allWrites)}if(parseFailed){let procSubWrites=detectProcessSubstitutionWrites(command);allWrites.push(...procSubWrites)}let seen=new Set,occurrence=new Map,collidingKeys=new Set,writes=[];for(let wt of allWrites){let key=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key)){if(collidingKeys.add(key),wt.capability!==!0||wt.category!=="interpreter_eval")continue;let n=(occurrence.get(key)??1)+1;occurrence.set(key,n),writes.push({...wt,operator:`${wt.operator} #${n}`});continue}seen.add(key),writes.push(wt)}if(writes=writes.map((wt)=>wt.emptyDirectoryRemoval===!0&&collidingKeys.has(buildDedupeKey(wt.category,wt.operator,wt.path))?withoutEmptyDirectoryRemoval(wt):wt),!PLAIN_COMMAND_LINE.test(command))writes=writes.map(withoutEmptyDirectoryRemoval);if(!cwdNeutral)writes=writes.map(withoutEmptyDirectoryRemoval);return{writes,hasWrites:writes.length>0,parseError:parseFailed&&writes.length===0?!0:void 0}}function isCwdNeutralLeaf(node){if(node.type!=="Command")return CWD_TRANSPARENT_NODE_TYPES.has(node.type);let name=getCommandName(node);if(name!==null)return CWD_NEUTRAL_COMMANDS.has(name);let prefix=node.prefix??[];return Array.isArray(prefix)&&prefix.every((entry)=>{if(!entry||typeof entry!=="object")return!1;let type=entry.type;return type==="AssignmentWord"||type==="Redirect"})}function detectWindowsInterpreterEval(fragment){let tokens=fragment.trim().split(/\s+/);if(tokens.length<2)return[];let leaf=basenameAnySep(tokens[0].replace(/^["']+|["']+$/g,"")),canonical=detectorSetMember(leaf,new Set(WINDOWS_INTERPRETER_EVAL_FLAGS.keys()));if(!canonical)return[];let flags=WINDOWS_INTERPRETER_EVAL_FLAGS.get(canonical)??[];for(let i=1;i<tokens.length;i++){let token=tokens[i];if(flags.some((flag)=>token===flag||token.startsWith(`${flag}=`)||token.startsWith(flag)&&token.length>flag.length))return[{category:"interpreter_eval",operator:`${tokens[0]} [eval]`,path:null,capability:!0}]}return[]}function detectWindowsWrites(command,shell){if(!command||typeof command!=="string")return{writes:[],hasWrites:!1};if(unsafeShellCommandTextReason(command))return{writes:[{category:"interpreter_eval",operator:"unsafe command text",path:null}],hasWrites:!0,parseError:!0};try{let subCommands=splitWindowsCommands(command,shell),allWrites=[];for(let subCmd of subCommands)allWrites.push(...detectWindowsInterpreterEval(subCmd));for(let subCmd of subCommands){let psWrites=detectPowerShellWrites(subCmd),psFiltered=shell==="powershell"?psWrites:psWrites.filter((w)=>w.operator!=="working-directory mutation");allWrites.push(...psFiltered);let cmdWrites=detectCmdWrites(subCmd),cmdFiltered=shell==="powershell"?cmdWrites.filter((w)=>w.category!=="redirect"):cmdWrites;allWrites.push(...cmdFiltered)}let stripQuotes=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),seen=new Set,seenStripped=[],occurrence=new Map,writes=[];for(let wt of allWrites){let key=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key)){if(wt.capability!==!0||wt.category!=="interpreter_eval")continue;let n=(occurrence.get(key)??1)+1;occurrence.set(key,n),writes.push({...wt,operator:`${wt.operator} #${n}`});continue}let stripped=stripQuotes(wt.path);if(stripped!==wt.path){if(seenStripped.some((other)=>other.category===wt.category&&other.operator===wt.operator&&stripQuotes(other.path)===stripped))continue}seen.add(key),seenStripped.push({category:wt.category,operator:wt.operator,path:wt.path}),writes.push(wt)}return{writes,hasWrites:writes.length>0}}catch{return{writes:[],hasWrites:!1,parseError:!0}}}function isDynamicPath(pathText){if(pathText===null||pathText===void 0)return!1;if(/\$[A-Za-z_][A-Za-z0-9_]*/.test(pathText))return!0;if(/\$\{[^}]+\}/.test(pathText))return!0;if(/%[A-Za-z_][A-Za-z0-9_]*%/.test(pathText))return!0;if(/\$\([^)]+\)/.test(pathText))return!0;if(/`[^`]+`/.test(pathText))return!0;if(/^~(?:[^/\\\s]*)?(?:[/\\]|$)/.test(pathText))return!0;if(/%~[A-Za-z]*(?:\d+|\*)/.test(pathText))return!0;if(/%(?:\d+|\*)/.test(pathText))return!0;return!1}function resolvePath(pathText,cwd){if(pathText===null)return null;if(isDynamicPath(pathText))return null;if(/^[a-zA-Z]:[\\\\/]/.test(cwd)||cwd.includes("\\"))return path58.win32.resolve(cwd,pathText);let normalizedRelativeWindowsPath=!path58.posix.isAbsolute(pathText)&&!/^[a-zA-Z]:[\\/]/.test(pathText)?pathText.replace(/\\/g,"/"):pathText;return path58.posix.resolve(cwd,normalizedRelativeWindowsPath)}function getCdTarget(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(c.type!=="SimpleCommand"&&c.type!=="Command")return null;let name=c.name;if(!name||typeof name!=="object")return null;let n=name;if(n.type!=="Word")return null;if(n.text!=="cd")return null;let suffix=c.suffix;if(!Array.isArray(suffix)||suffix.length===0)return null;let first=suffix[0];if(!first||typeof first!=="object")return null;let firstWord=first;if(firstWord.type!=="Word")return null;let target=firstWord.text;if(target==="-"||target==="~"||target==="~/")return null;return target}function collectWritesWithNodes(node,out,cwdStack,andSharedStack=!0){if(!node||typeof node!=="object")return;if(node.type==="CommandExpansion"){let inner=node.commandAST;if(inner)collectWritesWithNodes(inner,out,cwdStack,andSharedStack);return}switch(node.type){case"Script":{let _globalCwd=cwdStack[0]??"/";if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack,andSharedStack);break}case"Subshell":{let effectiveCwd=cwdStack[0]??"/",subshellRedirs=node.redirections;if(Array.isArray(subshellRedirs))for(let redirect of subshellRedirs){let writesFromRedirect=getWritesFromRedirectNode(redirect,effectiveCwd);for(let w of writesFromRedirect)out.push({write:w,context:effectiveCwd})}if(node.list){let subStack=[...cwdStack];collectWritesWithNodes(node.list,out,subStack,andSharedStack)}break}case"CompoundList":{if(Array.isArray(node.commands)){let currentStack=cwdStack;for(let cmd of node.commands){let cdTarget=getCdTarget(cmd);if(cdTarget)currentStack[0]=resolvePath(cdTarget,currentStack[0]??"/")??path58.posix.resolve(currentStack[0]??"/",cdTarget);else collectWritesWithNodes(cmd,out,currentStack,andSharedStack)}}break}case"Sequence":{if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack,andSharedStack);break}case"Pipeline":{if(Array.isArray(node.commands)){for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack,andSharedStack);let pipeEval=classifyPipeStdinEval(node);if(pipeEval)out.push({write:pipeEval,context:cwdStack[0]??"/"})}break}case"LogicalExpression":{let andChain=node.op==="and"||node.type==="And";if(node.left){collectWritesWithNodes(node.left,out,cwdStack,andSharedStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=andChain&&andSharedStack?cwdStack:[leftContext];collectWritesWithNodes(node.right,out,rightStack,andSharedStack)}}break}case"And":case"Or":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack,andSharedStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=node.type==="And"&&andSharedStack?cwdStack:[leftContext];collectWritesWithNodes(node.right,out,rightStack,andSharedStack)}}break}case"If":{let effectiveCwd=cwdStack[0]??"/";if(Array.isArray(node.redirections))for(let redirect of node.redirections)for(let w of getWritesFromRedirectNode(redirect,effectiveCwd))out.push({write:w,context:effectiveCwd});for(let body of[node.clause,node.then,node.else])if(body)collectWritesWithNodes(body,out,[...cwdStack],andSharedStack);break}case"While":case"Until":{let effectiveCwd=cwdStack[0]??"/";if(Array.isArray(node.redirections))for(let redirect of node.redirections)for(let w of getWritesFromRedirectNode(redirect,effectiveCwd))out.push({write:w,context:effectiveCwd});if(node.clause)collectWritesWithNodes(node.clause,out,[...cwdStack],andSharedStack);if(node.do)collectWritesWithNodes(node.do,out,[...cwdStack],andSharedStack);break}case"For":{let effectiveCwd=cwdStack[0]??"/";if(Array.isArray(node.redirections))for(let redirect of node.redirections)for(let w of getWritesFromRedirectNode(redirect,effectiveCwd))out.push({write:w,context:effectiveCwd});if(node.do)collectWritesWithNodes(node.do,out,[...cwdStack],andSharedStack);break}case"Case":{let effectiveCwd=cwdStack[0]??"/";if(Array.isArray(node.redirections))for(let redirect of node.redirections)for(let w of getWritesFromRedirectNode(redirect,effectiveCwd))out.push({write:w,context:effectiveCwd});if(Array.isArray(node.cases)){for(let entry of node.cases)if(entry?.body)collectWritesWithNodes(entry.body,out,[...cwdStack],andSharedStack)}break}case"Function":{let effectiveCwd=cwdStack[0]??"/";if(Array.isArray(node.redirections))for(let redirect of node.redirections)for(let w of getWritesFromRedirectNode(redirect,effectiveCwd))out.push({write:w,context:effectiveCwd});if(node.body)collectWritesWithNodes(node.body,out,[...cwdStack],andSharedStack);break}case"Command":case"SimpleCommand":{let effectiveCwd=cwdStack[0]??"/",cdTarget=getCdTarget(node);if(cdTarget){cwdStack[0]=resolvePath(cdTarget,cwdStack[0]??"/")??path58.posix.resolve(cwdStack[0]??"/",cdTarget);return}let writesFromRedirs=getWritesFromCommandRedirs(node,effectiveCwd);for(let w of writesFromRedirs)out.push({write:w,context:effectiveCwd});let builtinWrites=detectBuiltinWrites(node);for(let w of builtinWrites)out.push({write:w,context:effectiveCwd});let inplaceWrites=detectInplaceEdit(node);for(let w of inplaceWrites)out.push({write:w,context:effectiveCwd});let interpreterWrites=detectInterpreterEval(node);for(let w of interpreterWrites)out.push({write:w,context:effectiveCwd});let networkWrites=detectNetworkDownloaders(node);for(let w of networkWrites)out.push({write:w,context:effectiveCwd});let archiveWrites=detectArchiveExtract(node);for(let w of archiveWrites)out.push({write:w,context:effectiveCwd});let gitWrites=detectGitDestructive(node);for(let w of gitWrites)out.push({write:w,context:effectiveCwd});break}}}function getWritesFromRedirectNode(redirect,_context){if(!redirect||typeof redirect!=="object")return[];let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")return[];let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))return[];let fileNode=r.file,path59=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path59)){if(path59!==null&&isNullDevice(path59))return[];return[{category:"redirect",operator:opLabel,path:path59}]}else if(REDIRECT_HERE_TOKENS.has(opType))return[{category:"here_doc",operator:opLabel,path:path59}];return[]}function getWritesFromCommandRedirs(cmd,context){if(!cmd||typeof cmd!=="object")return[];let c=cmd,results=[];results.push(...detectHereDocMarkers(cmd));let{suffix,prefix}=c;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item)){let writes=getWritesFromRedirectNode(item,context);results.push(...writes)}}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item)){let writes=getWritesFromRedirectNode(item,context);results.push(...writes)}}return results}function resolveWriteTargets(command,writes,cwd){if(!writes||writes.length===0)return[];if(!command||typeof command!=="string")return writes.map((original)=>({original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path),...original.capability===!0&&original.category==="interpreter_eval"?{evalDirectory:cwd}:{}}));let ast;try{ast=import_bash_parser.default(command,{mode:"posix",insertLOC:!0}),annotateRawWordText(ast,command)}catch{ast=null}if(!ast||typeof ast!=="object")return writes.map((original)=>({original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path),...original.capability===!0&&original.category==="interpreter_eval"?{evalDirectory:cwd}:{}}));let cwdStack=[cwd],trackedNodes=[];collectWritesWithNodes(ast,trackedNodes,cwdStack);let pessimisticNodes=[];collectWritesWithNodes(ast,pessimisticNodes,[cwd],!1);let buildResolution=(nodes)=>{let seen=new Set,occurrence=new Map,colliding=new Set,deduplicated=[];for(let wwn of nodes){let key=buildDedupeKey(wwn.write.category,wwn.write.operator,wwn.write.path);if(seen.has(key)){if(colliding.add(key),wwn.write.capability!==!0||wwn.write.category!=="interpreter_eval")continue;let n=(occurrence.get(key)??1)+1;occurrence.set(key,n),deduplicated.push({write:{...wwn.write,operator:`${wwn.write.operator} #${n}`},context:wwn.context});continue}seen.add(key),deduplicated.push(wwn)}let map2=new Map;for(let{write,context}of deduplicated){let resolvedPath=resolvePath(write.path,context),resolved=write.path!==null&&!isDynamicPath(write.path),key=buildDedupeKey(write.category,write.operator,write.path),evalDirectory=write.capability===!0&&write.category==="interpreter_eval"?context:void 0;map2.set(key,{resolvedPath,resolved,evalDirectory})}return{map:map2,colliding}},{map:resolvedMap,colliding:collidingKeys}=buildResolution(trackedNodes),{map:pessimisticMap}=buildResolution(pessimisticNodes),inputKeys=new Set;for(let write of writes){let key=buildDedupeKey(write.category,write.operator,write.path);if(inputKeys.has(key))collidingKeys.add(key);inputKeys.add(key)}return writes.flatMap((input)=>{let key=buildDedupeKey(input.category,input.operator,input.path),original=collidingKeys.has(key)?withoutEmptyDirectoryRemoval(input):input,buildEntry=(resolved)=>({original,resolvedPath:resolved.resolvedPath,resolved:resolved.resolved,...resolved.evalDirectory!==void 0?{evalDirectory:resolved.evalDirectory}:{}}),entries=[],tracked=resolvedMap.get(key);if(tracked){entries.push(buildEntry(tracked));let pessimistic=pessimisticMap.get(key);if(pessimistic&&(pessimistic.resolvedPath!==tracked.resolvedPath||pessimistic.evalDirectory!==tracked.evalDirectory))entries.push(buildEntry(pessimistic));return entries}return[{original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path),...original.capability===!0&&original.category==="interpreter_eval"?{evalDirectory:cwd}:{}}]})}var import_bash_parser,REDIRECT_WRITE_TOKENS,REDIRECT_HERE_TOKENS,REDIRECT_GREATAND_TOKENS,REDIRECT_ALL_WRITE_TOKENS,BUILTIN_WRITE_COMMANDS,BARE_RMDIR_OPERAND,INPLACE_EDIT_COMMANDS,SED_LONG_SWITCHES,AWK_LONG_SWITCHES,INTERPRETER_EVAL_COMMANDS,NETWORK_DOWNLOAD_COMMANDS,ARCHIVE_EXTRACT_COMMANDS,BASH_BUILTIN_COMMANDS,GIT_COMMAND="git",POWERSHELL_WRITE_CMDLETS,AMBIGUOUS_WRITE_ALIASES,POWERSHELL_READ_ONLY_COMMANDS,POSIX_WRITE_TOKENS,READ_ONLY_SCRIPT_BLOCK_OPERATORS,RAW_WORD_TEXT,BRACE_EXPANSION,PARSER_CHAR_ESCAPES,ENV_FLAGS_WITH_ARG,_CMD_COPY_MOVE_SWITCHES,PLAIN_COMMAND_LINE,CWD_NEUTRAL_COMMANDS,CWD_TRANSPARENT_NODE_TYPES,WINDOWS_INTERPRETER_EVAL_FLAGS;var init_shell_write_detect=__esm(()=>{init_path_identity();init_shell_executor_context();import_bash_parser=__toESM(require_src(),1);REDIRECT_WRITE_TOKENS=new Set(["GREAT","DGREAT","CLOBBER","LESSGREAT"]),REDIRECT_HERE_TOKENS=new Set(["DLESS","DLESSDASH"]),REDIRECT_GREATAND_TOKENS=new Set(["GREATAND"]),REDIRECT_ALL_WRITE_TOKENS=new Set([...REDIRECT_WRITE_TOKENS,...REDIRECT_HERE_TOKENS,...REDIRECT_GREATAND_TOKENS]),BUILTIN_WRITE_COMMANDS=new Set(["cp","mv","install","ln","truncate","unlink","rmdir"]),BARE_RMDIR_OPERAND=/^[^-*?[\]{}$`~"'=\\#\s][^*?[\]{}$`~"'\\#\s]*$/;INPLACE_EDIT_COMMANDS=new Set(["sed","perl","awk"]),SED_LONG_SWITCHES=new Set(["--quiet","--silent","--debug","--follow-symlinks","--binary","--posix","--regexp-extended","--separate","--sandbox","--unbuffered","--null-data","--zero-terminated","--help","--version"]),AWK_LONG_SWITCHES=new Set(["--posix","--traditional","--lint","--re-interval","--sandbox","--version","--help"]),INTERPRETER_EVAL_COMMANDS=new Set(["python","python3","python2","py","node","bun","ruby","perl","php","bash","sh","dash","zsh","ksh","eval"]),NETWORK_DOWNLOAD_COMMANDS=new Set(["curl","wget","scp"]),ARCHIVE_EXTRACT_COMMANDS=new Set(["tar","unzip","gunzip","gzip","bzip2","xz","7z","rar"]),BASH_BUILTIN_COMMANDS=new Set(["echo","printf","cd","pwd","true","false","test","[",":","eval","wait","read","mapfile","source",".","alias","bg","fg","jobs","kill","type","ulimit","umask","unset","times","trap","getopts","help","fc","hash","history","let","local","declare","logout","pushd","popd","dirs","shopt","set","shift","caller","compgen","complete"]),POWERSHELL_WRITE_CMDLETS=new Set(["set-content","add-content","out-file","clear-content","copy-item","move-item","remove-item","new-item","ni","ac","sc","epcsv"]),AMBIGUOUS_WRITE_ALIASES=new Set(["cp","cpi","mv","rm","del","ren","rd","md","type"]),POWERSHELL_READ_ONLY_COMMANDS=new Set(["get-content","gc","get-item","gi","get-childitem","gci","get-location","pwd","get-command","get-member","get-date","get-help","get-itemproperty","select-string","select-object","where-object","foreach-object","sort-object","group-object","measure-object","compare-object","resolve-path","test-path","format-table","out-string","write-output","write-host","write-verbose","write-warning"]),POSIX_WRITE_TOKENS=new Set(["cp","mv","rm","rmdir","tee","dd","ln","touch","truncate","unlink","install"]);READ_ONLY_SCRIPT_BLOCK_OPERATORS=new Set(["-gt","-ge","-lt","-le","-eq","-ne","-match","-notmatch","-like","-notlike","-replace","-contains","-notcontains","-in","-notin","-is","-isnot","-join","-split","-f","-band","-bor","-bnot","-shl","-shr","-and","-or","-not","-xor"].map((op)=>op.toLowerCase()));RAW_WORD_TEXT=new WeakMap;BRACE_EXPANSION=/\{[^{}]*(?:,|\.\.)[^{}]*\}/;PARSER_CHAR_ESCAPES={t:"\t",n:`
|
|
752
|
-
`,r:"\r",b:"\b",f:"\f",v:"\v"};ENV_FLAGS_WITH_ARG=new Set(["-u","-U","-C","-S","-a","-P","--split-string","--unset","--chdir","--argv0","--env0-from"]);_CMD_COPY_MOVE_SWITCHES=new Set(["/a","/b","/d","/f","/n","/v","/y","/-y","/z"]);PLAIN_COMMAND_LINE=/^[A-Za-z0-9 \t\n_./=&|;<>-]*$/,CWD_NEUTRAL_COMMANDS=new Set(["rmdir","mkdir","echo","true","false","test"]),CWD_TRANSPARENT_NODE_TYPES=new Set(["CompoundList","If","While","Until","For"]);WINDOWS_INTERPRETER_EVAL_FLAGS=new Map(Object.entries({python:["-c"],python3:["-c"],python2:["-c"],py:["-c"],node:["-e","--eval","-p","--print"],bun:["-e"],ruby:["-e"],perl:["-e","-E"],php:["-r","-R","-F"]}))});import*as fsSync6 from"node:fs";import*as path59 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 dcStripExecutionLauncher(t){let bounded=t.length>8192,head=bounded?t.slice(0,8192):t,tail=bounded?t.slice(8192):"",withTail=(inner)=>{if(inner===null)return null;return`${inner}${tail}`.trim()||null},cm=/^command\s+(.*)$/is.exec(head);if(cm){let rest=cm[1];while(/^-p+\s+/i.test(rest))rest=rest.replace(/^-p+\s+/i,"");if(/^-[pvP]*[vV](?:\s|$)/.test(rest))return null;if(/^--\s+/.test(rest))rest=rest.replace(/^--\s+/,"");return withTail(rest.trim()||null)}let bm=/^builtin\s+(.+)$/is.exec(head);if(bm){let rest=bm[1].replace(/^--\s+/,""),leaf=(rest.split(/\s+/)[0]??"").split(/[\\/]/).pop()?.replace(/\.exe$/i,"").toLowerCase()??"";if(!BASH_BUILTIN_COMMANDS.has(leaf))return null;return withTail(rest.trim()||null)}let em=/^exec\s+(.+)$/is.exec(head);if(em){let rest=em[1];for(;;){if(/^--\s+/.test(rest)){rest=rest.replace(/^--\s+/,"");break}if(/^-[cl]+\s+/i.test(rest)){rest=rest.replace(/^-[cl]+\s+/i,"");continue}if(/^-a\S+\s+/i.test(rest)){rest=rest.replace(/^-a\S+\s+/i,"");continue}if(/^-a\s+\S+\s+/i.test(rest)){rest=rest.replace(/^-a\s+\S+\s+/i,"");continue}break}return withTail(rest.trim()||null)}let tm=/^timeout\s+(.+)$/is.exec(head);if(tm){let rest=tm[1];for(;;){let stripped=!0;if(/^--foreground\s+/i.test(rest))rest=rest.replace(/^--foreground\s+/i,"");else if(/^--preserve-status\s+/i.test(rest))rest=rest.replace(/^--preserve-status\s+/i,"");else if(/^--kill-after=\S+\s+/i.test(rest))rest=rest.replace(/^--kill-after=\S+\s+/i,"");else if(/^--signal=\S+\s+/i.test(rest))rest=rest.replace(/^--signal=\S+\s+/i,"");else if(/^--verbose\s+/i.test(rest))rest=rest.replace(/^--verbose\s+/i,"");else if(/^-[sk]\S+\s+/i.test(rest))rest=rest.replace(/^-[sk]\S+\s+/i,"");else if(/^-k\s+\S+\s+/i.test(rest))rest=rest.replace(/^-k\s+\S+\s+/i,"");else if(/^-s\s+\S+\s+/i.test(rest))rest=rest.replace(/^-s\s+\S+\s+/i,"");else if(/^--kill-after\s+\S+\s+/i.test(rest))rest=rest.replace(/^--kill-after\s+\S+\s+/i,"");else if(/^--signal\s+\S+\s+/i.test(rest))rest=rest.replace(/^--signal\s+\S+\s+/i,"");else if(/^-(?:v)\s+/i.test(rest))rest=rest.replace(/^-(?:v)\s+/i,"");else if(/^--\s+/.test(rest))rest=rest.replace(/^--\s+/,"");else stripped=!1;if(!stripped)break}let dm=/^[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[iI][nN][fF](?:[iI][nN][iI][tT][yY])?)[smhd]?\s+(.+)$/.exec(rest);return dm?withTail(dm[1].trim()):null}let sm=/^stdbuf\s+(.+)$/is.exec(head);if(sm){let rest=sm[1];for(;;){let m=/^-[ioe](?:[= ]?\S+)?(?:\s+|$)/i.exec(rest);if(m){rest=rest.slice(m[0].length);continue}if(m=/^--(?:input|output|error)(?:[= ]?\S+)?(?:\s+|$)/i.exec(rest),m){rest=rest.slice(m[0].length);continue}if(/^--\s+/.test(rest)){rest=rest.replace(/^--\s+/,"");break}break}return withTail(rest.trim()||null)}return null}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=new RegExp(`${CMD_STRIP_PREFIX.source}"?(.*?)"?\\s*$`,"is").exec(t);if(cmdExeMatch)return cmdExeMatch[1].trim();let psCommandMatch=new RegExp(`${PS_STRIP_PREFIX.source}(.+)$`,"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]??shellMatch[2]??shellMatch[3]).trim();let evalMatch=/^eval\s+(.+)$/is.exec(t);if(evalMatch)return evalMatch[1].replace(/^["']|["']$/g,"").trim();let envPrefix=/^env(?:\s+(?:[A-Za-z_][A-Za-z0-9_]*=\S+|(?:-[i0vVh]*[uUCSaP]|--u(?:n(?:s(?:e(?:t)?)?)?)?|--c(?:h(?:d(?:i(?:r)?)?)?)?|--a(?:r(?:g(?:v(?:0)?)?)?)?|--s(?:p(?:l(?:i(?:t(?:-(?:s(?:t(?:r(?:i(?:n(?:g)?)?)?)?)?)?)?)?)?)?)?|--e(?:n(?:v(?:0(?:-(?:f(?:r(?:o(?:m)?)?)?)?)?)?)?)?)\s+\S+|-\S+|--[A-Za-z][A-Za-z0-9-]*))*\s+(.+)$/is,launcherInner=dcStripExecutionLauncher(t),prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??envPrefix.exec(t)??(launcherInner!==null&&launcherInner!==""?[t,launcherInner]:null)??/^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===`
|
|
753
|
-
`||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=path59.resolve(cwd,targetPath),normalizedCwd=path59.resolve(cwd),ancestors=[],current=normalizedTarget;while(!0){let rel=path59.relative(normalizedCwd,current);if(rel===".."||rel.startsWith(`..${path59.sep}`)||path59.isAbsolute(rel))break;if(ancestors.push(current),rel==="")break;let parent=path59.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat9=null;try{stat9=fsSync6.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(stat9.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,path59.sep),lstatBlock=dcLstatAncestorWalk(filesystemTarget,cwd);if(lstatBlock)return lstatBlock;let basename12=path59.basename(filesystemTarget);if(dcPathComponents(t).length===1&&DC_SAFE_TARGETS.has(basename12))continue;if(DC_FS_ROOTS.has(t)||DC_FS_ROOTS.has(t.replace(/\//g,"\\")))return`BLOCKED: Destructive command targets filesystem root "${t}"`;if(path59.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 normalize8=(value)=>{let normalized=path59.posix.normalize(value.replace(/\\/g,"/")).replace(/^\.\//,"").replace(/\/$/,"");return process.platform==="win32"?normalized.toLowerCase():normalized},scope=normalize8(scopeEntry),candidate=normalize8(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,path59.sep),resolved=path59.resolve(input.cwd,filesystemTarget),relative13=path59.relative(path59.resolve(input.cwd),resolved);if(relative13===""||relative13===".."||relative13.startsWith(`..${path59.sep}`)||path59.isAbsolute(relative13))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUTSIDE_WORKSPACE",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not strictly contained by the workspace.`};let basename12=path59.basename(resolved);if(!DC_SAFE_TARGETS.has(basename12))return{allowed:!1,code:"DESTRUCTIVE_TARGET_NOT_SAFE_ARTIFACT",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not an allowlisted build/cache artifact.`};let normalizedRelative=relative13.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=path59.resolve(cwd,target),rel=path59.relative(cwd,resolved);if(rel.startsWith("..")||path59.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=path59.resolve(cwd,target),rel=path59.relative(cwd,resolved);if(rel.startsWith("..")||path59.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=path59.resolve(cwd,target),rel=path59.relative(cwd,resolved);if(rel.startsWith("..")||path59.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(()=>{init_shell_executor_context();init_shell_write_detect();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 createHash30}from"node:crypto";function digest2(value){return createHash30("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 path60 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)=>path60.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});class Reader{src;pos=0;constructor(src){this.src=src}eof(){return this.pos>=this.src.length}peek(){return this.src[this.pos]??""}skipWs(){while(!this.eof()&&WHITESPACE.test(this.peek()))this.pos+=1}eat(ch){if(this.peek()===ch)return this.pos+=1,!0;return!1}eatWord(word){if(!this.src.startsWith(word,this.pos))return!1;let next=this.src[this.pos+word.length]??"";if(next!==""&&IDENT_PART.test(next))return!1;return this.pos+=word.length,!0}ident(){if(!IDENT_START.test(this.peek()))return null;let start=this.pos;this.pos+=1;while(!this.eof()&&IDENT_PART.test(this.peek()))this.pos+=1;return this.src.slice(start,this.pos)}string(){let quote=this.peek();if(quote!=='"'&"e!=="'")return null;this.pos+=1;let out="";while(!this.eof()){let ch=this.peek();if(this.pos+=1,ch===quote)return out;if(ch===`
|
|
752
|
+
`,r:"\r",b:"\b",f:"\f",v:"\v"};ENV_FLAGS_WITH_ARG=new Set(["-u","-U","-C","-S","-a","-P","--split-string","--unset","--chdir","--argv0","--env0-from"]);_CMD_COPY_MOVE_SWITCHES=new Set(["/a","/b","/d","/f","/n","/v","/y","/-y","/z"]);PLAIN_COMMAND_LINE=/^[A-Za-z0-9 \t\n_./=&|;<>-]*$/,CWD_NEUTRAL_COMMANDS=new Set(["rmdir","mkdir","echo","true","false","test"]),CWD_TRANSPARENT_NODE_TYPES=new Set(["CompoundList","If","While","Until","For"]);WINDOWS_INTERPRETER_EVAL_FLAGS=new Map(Object.entries({python:["-c"],python3:["-c"],python2:["-c"],py:["-c"],node:["-e","--eval","-p","--print"],bun:["-e"],ruby:["-e"],perl:["-e","-E"],php:["-r","-R","-F"]}))});import*as fsSync6 from"node:fs";import*as path59 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 dcStripExecutionLauncher(t){let bounded=t.length>8192,head=bounded?t.slice(0,8192):t,tail=bounded?t.slice(8192):"",withTail=(inner)=>{if(inner===null)return null;return`${inner}${tail}`.trim()||null},cm=/^command\s+(.*)$/is.exec(head);if(cm){let rest=cm[1];while(/^-p+\s+/i.test(rest))rest=rest.replace(/^-p+\s+/i,"");if(/^-[pvP]*[vV](?:\s|$)/.test(rest))return null;if(/^--\s+/.test(rest))rest=rest.replace(/^--\s+/,"");return withTail(rest.trim()||null)}let bm=/^builtin\s+(.+)$/is.exec(head);if(bm){let rest=bm[1].replace(/^--\s+/,""),leaf=(rest.split(/\s+/)[0]??"").split(/[\\/]/).pop()?.replace(/\.exe$/i,"").toLowerCase()??"";if(!BASH_BUILTIN_COMMANDS.has(leaf))return null;return withTail(rest.trim()||null)}let em=/^exec\s+(.+)$/is.exec(head);if(em){let rest=em[1];for(;;){if(/^--\s+/.test(rest)){rest=rest.replace(/^--\s+/,"");break}if(/^-[cl]+\s+/i.test(rest)){rest=rest.replace(/^-[cl]+\s+/i,"");continue}if(/^-a\S+\s+/i.test(rest)){rest=rest.replace(/^-a\S+\s+/i,"");continue}if(/^-a\s+\S+\s+/i.test(rest)){rest=rest.replace(/^-a\s+\S+\s+/i,"");continue}break}return withTail(rest.trim()||null)}let tm=/^timeout\s+(.+)$/is.exec(head);if(tm){let rest=tm[1];for(;;){let stripped=!0;if(/^--foreground\s+/i.test(rest))rest=rest.replace(/^--foreground\s+/i,"");else if(/^--preserve-status\s+/i.test(rest))rest=rest.replace(/^--preserve-status\s+/i,"");else if(/^--kill-after=\S+\s+/i.test(rest))rest=rest.replace(/^--kill-after=\S+\s+/i,"");else if(/^--signal=\S+\s+/i.test(rest))rest=rest.replace(/^--signal=\S+\s+/i,"");else if(/^--verbose\s+/i.test(rest))rest=rest.replace(/^--verbose\s+/i,"");else if(/^-[sk]\S+\s+/i.test(rest))rest=rest.replace(/^-[sk]\S+\s+/i,"");else if(/^-k\s+\S+\s+/i.test(rest))rest=rest.replace(/^-k\s+\S+\s+/i,"");else if(/^-s\s+\S+\s+/i.test(rest))rest=rest.replace(/^-s\s+\S+\s+/i,"");else if(/^--kill-after\s+\S+\s+/i.test(rest))rest=rest.replace(/^--kill-after\s+\S+\s+/i,"");else if(/^--signal\s+\S+\s+/i.test(rest))rest=rest.replace(/^--signal\s+\S+\s+/i,"");else if(/^-(?:v)\s+/i.test(rest))rest=rest.replace(/^-(?:v)\s+/i,"");else if(/^--\s+/.test(rest))rest=rest.replace(/^--\s+/,"");else stripped=!1;if(!stripped)break}let dm=/^[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[iI][nN][fF](?:[iI][nN][iI][tT][yY])?)[smhd]?\s+(.+)$/.exec(rest);return dm?withTail(dm[1].trim()):null}let sm=/^stdbuf\s+(.+)$/is.exec(head);if(sm){let rest=sm[1];for(;;){let m=/^-[ioe](?:[= ]?\S+)?(?:\s+|$)/i.exec(rest);if(m){rest=rest.slice(m[0].length);continue}if(m=/^--(?:input|output|error)(?:[= ]?\S+)?(?:\s+|$)/i.exec(rest),m){rest=rest.slice(m[0].length);continue}if(/^--\s+/.test(rest)){rest=rest.replace(/^--\s+/,"");break}break}return withTail(rest.trim()||null)}return null}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=new RegExp(`${CMD_STRIP_PREFIX.source}"?(.*?)"?\\s*$`,"is").exec(t);if(cmdExeMatch)return cmdExeMatch[1].trim();let psCommandMatch=new RegExp(`${PS_STRIP_PREFIX.source}(.+)$`,"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]??shellMatch[2]??shellMatch[3]).trim();let evalMatch=/^eval\s+(.+)$/is.exec(t);if(evalMatch)return evalMatch[1].replace(/^["']|["']$/g,"").trim();let envPrefix=/^env(?:\s+(?:[A-Za-z_][A-Za-z0-9_]*=\S+|(?:-[i0vVh]*[uUCSaP]|--u(?:n(?:s(?:e(?:t)?)?)?)?|--c(?:h(?:d(?:i(?:r)?)?)?)?|--a(?:r(?:g(?:v(?:0)?)?)?)?|--s(?:p(?:l(?:i(?:t(?:-(?:s(?:t(?:r(?:i(?:n(?:g)?)?)?)?)?)?)?)?)?)?)?|--e(?:n(?:v(?:0(?:-(?:f(?:r(?:o(?:m)?)?)?)?)?)?)?)?)\s+\S+|-\S+|--[A-Za-z][A-Za-z0-9-]*))*\s+(.+)$/is,launcherInner=dcStripExecutionLauncher(t),prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??envPrefix.exec(t)??(launcherInner!==null&&launcherInner!==""?[t,launcherInner]:null)??/^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===`
|
|
753
|
+
`||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=path59.resolve(cwd,targetPath),normalizedCwd=path59.resolve(cwd),ancestors=[],current=normalizedTarget;while(!0){let rel=path59.relative(normalizedCwd,current);if(rel===".."||rel.startsWith(`..${path59.sep}`)||path59.isAbsolute(rel))break;if(ancestors.push(current),rel==="")break;let parent=path59.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat9=null;try{stat9=fsSync6.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(stat9.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,path59.sep),lstatBlock=dcLstatAncestorWalk(filesystemTarget,cwd);if(lstatBlock)return lstatBlock;let basename12=path59.basename(filesystemTarget);if(dcPathComponents(t).length===1&&DC_SAFE_TARGETS.has(basename12))continue;if(DC_FS_ROOTS.has(t)||DC_FS_ROOTS.has(t.replace(/\//g,"\\")))return`BLOCKED: Destructive command targets filesystem root "${t}"`;if(path59.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 normalize8=(value)=>{let normalized=path59.posix.normalize(value.replace(/\\/g,"/")).replace(/^\.\//,"").replace(/\/$/,"");return process.platform==="win32"?normalized.toLowerCase():normalized},scope=normalize8(scopeEntry),candidate=normalize8(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,path59.sep),resolved=path59.resolve(input.cwd,filesystemTarget),relative13=path59.relative(path59.resolve(input.cwd),resolved);if(relative13===""||relative13===".."||relative13.startsWith(`..${path59.sep}`)||path59.isAbsolute(relative13))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUTSIDE_WORKSPACE",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not strictly contained by the workspace.`};let basename12=path59.basename(resolved);if(!DC_SAFE_TARGETS.has(basename12))return{allowed:!1,code:"DESTRUCTIVE_TARGET_NOT_SAFE_ARTIFACT",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not an allowlisted build/cache artifact.`};let normalizedRelative=relative13.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=path59.resolve(cwd,target),rel=path59.relative(cwd,resolved);if(rel.startsWith("..")||path59.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=path59.resolve(cwd,target),rel=path59.relative(cwd,resolved);if(rel.startsWith("..")||path59.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=path59.resolve(cwd,target),rel=path59.relative(cwd,resolved);if(rel.startsWith("..")||path59.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 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(()=>{init_shell_executor_context();init_shell_write_detect();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 createHash30}from"node:crypto";function digest2(value){return createHash30("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 path60 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)=>path60.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});class Reader{src;pos=0;constructor(src){this.src=src}eof(){return this.pos>=this.src.length}peek(){return this.src[this.pos]??""}skipWs(){while(!this.eof()&&WHITESPACE.test(this.peek()))this.pos+=1}eat(ch){if(this.peek()===ch)return this.pos+=1,!0;return!1}eatWord(word){if(!this.src.startsWith(word,this.pos))return!1;let next=this.src[this.pos+word.length]??"";if(next!==""&&IDENT_PART.test(next))return!1;return this.pos+=word.length,!0}ident(){if(!IDENT_START.test(this.peek()))return null;let start=this.pos;this.pos+=1;while(!this.eof()&&IDENT_PART.test(this.peek()))this.pos+=1;return this.src.slice(start,this.pos)}string(){let quote=this.peek();if(quote!=='"'&"e!=="'")return null;this.pos+=1;let out="";while(!this.eof()){let ch=this.peek();if(this.pos+=1,ch===quote)return out;if(ch===`
|
|
754
754
|
`||ch==="\r")return null;if(ch==="\\"){let esc2=this.peek();if(!SIMPLE_ESCAPES.has(esc2))return null;this.pos+=1,out+=esc2;continue}out+=ch}return null}number(){let m=/^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(this.src.slice(this.pos));if(!m)return!1;return this.pos+=m[0].length,!0}}function parseValue(r,depth){if(depth>8)return!1;r.skipWs();let ch=r.peek();if(ch==='"'||ch==="'")return r.string()!==null;if(ch==="{")return parseObject(r,depth+1);if(ch==="[")return parseArray(r,depth+1);if(r.eatWord("true")||r.eatWord("false")||r.eatWord("null"))return!0;return r.number()}function parseArray(r,depth){if(!r.eat("["))return!1;if(r.skipWs(),r.eat("]"))return!0;for(;;){if(!parseValue(r,depth))return!1;if(r.skipWs(),r.eat(",")){if(r.skipWs(),r.eat("]"))return!0;continue}return r.eat("]")}}function parseObject(r,depth){if(!r.eat("{"))return!1;if(r.skipWs(),r.eat("}"))return!0;for(;;){r.skipWs();let key=r.peek()==='"'||r.peek()==="'"?r.string():r.ident();if(key===null||BLOCKED_NAMES.has(key))return!1;if(r.skipWs(),!r.eat(":"))return!1;if(!parseValue(r,depth))return!1;if(r.skipWs(),r.eat(",")){if(r.skipWs(),r.eat("}"))return!0;continue}return r.eat("}")}}function parseCallee(r){if(r.eatWord("search"))return!0;if(!r.eatWord("tools"))return!1;let segments=0;for(;;){if(r.skipWs(),r.eat(".")){r.skipWs();let name=r.ident();if(name===null||BLOCKED_NAMES.has(name))return!1;segments+=1;continue}if(r.peek()==="["){r.pos+=1,r.skipWs();let name=r.string();if(r.skipWs(),name===null||!SEGMENT_NAME.test(name)||BLOCKED_NAMES.has(name)||!r.eat("]"))return!1;segments+=1;continue}return segments>0}}function isSingleToolCallProgram(code){if(typeof code!=="string")return!1;if(code.length===0||code.length>20000)return!1;let r=new Reader(code);if(r.skipWs(),r.eatWord("return"),r.skipWs(),r.eatWord("await"),r.skipWs(),!parseCallee(r))return!1;if(r.skipWs(),!r.eat("("))return!1;if(r.skipWs(),!r.eat(")")){if(!parseValue(r,0))return!1;if(r.skipWs(),!r.eat(")"))return!1}return r.skipWs(),r.eat(";"),r.skipWs(),r.eof()}var BLOCKED_NAMES,IDENT_START,IDENT_PART,SEGMENT_NAME,WHITESPACE,SIMPLE_ESCAPES;var init_code_mode_program=__esm(()=>{BLOCKED_NAMES=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]),IDENT_START=/[A-Za-z_$]/,IDENT_PART=/[A-Za-z0-9_$]/,SEGMENT_NAME=/^[A-Za-z0-9_-]{1,100}$/,WHITESPACE=/[ \t\r\n]/,SIMPLE_ESCAPES=new Set(["n","r","t",'"',"'","\\","/"])});import*as fs33 from"node:fs";import*as path61 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=path61.resolve(target),resolvedRoot=path61.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path61.sep)?resolvedRoot:resolvedRoot+path61.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}function isProtectedPath2(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=path61.isAbsolute(filePath)?filePath:path61.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs33.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs33.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path61.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative14=normalizePath(path61.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 relative14===s||relative14.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative14.startsWith(e);return relative14===e||relative14.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]??[]]));if(isEpicModeConfigEnabled(pluginConfig))tools=Array.from(new Set([...tools,...EPIC_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(tool==="execute"&&config2?.permission_policy?.trust_code_mode_wrapper===!0&&input.hostCodeModeWrapper===!0&&isSingleToolCallProgram(input.args?.code))return{action:"allow",reason:"OpenCode v2 Code Mode wrapper around a single tool call (operator-trusted) — the nested call is classified individually",tier:"local"};if(tool==="swarm_command"&&mode!=="strict"&&input.swarmCommandReadOnly===!0)return{action:"allow",reason:"swarm_command is on the explicit read-only allowlist and permitted by the tool policy",tier:"local"};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(isProtectedPath2(path61.relative(input.directory,path61.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 FULL_AUTO_AUDITED_READ_ONLY_SWARM_TOOLS,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_config();init_normalize_tool_name();init_command_classifier();init_protected_path_policy();init_path();init_code_mode_program();FULL_AUTO_AUDITED_READ_ONLY_SWARM_TOOLS=["skill_list","skill_inspect","external_skill_list","external_skill_inspect","knowledge_receipt_status","retrieve_lane_output","lean_turbo_plan_lanes","plan_conflict_check","scope_validate","context_status","suggest_patch"],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(),...FULL_AUTO_AUDITED_READ_ONLY_SWARM_TOOLS,"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"]),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"]});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals59});import{existsSync as existsSync30,statSync as statSync19}from"node:fs";import*as path62 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(_internals59.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals59.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path62.join(grammarsDir,"tree-sitter.wasm");if(!_internals59.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
|
|
755
755
|
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 _internals59.parserInit({locateFile(scriptName){return path62.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?path62.join(thisDir,"grammars"):isCliBundle?path62.join(thisDir,"..","lang","grammars"):path62.join(thisDir,"lang","grammars")}function getGrammarsDirAbsolute(){let thisDir=_internals59.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=path62.join(getGrammarsDirAbsolute(),wasmFileName);if(!_internals59.fileExists(wasmPath))throw Error(`Grammar file not found for ${languageId}: ${wasmPath}
|
|
756
756
|
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)}
|
|
@@ -1045,7 +1045,7 @@ ${transcriptTail}`].join(`
|
|
|
1045
1045
|
`;if(Buffer.byteLength(line,"utf-8")>TRAJECTORY_LIMITS.maxLineBytes){warn(`[trajectory-store] Skipped oversize trajectory entry (${Buffer.byteLength(line,"utf-8")} B > ${TRAJECTORY_LIMITS.maxLineBytes} B)`);return}let trajectoryPath=getTrajectoryPath(sessionId,directory);await fs52.mkdir(path87.dirname(trajectoryPath),{recursive:!0});let lock=null;try{lock=await acquireTrajectoryLock(getLockPath(trajectoryPath));let tail=await readTailBytes(trajectoryPath,1),needsReframe=tail!==null&&tail.totalBytes>0&&tail.content!==`
|
|
1046
1046
|
`;if(tail!==null&&tail.totalBytes>sessionMaxBytesFor(maxLines))await compactTrajectoryFile(trajectoryPath,maxLines,directory);await fs52.appendFile(trajectoryPath,needsReframe?`
|
|
1047
1047
|
${line}`:line,"utf-8");let sinceCheck=(appendCheckCounters.get(key)??0)+1;if(sinceCheck>=TRAJECTORY_LIMITS.checkIntervalAppends){setAppendCheckCounter(key,0);let window2=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.readMaxBytes);if(window2!==null&&window2.totalBytes>0){let windowParsed=parseWindow(window2.content,window2.offset>0);if(window2.offset>0||windowParsed.entries.length>maxLines)await compactTrajectoryFile(trajectoryPath,maxLines,directory)}}else setAppendCheckCounter(key,sinceCheck)}finally{if(lock)await lock.release()}let cached3=_inMemoryTrajectoryCache.get(key)??[];setTrajectoryCache(key,[...cached3,entry],maxLines)})}catch(err){let busy=err instanceof Error&&err.message.includes("lock busy");if(log(`[trajectory-store] Failed to append trajectory entry: ${err}`),busy){skippedLockAppends+=1;let now=Date.now();if(now-lastAppendSkipEventAtMs>=TRAJECTORY_LIMITS.appendSkipEventCooldownMs)lastAppendSkipEventAtMs=now,emitTrajectoryHealth(directory,{trigger:"append_skip",retained_count:0,dropped_count:0,corrupt_count:0,bytes:0,limit_bytes:0}),skippedLockAppends=0}}}async function readTrajectoryWithCoverage(sessionId,directory,maxLines=1000){try{let trajectoryPath=getTrajectoryPath(sessionId,directory),tail=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.readMaxBytes),checkpoint2=await readCheckpointByPath(getMetaPath2(trajectoryPath));if(tail===null)return{entries:[],coverage:"empty",droppedByCompaction:checkpoint2?.droppedEntries??0,skippedMalformed:0};let parsed=parseWindow(tail.content,tail.offset>0),key=compositeSessionKey(directory,sessionId);setTrajectoryCache(key,parsed.entries,maxLines);let dropped=checkpoint2?.droppedEntries??0,droppedBytes=checkpoint2?.droppedBytes??0,coverage=parsed.entries.length===0&&tail.totalBytes===0?"empty":tail.offset>0||dropped>0||droppedBytes>0?"truncated":"complete";return{entries:parsed.entries,coverage,droppedByCompaction:dropped,skippedMalformed:parsed.skippedMalformed+parsed.skippedOversize}}catch(err){if(err.code==="ENOENT")return{entries:[],coverage:"empty",droppedByCompaction:0,skippedMalformed:0};return log(`[trajectory-store] Failed to read trajectory: ${err}`),{entries:[],coverage:"empty",droppedByCompaction:0,skippedMalformed:0}}}async function readTrajectory(sessionId,directory,maxLines){return(await readTrajectoryWithCoverage(sessionId,directory,maxLines)).entries}async function getCurrentStep(sessionId,directory){try{let trajectoryPath=getTrajectoryPath(sessionId,directory),maxStep=(await readCheckpointByPath(getMetaPath2(trajectoryPath)))?.highestStep??0,tail=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.stepReadMaxBytes);if(tail!==null&&tail.totalBytes>0){let parsed=parseWindow(tail.content,tail.offset>0);if(parsed.maxStep>maxStep)maxStep=parsed.maxStep}return maxStep}catch(err){if(err.code==="ENOENT")return 0;return log(`[trajectory-store] Failed to get current step: ${err}`),0}}function scheduleTrajectoryCleanup(directory){let now=Date.now();if(now-lastCleanupScheduledAtMs<TRAJECTORY_LIMITS.cleanupDebounceMs)return;lastCleanupScheduledAtMs=now,cleanupOldTrajectoryFiles(directory).catch(()=>{})}async function cleanupOldTrajectoryFiles(directory,maxAgeDays=TRAJECTORY_LIMITS.defaultMaxAgeDays){let cutoffMs=maxAgeDays*24*60*60*1000,now=Date.now(),removed=0,retained=0;for(let subdir of["trajectories","replays"]){if(removed>=TRAJECTORY_LIMITS.maxDeletionsPerRun)break;try{let dirPath=trajectorySwarmPath(directory,subdir),entries=await fs52.readdir(dirPath,{withFileTypes:!0}),candidates=[];for(let entry of entries){if(!entry.isFile())continue;if(entry.name.endsWith(".lock"))continue;let filePath=path87.join(dirPath,entry.name);try{let stat11=await fs52.stat(filePath);candidates.push({name:entry.name,filePath,effectiveMtimeMs:Math.min(stat11.mtimeMs,now)})}catch{}}let deleted=new Set,removeCandidate2=async(candidate)=>{if(await fs52.unlink(candidate.filePath),deleted.add(candidate.name),removed+=1,candidate.name.endsWith(".jsonl")){let metaSibling=`${candidate.filePath}.meta.json`;await fs52.unlink(metaSibling).catch(()=>{})}};for(let candidate of candidates){if(removed>=TRAJECTORY_LIMITS.maxDeletionsPerRun)break;if(now-candidate.effectiveMtimeMs>cutoffMs)await removeCandidate2(candidate).catch(()=>{})}let remainingJsonl=candidates.filter((c)=>!deleted.has(c.name)&&c.name.endsWith(".jsonl")).sort((a,b)=>b.effectiveMtimeMs-a.effectiveMtimeMs);retained+=remainingJsonl.length;while(remainingJsonl.length>TRAJECTORY_LIMITS.maxFilesPerDir&&removed<TRAJECTORY_LIMITS.maxDeletionsPerRun){let oldest=remainingJsonl.pop();if(oldest===void 0)break;await removeCandidate2(oldest).catch(()=>{}),retained-=1}}catch{}}if(removed>0)emitTrajectoryHealth(directory,{trigger:"cleanup",retained_count:retained,dropped_count:removed,corrupt_count:0,bytes:0,limit_bytes:TRAJECTORY_LIMITS.maxFilesPerDir}),skippedLockAppends=0}var MAX_TRACKED_TRAJECTORY_SESSIONS=500,TRAJECTORY_LIMITS,_internals81,skippedLockAppends=0,lastAppendSkipEventAtMs=0,_inMemoryTrajectoryCache,appendChains2,appendCheckCounters,lastCleanupScheduledAtMs=0;var init_trajectory_store=__esm(()=>{init_learning_health();init_utils2();init_telemetry();init_atomic_write();init_canonical_root();init_logger();TRAJECTORY_LIMITS={checkIntervalAppends:25,readMaxBytes:1048576,stepReadMaxBytes:65536,compactMaxBytes:1048576,maxLineBytes:65536,estimatedLineBytes:512,minSessionMaxBytes:65536,lockRetries:20,lockRetryDelayMs:5,lockStaleMs:300000,maxFilesPerDir:200,maxDeletionsPerRun:256,defaultMaxAgeDays:7,cleanupDebounceMs:600000,appendSkipEventCooldownMs:60000};_internals81={telemetry};_inMemoryTrajectoryCache=new Map;appendChains2=new Map,appendCheckCounters=new Map});function resetPrmSessionState(session,sessionId){if(session.prmEscalationTracker=void 0,session.prmInitialized=!1,session.prmPatternCounts=new Map,session.prmEscalationLevel=0,session.prmLastPatternDetected=null,session.prmHardStopPending=!1,session.prmHardStopInjectPending=!1,session.prmTrajectoryStep=0,session.prmInjectedAdvisoryKeys=new Set,session.prmStruckEpisodes=new Map,session.prmLadderCounts=new Map,session.prmEpisodes=new Map,session.prmEpisodeGeneration=0,session.replayArtifactPath=null,sessionId)_internals82.clearTrajectoryCache(sessionId)}function resolvePrmPatternPersistenceOptions(learning){return{enabled:learning.prm_persistence.enabled,min_support:learning.prm_persistence.min_support,cooldown_ms:learning.prm_persistence.cooldown_ms,admission_enabled:learning.realtime_admission.enabled,max_queue_size:learning.realtime_admission.max_queue_size}}function createPrmHook(config3,directory,patternPersistence){async function toolAfter(context){if(!config3.enabled)return;let{sessionID}=context,session=_internals82.getAgentSession(sessionID);if(!session||!session.delegationActive)return;try{let sessionPrmState=session;if(!sessionPrmState.prmInitialized)sessionPrmState.prmInitialized=!0,_internals82.scheduleTrajectoryCleanup(directory);let cachedTrajectory=_internals82.getInMemoryTrajectory(sessionID,directory),trajectory=cachedTrajectory;if(cachedTrajectory.length===0){let coldRead=await _internals82.readTrajectoryWithCoverage(sessionID,directory,config3.max_trajectory_lines);if(trajectory=coldRead.entries,coldRead.coverage==="truncated")log(`[prm] session ${sessionID} trajectory window is partial: ${coldRead.droppedByCompaction} older entries were dropped by compaction (pattern detection runs on the newest retained window)`)}let detectionResult=_internals82.detectPatterns(trajectory,config3,session.prmTrajectoryStep);if(detectionResult.matches.length===0)return;session.prmStruckEpisodes??=new Map;let struckEpisodes=session.prmStruckEpisodes,strikeable=[],claimedThisTick=new Set;for(let match of[...detectionResult.matches].sort((a,b)=>a.stepRange[0]-b.stepRange[0])){if(claimedThisTick.has(match.pattern))continue;let episodeKey=`${match.pattern}|${match.stepRange[0]}`,struckAtCount=struckEpisodes.get(episodeKey);if(struckAtCount!==void 0){let threshold=resolvePatternThreshold(config3,match.pattern);if(match.occurrenceCount<struckAtCount+threshold)continue}claimedThisTick.add(match.pattern),strikeable.push(match)}if(strikeable.length===0){if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step;return}for(let match of strikeable){let episodeKey=`${match.pattern}|${match.stepRange[0]}`;struckEpisodes.delete(episodeKey),struckEpisodes.set(episodeKey,match.occurrenceCount)}while(struckEpisodes.size>MAX_TRACKED_EPISODES){let oldest=struckEpisodes.keys().next().value;if(oldest===void 0)break;struckEpisodes.delete(oldest)}if(patternPersistence?.enabled)for(let match of strikeable){let observation=_internals82.recordPatternObservation(sessionID,match,{minSupport:patternPersistence.min_support,cooldownMs:patternPersistence.cooldown_ms});if(observation.persistable&&observation.candidate){try{await _internals82.appendInsightCandidates(directory,[observation.candidate])}catch(err){warn(`[prm] insight-candidate append failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}if(patternPersistence.admission_enabled)_internals82.enqueueCandidate(sessionID,observation.candidate,{maxQueueSize:patternPersistence.max_queue_size})}}let escalationTracker=sessionPrmState.prmEscalationTracker;if(!sessionPrmState.replayArtifactPath)sessionPrmState.replayArtifactPath=await _internals82.startReplayRecording(sessionID,directory);let artifactPath=sessionPrmState.replayArtifactPath;if(!escalationTracker){let initialState=session.prmLastPatternDetected?{patternCounts:new Map(session.prmLadderCounts??[]),escalationLevel:session.prmEscalationLevel,lastPatternDetected:session.prmLastPatternDetected,hardStopPending:session.prmHardStopPending,episodes:new Map(session.prmEpisodes??[]),generation:session.prmEpisodeGeneration??0}:void 0;escalationTracker=new EscalationTracker(sessionID,initialState),sessionPrmState.prmEscalationTracker=escalationTracker}let previousEscalationLevel=session.prmEscalationLevel,tickHardStop=!1;for(let match of strikeable){let correction=_internals82.generateCourseCorrection(match,trajectory),formattedCorrection=_internals82.formatCourseCorrectionForInjection(correction),escalationLevel=0,hardStopPending=!1,hardStopTerminal=!1;if(config3.escalation_enabled!==!1){let escalationResult=escalationTracker.recordDetection(match);escalationLevel=escalationResult.level,hardStopPending=escalationResult.hardStop,hardStopTerminal=escalationResult.terminal}let prmDedupeKey=`prm:${resolveLadderKey(match)}:${escalationLevel}${hardStopTerminal?":terminal":""}:g${escalationTracker.getGeneration()}`;if(!session.prmInjectedAdvisoryKeys?.has(prmDedupeKey))pushAdvisory(session,`[${prmDedupeKey}] ${formattedCorrection}`,{dedupeKey:prmDedupeKey}),session.prmInjectedAdvisoryKeys??=new Set,session.prmInjectedAdvisoryKeys.add(prmDedupeKey);if(session.prmPatternCounts.set(match.pattern,(session.prmPatternCounts.get(match.pattern)??0)+1),session.prmLadderCounts=escalationTracker.getLadderCounts(),session.prmEpisodes=escalationTracker.getEpisodes(),session.prmEpisodeGeneration=escalationTracker.getGeneration(),session.prmEscalationLevel=escalationLevel,session.prmLastPatternDetected=match,tickHardStop=tickHardStop||hardStopPending,session.prmHardStopPending=tickHardStop,tickHardStop)session.prmHardStopInjectPending=!0;if(_internals82.telemetry.prmPatternDetected(sessionID,match.pattern,match.severity,match.category,match.stepRange),_internals82.telemetry.prmCourseCorrectionInjected(sessionID,match.pattern,escalationLevel),artifactPath)await _internals82.recordReplayEntry(artifactPath,sessionID,{type:"pattern_detected",data:{pattern:match.pattern,severity:match.severity,category:match.category,stepRange:match.stepRange,description:match.description,affectedAgents:match.affectedAgents,affectedTargets:match.affectedTargets,occurrenceCount:match.occurrenceCount}});if(artifactPath)await _internals82.recordReplayEntry(artifactPath,sessionID,{type:"course_correction",data:{pattern:correction.pattern,alert:correction.alert,category:correction.category,guidance:correction.guidance,action:correction.action,stepRange:correction.stepRange,escalationLevel}})}if(artifactPath&&session.prmEscalationLevel>previousEscalationLevel)await _internals82.recordReplayEntry(artifactPath,sessionID,{type:"escalation",data:{previousLevel:previousEscalationLevel,newLevel:session.prmEscalationLevel,hardStopPending:session.prmHardStopPending}});if(artifactPath&&session.prmHardStopPending&&previousEscalationLevel<3)await _internals82.recordReplayEntry(artifactPath,sessionID,{type:"hard_stop",data:{escalationLevel:session.prmEscalationLevel,triggeredAt:new Date().toISOString()}});if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step}catch(err){log(`[prm] toolAfter error for session ${sessionID}: ${err}`)}}return{toolAfter}}var _internals82,MAX_TRACKED_EPISODES=256;var init_prm=__esm(()=>{init_course_correction();init_escalation();init_pattern_detector();init_micro_reflector();init_candidate_queue();init_prm_pattern_support();init_state();init_telemetry();init_logger();init_course_correction();init_escalation();init_pattern_detector();init_replay();init_trajectory_store();_internals82={getAgentSession,readTrajectoryWithCoverage,getInMemoryTrajectory,detectPatterns,generateCourseCorrection,formatCourseCorrectionForInjection,scheduleTrajectoryCleanup,clearTrajectoryCache,recordReplayEntry,startReplayRecording,telemetry,recordPatternObservation,enqueueCandidate,appendInsightCandidates}});import{createHash as createHash39,createHmac,randomBytes as randomBytes6,timingSafeEqual}from"node:crypto";import*as fs53 from"node:fs";import*as fsp4 from"node:fs/promises";import*as path88 from"node:path";function normalizedIdentity(value,label){let normalized=value.trim();if(!normalized||normalized.length>256)throw Error(`ROUTE_RECEIPT_INVALID_IDENTITY: ${label}`);return normalized}function uniqueIdentities(values,label){let result=values.map((value)=>normalizedIdentity(value,label));if(new Set(result).size!==result.length)throw Error(`ROUTE_RECEIPT_DUPLICATE: ${label}`);return[...result]}function slotsFor(role,identities,provided,taskId){let slots=provided?uniqueIdentities(provided,`${role} slots`):identities.map((_,index)=>`${taskId}:${role}:${index+1}`);if(slots.length!==identities.length)throw Error(`ROUTE_RECEIPT_SLOT_COUNT_MISMATCH: ${role}`);return slots}function buildReviewRouteReceipt(input){let sessionId=normalizedIdentity(input.sessionId,"sessionId"),taskId=normalizedIdentity(input.taskId,"taskId"),reviewers=uniqueIdentities(input.requiredReviewers,"reviewers"),testEngineers=uniqueIdentities(input.requiredTestEngineers,"test_engineers");return ReviewRouteReceiptSchema.parse({kind:"review_route_receipt",version:REVIEW_ROUTE_RECEIPT_VERSION,sessionId,taskId,complexity:input.complexity,semanticRisk:input.semanticRisk,required:{reviewers:reviewers.length,testEngineers:testEngineers.length},identities:{reviewers,testEngineers},slots:{reviewers:slotsFor("reviewer",reviewers,input.reviewerSlots,taskId),testEngineers:slotsFor("test_engineer",testEngineers,input.testEngineerSlots,taskId)},createdAt:input.createdAt??new Date().toISOString()})}function buildReviewRouteRouterError(input){return ReviewRouteRouterErrorReceiptSchema.parse({kind:"review_route_router_error",version:REVIEW_ROUTE_RECEIPT_VERSION,code:input.code,failOpen:!0,...input.sessionId?{sessionId:input.sessionId}:{},...input.taskId?{taskId:input.taskId}:{},...input.detail?{detail:input.detail.slice(0,512)}:{},createdAt:input.createdAt??new Date().toISOString()})}function buildReviewRoutePending(input){return ReviewRoutePendingReceiptSchema.parse({kind:"review_route_pending",version:REVIEW_ROUTE_RECEIPT_VERSION,sessionId:input.sessionId,taskId:input.taskId,createdAt:input.createdAt??new Date().toISOString()})}function routeReceiptRelativePath(sessionId,taskId){let normalizedSessionId=normalizedIdentity(sessionId,"sessionId"),normalizedTaskId=normalizedIdentity(taskId,"taskId"),encodeIdentity=(normalized)=>{let encoded=Buffer.from(normalized,"utf8").toString("base64url").replace(/-/g,"~");return encoded.length<=180?encoded:`sha256_${createHash39("sha256").update(normalized,"utf8").digest("hex")}`},safeSession=encodeIdentity(normalizedSessionId),safeTask=encodeIdentity(normalizedTaskId),basename16=`${safeSession}--${safeTask}.json`,boundedBasename=Buffer.byteLength(basename16,"utf8")<=255?basename16:`sha256_${createHash39("sha256").update(JSON.stringify([normalizedSessionId,normalizedTaskId]),"utf8").digest("hex")}.json`;return path88.join("pr-review","route-receipts",boundedBasename)}function routeReceiptPath(directory,sessionId,taskId){return validateSwarmPath(directory,routeReceiptRelativePath(sessionId,taskId))}async function ensureSafeParent(directory,filePath){assertProjectRoot(directory,void 0,"review route receipt");let swarmRoot=path88.resolve(directory,".swarm"),parent=path88.dirname(filePath),relative21=path88.relative(swarmRoot,parent);if(relative21===".."||relative21.startsWith(`..${path88.sep}`)||path88.isAbsolute(relative21))throw Error("ROUTE_RECEIPT_PATH_ESCAPE: route receipt is outside .swarm");await fsp4.mkdir(parent,{recursive:!0});for(let candidate of[swarmRoot,path88.join(swarmRoot,"pr-review"),parent]){let stat11=await fsp4.lstat(candidate);if(!stat11.isDirectory()||stat11.isSymbolicLink())throw Error("ROUTE_RECEIPT_PATH_UNSAFE: receipt parent is not a real directory")}}function routeReceiptSecretPath(projectRoot){let hiveDir=path88.resolve(resolveHiveDataDir());if(projectRoot){let root=path88.resolve(projectRoot),relative21=path88.relative(root,hiveDir);if(relative21===""||!path88.isAbsolute(relative21)&&!relative21.startsWith(`..${path88.sep}`))throw Error("ROUTE_RECEIPT_SECRET_UNSAFE_PATH: app-data key path is inside the project root")}return path88.join(hiveDir,ROUTE_RECEIPT_SECRET_FILE)}function parseRouteReceiptSecret(raw){let value=raw.trim();return/^[0-9a-f]{64}$/.test(value)?Buffer.from(value,"hex"):null}async function readRouteReceiptSecret(projectRoot){let secretPath=routeReceiptSecretPath(projectRoot);try{let stat11=await fsp4.lstat(secretPath);if(stat11.isSymbolicLink()||!stat11.isFile())throw Error("ROUTE_RECEIPT_SECRET_INVALID");let secret=parseRouteReceiptSecret(await fsp4.readFile(secretPath,"utf8"));if(!secret)throw Error("ROUTE_RECEIPT_SECRET_INVALID");return secret}catch(error93){if(error93.code!=="ENOENT")throw error93}await fsp4.mkdir(path88.dirname(secretPath),{recursive:!0});let generated=randomBytes6(32);try{await fsp4.writeFile(secretPath,generated.toString("hex"),{encoding:"utf8",flag:"wx",mode:384})}catch(error93){if(error93.code!=="EEXIST")throw error93;return readRouteReceiptSecret(projectRoot)}try{await fsp4.chmod(secretPath,384)}catch{}return generated}function readRouteReceiptSecretSync(projectRoot){try{let secretPath=routeReceiptSecretPath(projectRoot),stat11=fs53.lstatSync(secretPath);if(stat11.isSymbolicLink()||!stat11.isFile())return null;return parseRouteReceiptSecret(fs53.readFileSync(secretPath,"utf8"))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_SECRET_UNSAFE_PATH:"))throw error93;return null}}function canonicalRouteReceiptJson(value){if(value===null||typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((entry)=>canonicalRouteReceiptJson(entry)).join(",")}]`;return`{${Object.entries(value).filter(([,entry])=>entry!==void 0).sort(([left],[right])=>left.localeCompare(right)).map(([key,entry])=>`${JSON.stringify(key)}:${canonicalRouteReceiptJson(entry)}`).join(",")}}`}function routeReceiptMacPayload(receipt){let{mac:_mac2,...payload}=receipt;return`${ROUTE_RECEIPT_MAC_CONTEXT}${canonicalRouteReceiptJson(payload)}`}function computeRouteReceiptMac(receipt,secret){return createHmac("sha256",secret).update(routeReceiptMacPayload(receipt),"utf8").digest("hex")}function hasValidRouteReceiptMac(receipt,secret){if(!secret||!receipt.mac||!RouteReceiptMacSchema.safeParse(receipt.mac).success)return!1;let expected=Buffer.from(computeRouteReceiptMac(receipt,secret),"hex"),supplied=Buffer.from(receipt.mac,"hex");return supplied.length===expected.length&&timingSafeEqual(supplied,expected)}function authenticatePersistedRouteReceipt(receipt,secret){if(hasValidRouteReceiptMac(receipt,secret))return receipt;throw Error("ROUTE_RECEIPT_AUTH_INVALID: receipt MAC is missing or invalid")}async function persistReviewRouteReceipt(input){let parsed=input.receipt.kind==="review_route_receipt"?ReviewRouteReceiptSchema.parse(input.receipt):input.receipt.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.parse(input.receipt):ReviewRoutePendingReceiptSchema.parse(input.receipt),sessionId=parsed.kind==="review_route_receipt"?parsed.sessionId:parsed.sessionId??"router",taskId=parsed.kind==="review_route_receipt"?parsed.taskId:parsed.taskId??"unknown",filePath=routeReceiptPath(input.projectRoot,sessionId,taskId);await ensureSafeParent(input.projectRoot,filePath);let authenticated={...parsed,mac:computeRouteReceiptMac(parsed,await readRouteReceiptSecret(input.projectRoot))},encoded=JSON.stringify(authenticated,null,2);if(Buffer.byteLength(encoded,"utf8")>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_OVERSIZED: receipt exceeds size bound");return await atomicWriteFile(filePath,`${encoded}
|
|
1048
|
-
`),{persisted:!0,path:filePath}}function readReviewRouteReceiptSync(input){let filePath=routeReceiptPath(input.projectRoot,input.sessionId,input.taskId),stat11;try{stat11=fs53.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}if(stat11.isSymbolicLink()||!stat11.isFile()||stat11.size>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_UNREADABLE: receipt is not a bounded regular file");let value;try{value=JSON.parse(fs53.readFileSync(filePath,"utf8"))}catch(error93){if(error93 instanceof SyntaxError)throw Error("ROUTE_RECEIPT_INVALID_JSON: receipt is not valid JSON");throw error93}let parsed=typeof value==="object"&&value!==null&&value.kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):value.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);if(!parsed.success)throw Error("ROUTE_RECEIPT_INVALID: receipt failed schema validation");let authenticated=authenticatePersistedRouteReceipt(parsed.data,readRouteReceiptSecretSync(input.projectRoot));if((authenticated.kind==="review_route_receipt"||authenticated.kind==="review_route_pending")&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");if(authenticated.kind==="review_route_router_error"&&authenticated.sessionId!==void 0&&authenticated.taskId!==void 0&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");return authenticated}function parseRouteReceipt(value){if(!value||typeof value!=="object")return null;let kind=value.kind,parsed=kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);return parsed.success?parsed.data:null}function fail(reason){return{canAdvance:!1,mode:"enforced",reason}}function enforceReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route=parseRouteReceipt(input.routeReceipt);if(!route)return fail("ROUTE_RECEIPT_MISSING");if(route.kind==="review_route_router_error"){if(input.sessionId&&(!route.sessionId||!route.taskId||route.sessionId!==input.sessionId||route.taskId!==input.taskId))return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");return{canAdvance:!0,mode:"fail_open",routerFailure:route.code}}if(route.kind==="review_route_pending")return fail("ROUTE_RECEIPT_PENDING");if(input.sessionId&&route.sessionId!==input.sessionId||input.taskId&&route.taskId!==input.taskId)return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");if(route.required.reviewers!==route.identities.reviewers.length||route.required.testEngineers!==route.identities.testEngineers.length)return fail("ROUTE_RECEIPT_COUNT_MISMATCH");let expected=new Map;for(let identity of route.identities.reviewers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"reviewer")}for(let identity of route.identities.testEngineers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"test_engineer")}if(input.requireEvidenceBindings&&input.requireCompleteEvidence===!1&&expected.size>0&&!input.expectedDispatch)return fail("ROUTE_RECEIPT_DISPATCH_REQUIRED");let seen=new Set,seenSlots=new Set;for(let evidence of input.receipts){if(input.requireEvidenceBindings&&(!evidence.sessionId||!evidence.taskId||!evidence.slotId||!evidence.callId||!evidence.childSessionId||typeof evidence.generation!=="number"))return fail("ROUTE_RECEIPT_BINDING_MISSING");let identity=evidence.identity.trim();if(!identity||identity.length>256)return fail("ROUTE_RECEIPT_INVALID_IDENTITY");let expectedRole=expected.get(identity);if(!expectedRole)return fail("ROUTE_RECEIPT_IDENTITY_UNLISTED");if(expectedRole!==evidence.role)return fail("ROUTE_RECEIPT_ROLE_MISMATCH");if(seen.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");if(evidence.sessionId&&evidence.sessionId!==route.sessionId)return fail("ROUTE_RECEIPT_SESSION_MISMATCH");if(evidence.taskId&&evidence.taskId!==route.taskId)return fail("ROUTE_RECEIPT_TASK_MISMATCH");if(evidence.slotId){if(seenSlots.has(evidence.slotId))return fail("ROUTE_RECEIPT_DUPLICATE");let slots=evidence.role==="reviewer"?route.slots?.reviewers:route.slots?.testEngineers;if(slots&&!slots.includes(evidence.slotId))return fail("ROUTE_RECEIPT_SLOT_UNLISTED");if(slots){let expectedIndex=evidence.role==="reviewer"?route.identities.reviewers.indexOf(identity):route.identities.testEngineers.indexOf(identity);if(expectedIndex<0||slots[expectedIndex]!==evidence.slotId)return fail("ROUTE_RECEIPT_SLOT_MISMATCH")}seenSlots.add(evidence.slotId)}seen.add(identity)}if(input.expectedDispatch){let expected2=input.expectedDispatch,matching=input.receipts.find((evidence)=>evidence.role===expected2.role&&evidence.identity===expected2.identity);if(!matching||matching.callId!==expected2.callId||matching.childSessionId!==expected2.childSessionId||matching.generation!==expected2.generation)return fail("ROUTE_RECEIPT_DISPATCH_MISMATCH")}if(input.requireCompleteEvidence!==!1&&seen.size!==expected.size)return fail("ROUTE_RECEIPT_INCOMPLETE");return{canAdvance:!0,mode:"enforced"}}function enforcePersistedReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route;try{route=readReviewRouteReceiptSync({projectRoot:input.projectRoot,sessionId:input.sessionId,taskId:input.taskId})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_AUTH_INVALID:"))return fail("ROUTE_RECEIPT_AUTH_INVALID");throw error93}if(!route&&input.legacyUnrouted)return{canAdvance:!0,mode:"legacy_unrouted",reason:"legacy_unrouted: route receipt predates version-1 enforcement"};return enforceReviewRouteReceipt({enforcementEnabled:!0,routeReceipt:route,receipts:input.receipts,sessionId:input.sessionId,taskId:input.taskId,requireEvidenceBindings:input.requireEvidenceBindings,expectedDispatch:input.expectedDispatch,requireCompleteEvidence:input.requireCompleteEvidence})}var REVIEW_ROUTE_RECEIPT_VERSION=1,IdentitySchema,RouteReceiptMacSchema,ReviewRouteReceiptSchema,ReviewRouteRouterErrorReceiptSchema,ReviewRoutePendingReceiptSchema,MAX_ROUTE_RECEIPT_BYTES=65536,ROUTE_RECEIPT_SECRET_FILE="review-route-receipts.key",ROUTE_RECEIPT_MAC_CONTEXT="opencode-swarm/review-route-receipt/v1\x00";var init_routing_enforcement=__esm(()=>{init_zod();init_task_file();init_utils2();init_hive_paths();init_project_boundary();IdentitySchema=exports_external.string().trim().min(1).max(256),RouteReceiptMacSchema=exports_external.string().regex(/^[0-9a-f]{64}$/,"route receipt MAC must be a SHA-256 HMAC"),ReviewRouteReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_receipt"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,complexity:exports_external.string().trim().min(1).max(80),semanticRisk:exports_external.string().trim().min(1).max(120),required:exports_external.object({reviewers:exports_external.number().int().nonnegative().max(16),testEngineers:exports_external.number().int().nonnegative().max(16)}),identities:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}),slots:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRouteRouterErrorReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_router_error"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),code:exports_external.enum(["NO_CHANGED_FILES","ROUTER_UNAVAILABLE","ROUTER_FAILED"]),failOpen:exports_external.literal(!0),sessionId:IdentitySchema.optional(),taskId:IdentitySchema.optional(),detail:exports_external.string().trim().max(512).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRoutePendingReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_pending"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict()});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),wal=await readWal2(walPath,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal(walPath,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal2(walPath,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal2(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function writeWal(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}async function ensureAuditEvent(directory,wal){if(hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))return;try{appendCoreEventSync(directory,{type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_REPAIR_AUDIT_LOCKED");throw error93}if(!hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}function workflowMatchesCommittedRepair(evidence,wal){let snapshot=getTaskWorkflowSnapshot(evidence);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence),existingWal=await readWal2(walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence,existingWal))return await ensureAuditEvent(options.directory,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed"&&options.currentPlanStatus!=="in_progress")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);if(existingWal===null&&options.currentPlanStatus==="in_progress"){let wedgeEscalated=!1;try{wedgeEscalated=getCoderRetryEscalationActions(options.directory,options.taskId,snapshot.retryEpoch).has("user_escalation")&&snapshot.retryCount>=3}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_REPAIR_ESCALATION_INDEX_UNREADABLE: cannot verify the retry-escalation wedge evidence for an in_progress repair (the core-event authority index is unreadable). The unreadable index is not content-restored: a later authority write rebuilds it from subsequent events only, so escalation evidence already folded out of the retained events window stays lost, and producers may refuse while the index is unreadable. "+"Recovery without discarding the events trail: re-dispatching the task re-runs the retry ladder from scratch and re-records the rungs; /swarm reset is the destructive full reset (it clears the plan, the events trail, and run state — session state is reset-session's charter and survives). Admission refuses to guess.");throw error93}if(!wedgeEscalated)throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus} — an in_progress task is repairable only once the coder retry ladder has recorded a durable user_escalation for its current retry epoch with retryCount at the threshold; no such record is visible for this task.`)}let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal(walPath,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal(walPath,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_core_events();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence,wal){let workflow=getTaskWorkflowSnapshot(evidence);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,readOnlyNoMutation:wal.readOnlyNoMutation,externalEvidence:wal.externalEvidence,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath){try{return await _internals83.applyTerminalEvidence(transaction,wal)}catch(error93){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal2(walPath,{...wal,state:"ABORTED"}),null;if(wal.externalEvidence===!0){if(!externalProofCurrent({title:plan.title,swarm:plan.swarm},task,evidence))throw Error(`TASK_TERMINAL_EXTERNAL_EVIDENCE_DIGEST_MISMATCH: ${walPath} records an external-evidence completion for task ${taskId}, but the current plan declaration no longer matches the attested declaration digest. Re-attest with /swarm attest ${taskId} (or re-plan the declaration), then re-run task-terminal recovery.`)}if(wal.readOnlyNoMutation===!0&&!evidenceAlreadyTerminal){let replayed;try{replayed=await peekPlanFromLedger(directory)}catch(error93){throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: could not inspect the authoritative plan ledger: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}if(replayed.truncated||replayed.badSuffix!==null)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");if(!replayed.plan)throw Error("TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: authoritative plan ledger has no replayable plan");let authoritativeTask=replayed.plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!authoritativeTask)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);if(wal.version===2){let identity=await readPlanEpochIdentity(directory,replayed.plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}plan=replayed.plan,task=authoritativeTask;let currentFiles=authoritativeTask.files_touched;if(!(Array.isArray(currentFiles)&¤tFiles.length===0)){if(authoritativeTask.status!==wal.oldPlanStatus&&authoritativeTask.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${authoritativeTask.status}`);if(authoritativeTask.status===wal.newPlanStatus&&authoritativeTask.status!==wal.oldPlanStatus){let oldStatus=TaskStatusSchema.safeParse(wal.oldPlanStatus);if(!oldStatus.success)throw Error(`TASK_TERMINAL_OLD_STATUS_INVALID: ${wal.oldPlanStatus}`);let rolledBackPlan=await updateTaskStatus(directory,taskId,oldStatus.data,{planLockAlreadyHeld:!0,terminalReconciliation:!0}),rolledBackTask=rolledBackPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(rolledBackTask?.status!==oldStatus.data)throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_ROLLBACK_FAILED: expected ${oldStatus.data}, found ${rolledBackTask?.status??"missing task"}`);plan=rolledBackPlan}throw await writeWal2(walPath,{...wal,state:"ABORTED"}),Error(`TASK_TERMINAL_READ_ONLY_SCOPE_CHANGED: task ${taskId} no longer has a known empty declared scope; terminal evidence was not applied`)}}if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence:await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence);await options.validateEvidence?.(evidence);let terminal=options.resolveTerminal?.(evidence)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&existingWal.readOnlyNoMutation===!0===(terminal.readOnlyNoMutation===!0)&&existingWal.externalEvidence===!0===(terminal.externalEvidence===!0)&&evidenceMatchesTerminal(evidence,existingWal))return{plan:options.currentPlan,evidence,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath}); found ${evidence?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,...terminal.readOnlyNoMutation===!0?{readOnlyNoMutation:!0}:{},...terminal.externalEvidence===!0?{externalEvidence:!0}:{},recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal2(walPath,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal2=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals83;var init_task_terminal=__esm(()=>{init_plan_schema();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals83={applyTerminalEvidence}});import*as fs54 from"node:fs";function storePath2(directory){return validateSwarmPath(directory,DEAD_LANE_RECLAIM_PATH)}function isDeadLaneReclaimEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return typeof candidate.lanePath==="string"&&candidate.lanePath.length>0&&typeof candidate.branchName==="string"&&typeof candidate.parentSessionId==="string"&&typeof candidate.taskId==="string"&&typeof candidate.reason==="string"&&typeof candidate.recordedAt==="number"}function readStore2(directory){try{let raw=fs54.readFileSync(storePath2(directory),"utf-8");if(raw.length>MAX_DEAD_LANE_RECLAIM_BYTES)return{schemaVersion:1,entries:[]};let parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{schemaVersion:1,entries:[]};return{schemaVersion:1,entries:parsed.entries.filter(isDeadLaneReclaimEntry)}}catch{return{schemaVersion:1,entries:[]}}}function writeStore2(directory,store){let entries=store.entries.slice(-MAX_DEAD_LANE_RECLAIMS);for(;;){let serialized2=JSON.stringify({schemaVersion:1,entries},null,2);if(serialized2.length<=MAX_DEAD_LANE_RECLAIM_BYTES||entries.length===0){if(entries.length<store.entries.length)log(`[dead-lane-reclaim] store bound dropped ${store.entries.length-entries.length} oldest entries (caps: ${MAX_DEAD_LANE_RECLAIMS} entries / ${MAX_DEAD_LANE_RECLAIM_BYTES} bytes)`);_internals84.atomicWriteSwarmFileSync(storePath2(directory),serialized2);return}entries=entries.slice(1)}}function recordDeadLaneReclaim(directory,entry){try{let filtered=readStore2(directory).entries.filter((existing)=>existing.lanePath!==entry.lanePath);filtered.push({...entry,recordedAt:Date.now()}),writeStore2(directory,{schemaVersion:1,entries:filtered})}catch(error93){log(`[dead-lane-reclaim] could not record stranded lane ${entry.lanePath}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function isLaneOwnedByActiveSession(lanePath,activeSessionIds,parentSessionId){if(activeSessionIds.has(parentSessionId??""))return!0;if(parentSessionId&&!lanePathIncludesSessionSegment(lanePath,parentSessionId))return!0;return!1}function lanePathIncludesSessionSegment(lanePath,sessionId){return lanePath.replace(/\\/g,"/").split("/").includes(sessionId)}async function isLaneDirty(lanePath){let proc;try{let options={cwd:lanePath,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:LANE_DIRTY_CHECK_TIMEOUT_MS,killProcessTree:!0};proc=_internals84.bunSpawn([_internals84.resolveGitExecutable(),"-C",lanePath,"status","--porcelain"],options);let stdout="";if(proc.stdout){let reader=proc.stdout.getReader();for(;;){let{done,value}=await reader.read();if(done||!value)break;if(stdout+=Buffer.from(value).toString("utf-8"),stdout.length>LANE_DIRTY_STDOUT_CAP_BYTES)break}}if(await proc.exited!==0)return!0;return stdout.trim().length>0}catch{return!0}finally{try{proc?.kill?.()}catch{}}}async function reclaimDeadLanes(directory,context={}){let result={reclaimed:[],retained:[]},store;try{store=readStore2(directory)}catch{return result}if(store.entries.length===0)return result;let activeSessionIds=new Set(context.activeSessionIds??[]),protectedPaths=new Set(context.protectedWorktreePaths??[]),retained=[];for(let entry of store.entries){let protectedLane=protectedPaths.has(entry.lanePath)||protectedPaths.has(_internals84.canonicalRootKeyFresh(entry.lanePath));if(_internals84.isLaneOwnedByActiveSession(entry.lanePath,activeSessionIds,entry.parentSessionId)||protectedLane){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"owned-by-active-session-or-protected"});continue}if(!await _internals84.pathExists(entry.lanePath))continue;if(await _internals84.isLaneDirty(entry.lanePath)){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"dirty-lane-preserved"});continue}_internals84.closeProjectDb(entry.lanePath);let removalError;try{let removal=await _internals84.removeWorktree(entry.lanePath,directory);if("error"in removal)removalError=removal.error}catch(error93){removalError=error93 instanceof Error?error93.message:String(error93)}if(removalError!==void 0){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:removalError});continue}result.reclaimed.push(entry.lanePath)}try{if(retained.length===0)fs54.rmSync(storePath2(directory),{force:!0});else writeStore2(directory,{schemaVersion:1,entries:retained})}catch(error93){log(`[dead-lane-reclaim] could not persist reclaim state: ${error93 instanceof Error?error93.message:String(error93)}`)}return result}async function pathExists2(target){try{return await fs54.promises.stat(target),!0}catch{return!1}}var DEAD_LANE_RECLAIM_PATH="dead-lane-reclaims.json",MAX_DEAD_LANE_RECLAIMS=512,MAX_DEAD_LANE_RECLAIM_BYTES=262144,LANE_DIRTY_CHECK_TIMEOUT_MS=5000,LANE_DIRTY_STDOUT_CAP_BYTES=4096,_internals84;var init_dead_lane_reclaim=__esm(()=>{init_project_db();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();init_utils2();_internals84={removeWorktree,closeProjectDb,isLaneOwnedByActiveSession,isLaneDirty,pathExists:pathExists2,bunSpawn,resolveGitExecutable,atomicWriteSwarmFileSync,canonicalRootKeyFresh}});function normalizeToForwardSlash(filePath){return filePath.replace(/\\/g,"/")}function matchesTier3(files){for(let file3 of files)if(isTier3Path(file3))return!0;return!1}function isTier3Path(filePath){let segments=normalizeToForwardSlash(filePath).split("/"),fileName=segments[segments.length-1]||"",fileBaseName=fileName.replace(/\.[^.]*$/,"").toLowerCase();if(TIER_3_EXACT_BASENAMES.has(fileBaseName))return!0;if(TIER_3_KEYWORD_PREFIX_RE.test(fileBaseName))return!0;for(let pattern of TIER_3_BASENAME_PATTERNS)if(pattern.test(fileName))return!0;for(let i=0;i<segments.length-1;i++)if(TIER_3_DIRECTORY_SEGMENTS.has(segments[i].toLowerCase()))return!0;return!1}var TIER_3_BASENAME_PATTERNS,TIER_3_EXACT_BASENAMES,TIER_3_KEYWORD_PREFIX_RE,TIER_3_DIRECTORY_SEGMENTS;var init_tier3_classifier=__esm(()=>{TIER_3_BASENAME_PATTERNS=[/^architect.*\.ts$/i,/^delegation.*\.ts$/i,/^guardrails?.*\.ts$/i,/^adversarial.*\.ts$/i,/^sanitiz.*\.ts$/i,/^security.*\.ts$/i],TIER_3_EXACT_BASENAMES=new Set(["auth","authenticate","authentication","authorization","permission","permissions","crypto","secret","secrets","secretscan"]),TIER_3_KEYWORD_PREFIX_RE=/^(auth|permission|crypto|secret|security)[-_.]/i,TIER_3_DIRECTORY_SEGMENTS=new Set(["auth","security","crypto","permission","secret"])});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win3210){return win3210===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils2=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state2={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state2.prefix="./";return output};exports.wrapOutput=(input,state2={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state2.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path89,{windows}={})=>{let segs=path89.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils2(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state2={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state2.maxDepth=0,!isPathSeparator(code))tokens.push(token);state2.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state2.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state2.maxDepth+=tokens[tokens.length-1].depth}state2.slashes=slashes,state2.parts=parts}return state2};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants5=require_constants(),utils=require_utils2(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants5,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants5.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse10=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants5.globChars(opts.windows),EXTGLOB_CHARS=constants5.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state2={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state2),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state2.index===len-1,peek=state2.peek=(n=1)=>input[state2.index+n],advance=state2.advance=()=>input[++state2.index]||"",remaining=()=>input.slice(state2.index+1),consume=(value2="",num=0)=>{state2.consumed+=value2,state2.index+=num},append=(token)=>{state2.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count2=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state2.start++,count2++;if(count2%2===0)return!1;return state2.negated=!0,state2.start++,!0},increment=(type)=>{state2[type]++,stack.push(type)},decrement=(type)=>{state2[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state2.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state2.output=state2.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state2.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state2.parens,token.output=state2.output,token.startIndex=state2.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state2.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal4=input.slice(token.startIndex,state2.index+1),body=input.slice(token.startIndex+2,state2.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open6=tokens[token.tokensIndex];open6.type="text",open6.value=literal4,open6.output=safeOutput||utils.escapeRegex(literal4);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state2.output=token.output+open6.output,state2.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse10(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state2.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc3,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc3)return esc3+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc3)return esc3+first+(rest?star:"");return star}return esc3?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state2.output=input,state2;return state2.output=utils.wrapOutput(output,state2,options),state2}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state2.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state2.brackets===0){push({type:"text",value});continue}}if(state2.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix13=POSIX_REGEX_SOURCE[rest2];if(posix13){if(prev.value=pre+posix13,state2.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state2.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state2.quotes=state2.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state2.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state2.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state2.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state2.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state2.output=state2.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state2.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state2.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open6={type:"brace",value,output:"(",outputIndex:state2.output.length,tokensIndex:state2.tokens.length};braces.push(open6),push(open6);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state2.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state2.output.slice(0,brace.outputIndex),toks=state2.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state2.output=out;for(let t of toks)state2.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state2.index===state2.start+1){state2.start=state2.index+1,state2.consumed="",state2.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state2.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state2.braces+state2.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state2.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state2.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state2.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state2.backtrack=!0,state2.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state2.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state2.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state2.output=prev.output,state2.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state2.globstar=!0,state2.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state2.output+=prior.output+prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state2.output=prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state2.output=state2.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state2.output+=prev.output,state2.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state2.index===state2.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state2.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state2.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state2.output+=nodot,prev.output+=nodot;if(peek()!=="*")state2.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state2.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state2.output=utils.escapeLast(state2.output,"["),decrement("brackets")}while(state2.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state2.output=utils.escapeLast(state2.output,"("),decrement("parens")}while(state2.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state2.output=utils.escapeLast(state2.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state2.backtrack===!0){state2.output="";for(let token of state2.tokens)if(state2.output+=token.output!=null?token.output:token.value,token.suffix)state2.output+=token.suffix}return state2};parse10.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants5.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state2={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state2),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse10});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse10=require_parse(),utils=require_utils2(),constants5=require_constants(),isObject3=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state3=isMatch(str);if(state3)return state3}return!1}}let isState=isObject3(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix13=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state2=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix13}),result={glob,state:state2,regex,posix:posix13,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state2;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix13}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix13?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix13);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse10(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state2,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state2.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state2.output})${append}`;if(state2&&state2.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state2;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse10.fastpaths(input,options);if(!parsed.output)parsed=parse10(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants5;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils2();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count2=1){let requested=Number(count2);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import{execFileSync}from"node:child_process";import*as fsSync9 from"node:fs";import*as path89 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error93){return log("[Guardrails] hashArgs failed",{error:error93 instanceof Error?error93.message:String(error93)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function gitEnvWithoutRepoRedirectors2(){let env={...process.env};return delete env.GIT_DIR,delete env.GIT_WORK_TREE,delete env.GIT_INDEX_FILE,delete env.GIT_COMMON_DIR,env}function parseWorktreeListPorcelain(output){let records=[];for(let line of output.split(`
|
|
1048
|
+
`),{persisted:!0,path:filePath}}function readReviewRouteReceiptSync(input){let filePath=routeReceiptPath(input.projectRoot,input.sessionId,input.taskId),stat11;try{stat11=fs53.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}if(stat11.isSymbolicLink()||!stat11.isFile()||stat11.size>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_UNREADABLE: receipt is not a bounded regular file");let value;try{value=JSON.parse(fs53.readFileSync(filePath,"utf8"))}catch(error93){if(error93 instanceof SyntaxError)throw Error("ROUTE_RECEIPT_INVALID_JSON: receipt is not valid JSON");throw error93}let parsed=typeof value==="object"&&value!==null&&value.kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):value.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);if(!parsed.success)throw Error("ROUTE_RECEIPT_INVALID: receipt failed schema validation");let authenticated=authenticatePersistedRouteReceipt(parsed.data,readRouteReceiptSecretSync(input.projectRoot));if((authenticated.kind==="review_route_receipt"||authenticated.kind==="review_route_pending")&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");if(authenticated.kind==="review_route_router_error"&&authenticated.sessionId!==void 0&&authenticated.taskId!==void 0&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");return authenticated}function parseRouteReceipt(value){if(!value||typeof value!=="object")return null;let kind=value.kind,parsed=kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);return parsed.success?parsed.data:null}function fail(reason){return{canAdvance:!1,mode:"enforced",reason}}function enforceReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route=parseRouteReceipt(input.routeReceipt);if(!route)return fail("ROUTE_RECEIPT_MISSING");if(route.kind==="review_route_router_error"){if(input.sessionId&&(!route.sessionId||!route.taskId||route.sessionId!==input.sessionId||route.taskId!==input.taskId))return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");return{canAdvance:!0,mode:"fail_open",routerFailure:route.code}}if(route.kind==="review_route_pending")return fail("ROUTE_RECEIPT_PENDING");if(input.sessionId&&route.sessionId!==input.sessionId||input.taskId&&route.taskId!==input.taskId)return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");if(route.required.reviewers!==route.identities.reviewers.length||route.required.testEngineers!==route.identities.testEngineers.length)return fail("ROUTE_RECEIPT_COUNT_MISMATCH");let expected=new Map;for(let identity of route.identities.reviewers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"reviewer")}for(let identity of route.identities.testEngineers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"test_engineer")}if(input.requireEvidenceBindings&&input.requireCompleteEvidence===!1&&expected.size>0&&!input.expectedDispatch)return fail("ROUTE_RECEIPT_DISPATCH_REQUIRED");let seen=new Set,seenSlots=new Set;for(let evidence of input.receipts){if(input.requireEvidenceBindings&&(!evidence.sessionId||!evidence.taskId||!evidence.slotId||!evidence.callId||!evidence.childSessionId||typeof evidence.generation!=="number"))return fail("ROUTE_RECEIPT_BINDING_MISSING");let identity=evidence.identity.trim();if(!identity||identity.length>256)return fail("ROUTE_RECEIPT_INVALID_IDENTITY");let expectedRole=expected.get(identity);if(!expectedRole)return fail("ROUTE_RECEIPT_IDENTITY_UNLISTED");if(expectedRole!==evidence.role)return fail("ROUTE_RECEIPT_ROLE_MISMATCH");if(seen.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");if(evidence.sessionId&&evidence.sessionId!==route.sessionId)return fail("ROUTE_RECEIPT_SESSION_MISMATCH");if(evidence.taskId&&evidence.taskId!==route.taskId)return fail("ROUTE_RECEIPT_TASK_MISMATCH");if(evidence.slotId){if(seenSlots.has(evidence.slotId))return fail("ROUTE_RECEIPT_DUPLICATE");let slots=evidence.role==="reviewer"?route.slots?.reviewers:route.slots?.testEngineers;if(slots&&!slots.includes(evidence.slotId))return fail("ROUTE_RECEIPT_SLOT_UNLISTED");if(slots){let expectedIndex=evidence.role==="reviewer"?route.identities.reviewers.indexOf(identity):route.identities.testEngineers.indexOf(identity);if(expectedIndex<0||slots[expectedIndex]!==evidence.slotId)return fail("ROUTE_RECEIPT_SLOT_MISMATCH")}seenSlots.add(evidence.slotId)}seen.add(identity)}if(input.expectedDispatch){let expected2=input.expectedDispatch,matching=input.receipts.find((evidence)=>evidence.role===expected2.role&&evidence.identity===expected2.identity);if(!matching||matching.callId!==expected2.callId||matching.childSessionId!==expected2.childSessionId||matching.generation!==expected2.generation)return fail("ROUTE_RECEIPT_DISPATCH_MISMATCH")}if(input.requireCompleteEvidence!==!1&&seen.size!==expected.size)return fail("ROUTE_RECEIPT_INCOMPLETE");return{canAdvance:!0,mode:"enforced"}}function enforcePersistedReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route;try{route=readReviewRouteReceiptSync({projectRoot:input.projectRoot,sessionId:input.sessionId,taskId:input.taskId})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_AUTH_INVALID:"))return fail("ROUTE_RECEIPT_AUTH_INVALID");throw error93}if(!route&&input.legacyUnrouted)return{canAdvance:!0,mode:"legacy_unrouted",reason:"legacy_unrouted: route receipt predates version-1 enforcement"};return enforceReviewRouteReceipt({enforcementEnabled:!0,routeReceipt:route,receipts:input.receipts,sessionId:input.sessionId,taskId:input.taskId,requireEvidenceBindings:input.requireEvidenceBindings,expectedDispatch:input.expectedDispatch,requireCompleteEvidence:input.requireCompleteEvidence})}var REVIEW_ROUTE_RECEIPT_VERSION=1,IdentitySchema,RouteReceiptMacSchema,ReviewRouteReceiptSchema,ReviewRouteRouterErrorReceiptSchema,ReviewRoutePendingReceiptSchema,MAX_ROUTE_RECEIPT_BYTES=65536,ROUTE_RECEIPT_SECRET_FILE="review-route-receipts.key",ROUTE_RECEIPT_MAC_CONTEXT="opencode-swarm/review-route-receipt/v1\x00";var init_routing_enforcement=__esm(()=>{init_zod();init_task_file();init_utils2();init_hive_paths();init_project_boundary();IdentitySchema=exports_external.string().trim().min(1).max(256),RouteReceiptMacSchema=exports_external.string().regex(/^[0-9a-f]{64}$/,"route receipt MAC must be a SHA-256 HMAC"),ReviewRouteReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_receipt"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,complexity:exports_external.string().trim().min(1).max(80),semanticRisk:exports_external.string().trim().min(1).max(120),required:exports_external.object({reviewers:exports_external.number().int().nonnegative().max(16),testEngineers:exports_external.number().int().nonnegative().max(16)}),identities:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}),slots:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRouteRouterErrorReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_router_error"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),code:exports_external.enum(["NO_CHANGED_FILES","ROUTER_UNAVAILABLE","ROUTER_FAILED"]),failOpen:exports_external.literal(!0),sessionId:IdentitySchema.optional(),taskId:IdentitySchema.optional(),detail:exports_external.string().trim().max(512).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRoutePendingReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_pending"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict()});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),wal=await readWal2(walPath,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal(walPath,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal2(walPath,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal2(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function writeWal(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}async function ensureAuditEvent(directory,wal){if(hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))return;try{appendCoreEventSync(directory,{type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_REPAIR_AUDIT_LOCKED");throw error93}if(!hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}function workflowMatchesCommittedRepair(evidence,wal){let snapshot=getTaskWorkflowSnapshot(evidence);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence),existingWal=await readWal2(walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence,existingWal))return await ensureAuditEvent(options.directory,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed"&&options.currentPlanStatus!=="in_progress")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);if(existingWal===null&&options.currentPlanStatus==="in_progress"){let wedgeEscalated=!1;try{wedgeEscalated=getCoderRetryEscalationActions(options.directory,options.taskId,snapshot.retryEpoch).has("user_escalation")&&snapshot.retryCount>=3}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_REPAIR_ESCALATION_INDEX_UNREADABLE: cannot verify the retry-escalation wedge evidence for an in_progress repair (the core-event authority index is unreadable). The unreadable index is not content-restored: a later authority write rebuilds it from subsequent events only, so escalation evidence already folded out of the retained events window stays lost, and producers may refuse while the index is unreadable. "+"Recovery without discarding the events trail: re-dispatching the task re-runs the retry ladder from scratch and re-records the rungs; /swarm reset is the destructive full reset (it clears the plan, the events trail, and run state — session state is reset-session's charter and survives). Admission refuses to guess.");throw error93}if(!wedgeEscalated)throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus} — an in_progress task is repairable only once the coder retry ladder has recorded a durable user_escalation for its current retry epoch with retryCount at the threshold; no such record is visible for this task.`)}let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal(walPath,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal(walPath,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_core_events();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence,wal){let workflow=getTaskWorkflowSnapshot(evidence);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,readOnlyNoMutation:wal.readOnlyNoMutation,externalEvidence:wal.externalEvidence,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath){try{return await _internals83.applyTerminalEvidence(transaction,wal)}catch(error93){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal2(walPath,{...wal,state:"ABORTED"}),null;if(wal.externalEvidence===!0){if(!externalProofCurrent({title:plan.title,swarm:plan.swarm},task,evidence))throw Error(`TASK_TERMINAL_EXTERNAL_EVIDENCE_DIGEST_MISMATCH: ${walPath} records an external-evidence completion for task ${taskId}, but the current plan declaration no longer matches the attested declaration digest. Re-attest with /swarm attest ${taskId} (or re-plan the declaration), then re-run task-terminal recovery.`)}if(wal.readOnlyNoMutation===!0&&!evidenceAlreadyTerminal){let replayed;try{replayed=await peekPlanFromLedger(directory)}catch(error93){throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: could not inspect the authoritative plan ledger: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}if(replayed.truncated||replayed.badSuffix!==null)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");if(!replayed.plan)throw Error("TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: authoritative plan ledger has no replayable plan");let authoritativeTask=replayed.plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!authoritativeTask)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);if(wal.version===2){let identity=await readPlanEpochIdentity(directory,replayed.plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}plan=replayed.plan,task=authoritativeTask;let currentFiles=authoritativeTask.files_touched;if(!(Array.isArray(currentFiles)&¤tFiles.length===0)){if(authoritativeTask.status!==wal.oldPlanStatus&&authoritativeTask.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${authoritativeTask.status}`);if(authoritativeTask.status===wal.newPlanStatus&&authoritativeTask.status!==wal.oldPlanStatus){let oldStatus=TaskStatusSchema.safeParse(wal.oldPlanStatus);if(!oldStatus.success)throw Error(`TASK_TERMINAL_OLD_STATUS_INVALID: ${wal.oldPlanStatus}`);let rolledBackPlan=await updateTaskStatus(directory,taskId,oldStatus.data,{planLockAlreadyHeld:!0,terminalReconciliation:!0}),rolledBackTask=rolledBackPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(rolledBackTask?.status!==oldStatus.data)throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_ROLLBACK_FAILED: expected ${oldStatus.data}, found ${rolledBackTask?.status??"missing task"}`);plan=rolledBackPlan}throw await writeWal2(walPath,{...wal,state:"ABORTED"}),Error(`TASK_TERMINAL_READ_ONLY_SCOPE_CHANGED: task ${taskId} no longer has a known empty declared scope; terminal evidence was not applied`)}}if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence:await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence);await options.validateEvidence?.(evidence);let terminal=options.resolveTerminal?.(evidence)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&existingWal.readOnlyNoMutation===!0===(terminal.readOnlyNoMutation===!0)&&existingWal.externalEvidence===!0===(terminal.externalEvidence===!0)&&evidenceMatchesTerminal(evidence,existingWal))return{plan:options.currentPlan,evidence,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath}); found ${evidence?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,...terminal.readOnlyNoMutation===!0?{readOnlyNoMutation:!0}:{},...terminal.externalEvidence===!0?{externalEvidence:!0}:{},recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal2(walPath,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal2=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals83;var init_task_terminal=__esm(()=>{init_plan_schema();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals83={applyTerminalEvidence}});import*as fs54 from"node:fs";function storePath2(directory){return validateSwarmPath(directory,DEAD_LANE_RECLAIM_PATH)}function isDeadLaneReclaimEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return typeof candidate.lanePath==="string"&&candidate.lanePath.length>0&&typeof candidate.branchName==="string"&&typeof candidate.parentSessionId==="string"&&typeof candidate.taskId==="string"&&typeof candidate.reason==="string"&&typeof candidate.recordedAt==="number"}function readStore2(directory){try{let raw=fs54.readFileSync(storePath2(directory),"utf-8");if(raw.length>MAX_DEAD_LANE_RECLAIM_BYTES)return{schemaVersion:1,entries:[]};let parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{schemaVersion:1,entries:[]};return{schemaVersion:1,entries:parsed.entries.filter(isDeadLaneReclaimEntry)}}catch{return{schemaVersion:1,entries:[]}}}function writeStore2(directory,store){let entries=store.entries.slice(-MAX_DEAD_LANE_RECLAIMS);for(;;){let serialized2=JSON.stringify({schemaVersion:1,entries},null,2);if(serialized2.length<=MAX_DEAD_LANE_RECLAIM_BYTES||entries.length===0){if(entries.length<store.entries.length)log(`[dead-lane-reclaim] store bound dropped ${store.entries.length-entries.length} oldest entries (caps: ${MAX_DEAD_LANE_RECLAIMS} entries / ${MAX_DEAD_LANE_RECLAIM_BYTES} bytes)`);_internals84.atomicWriteSwarmFileSync(storePath2(directory),serialized2);return}entries=entries.slice(1)}}function recordDeadLaneReclaim(directory,entry){try{let filtered=readStore2(directory).entries.filter((existing)=>existing.lanePath!==entry.lanePath);filtered.push({...entry,recordedAt:Date.now()}),writeStore2(directory,{schemaVersion:1,entries:filtered})}catch(error93){log(`[dead-lane-reclaim] could not record stranded lane ${entry.lanePath}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function isLaneOwnedByActiveSession(lanePath,activeSessionIds,parentSessionId){if(activeSessionIds.has(parentSessionId??""))return!0;if(parentSessionId&&!lanePathIncludesSessionSegment(lanePath,parentSessionId))return!0;return!1}function lanePathIncludesSessionSegment(lanePath,sessionId){return lanePath.replace(/\\/g,"/").split("/").includes(sessionId)}async function isLaneDirty(lanePath){let proc;try{let options={cwd:lanePath,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:LANE_DIRTY_CHECK_TIMEOUT_MS,killProcessTree:!0};proc=_internals84.bunSpawn([_internals84.resolveGitExecutable(),"-C",lanePath,"status","--porcelain"],options);let stdout="";if(proc.stdout){let reader=proc.stdout.getReader();for(;;){let{done,value}=await reader.read();if(done||!value)break;if(stdout+=Buffer.from(value).toString("utf-8"),stdout.length>LANE_DIRTY_STDOUT_CAP_BYTES)break}}if(await proc.exited!==0)return!0;return stdout.trim().length>0}catch{return!0}finally{try{proc?.kill?.()}catch{}}}async function reclaimDeadLanes(directory,context={}){let result={reclaimed:[],retained:[]},store;try{store=readStore2(directory)}catch{return result}if(store.entries.length===0)return result;let activeSessionIds=new Set(context.activeSessionIds??[]),protectedPaths=new Set(context.protectedWorktreePaths??[]),retained=[];for(let entry of store.entries){let protectedLane=protectedPaths.has(entry.lanePath)||protectedPaths.has(_internals84.canonicalRootKeyFresh(entry.lanePath));if(_internals84.isLaneOwnedByActiveSession(entry.lanePath,activeSessionIds,entry.parentSessionId)||protectedLane){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"owned-by-active-session-or-protected"});continue}if(!await _internals84.pathExists(entry.lanePath))continue;if(await _internals84.isLaneDirty(entry.lanePath)){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"dirty-lane-preserved"});continue}_internals84.closeProjectDb(entry.lanePath);let removalError;try{let removal=await _internals84.removeWorktree(entry.lanePath,directory);if("error"in removal)removalError=removal.error}catch(error93){removalError=error93 instanceof Error?error93.message:String(error93)}if(removalError!==void 0){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:removalError});continue}result.reclaimed.push(entry.lanePath)}try{if(retained.length===0)fs54.rmSync(storePath2(directory),{force:!0});else writeStore2(directory,{schemaVersion:1,entries:retained})}catch(error93){log(`[dead-lane-reclaim] could not persist reclaim state: ${error93 instanceof Error?error93.message:String(error93)}`)}return result}async function pathExists2(target){try{return await fs54.promises.stat(target),!0}catch{return!1}}var DEAD_LANE_RECLAIM_PATH="dead-lane-reclaims.json",MAX_DEAD_LANE_RECLAIMS=512,MAX_DEAD_LANE_RECLAIM_BYTES=262144,LANE_DIRTY_CHECK_TIMEOUT_MS=5000,LANE_DIRTY_STDOUT_CAP_BYTES=4096,_internals84;var init_dead_lane_reclaim=__esm(()=>{init_project_db();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();init_utils2();_internals84={removeWorktree,closeProjectDb,isLaneOwnedByActiveSession,isLaneDirty,pathExists:pathExists2,bunSpawn,resolveGitExecutable,atomicWriteSwarmFileSync,canonicalRootKeyFresh}});function normalizeToForwardSlash(filePath){return filePath.replace(/\\/g,"/")}function matchesTier3(files){for(let file3 of files)if(isTier3Path(file3))return!0;return!1}function isTier3Path(filePath){let segments=normalizeToForwardSlash(filePath).split("/"),fileName=segments[segments.length-1]||"",fileBaseName=fileName.replace(/\.[^.]*$/,"").toLowerCase();if(TIER_3_EXACT_BASENAMES.has(fileBaseName))return!0;if(TIER_3_KEYWORD_PREFIX_RE.test(fileBaseName))return!0;for(let pattern of TIER_3_BASENAME_PATTERNS)if(pattern.test(fileName))return!0;for(let i=0;i<segments.length-1;i++)if(TIER_3_DIRECTORY_SEGMENTS.has(segments[i].toLowerCase()))return!0;return!1}var TIER_3_BASENAME_PATTERNS,TIER_3_EXACT_BASENAMES,TIER_3_KEYWORD_PREFIX_RE,TIER_3_DIRECTORY_SEGMENTS;var init_tier3_classifier=__esm(()=>{TIER_3_BASENAME_PATTERNS=[/^architect.*\.ts$/i,/^delegation.*\.ts$/i,/^guardrails?.*\.ts$/i,/^adversarial.*\.ts$/i,/^sanitiz.*\.ts$/i,/^security.*\.ts$/i],TIER_3_EXACT_BASENAMES=new Set(["auth","authenticate","authentication","authorization","permission","permissions","crypto","secret","secrets","secretscan"]),TIER_3_KEYWORD_PREFIX_RE=/^(auth|permission|crypto|secret|security)[-_.]/i,TIER_3_DIRECTORY_SEGMENTS=new Set(["auth","security","crypto","permission","secret"])});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win3210){return win3210===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils2=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state2={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state2.prefix="./";return output};exports.wrapOutput=(input,state2={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state2.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path89,{windows}={})=>{let segs=path89.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils2(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.tokens===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){let parens=0;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_PARENTHESES){parens++;continue}if(code===CHAR_RIGHT_PARENTHESES&&--parens===0){finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){let parens=1;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_PARENTHESES){parens++;continue}if(code===CHAR_RIGHT_PARENTHESES&&--parens===0){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state2={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state2.maxDepth=0,!isPathSeparator(code))tokens.push(token);state2.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n2=prevIndex!==void 0?prevIndex+1:start,i=slashes[idx],value2=input.slice(n2,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value2;depth(tokens[idx]),state2.maxDepth+=tokens[idx].depth}if(i>=start)parts.push(value2),prevIndex=i}let n=prevIndex!==void 0?prevIndex+1:start,value=input.slice(n);if(parts.push(value),opts.tokens&&prevIndex&&prevIndex+1<input.length)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state2.maxDepth+=tokens[tokens.length-1].depth;state2.slashes=slashes,state2.parts=parts}return state2};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants5=require_constants(),utils=require_utils2(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants5,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},buildCharClassStar=(chars)=>{return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},getStarExtglobSequenceChars=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return chars},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants5.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}let safeChars=[],sawStarSequence=!1,combinable=!0;for(let branch of branches){let chars=getStarExtglobSequenceChars(branch);if(chars){sawStarSequence=!0,safeChars.push(...chars);continue}let literal4=normalizeSimpleBranch(branch);if(literal4&&literal4.length===1){safeChars.push(literal4);continue}if(combinable=!1,repeatedExtglobRecursion(branch)>max)return{risky:!0}}if(sawStarSequence)return combinable?{risky:!0,safeOutput:buildCharClassStar([...new Set(safeChars)])}:{risky:!0};return{risky:!1}},parse10=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants5.globChars(opts.windows),EXTGLOB_CHARS=constants5.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state2={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state2),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state2.index===len-1,peek=state2.peek=(n=1)=>input[state2.index+n],advance=state2.advance=()=>input[++state2.index]||"",remaining=()=>input.slice(state2.index+1),consume=(value2="",num=0)=>{state2.consumed+=value2,state2.index+=num},append=(token)=>{state2.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count2=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state2.start++,count2++;if(count2%2===0)return!1;return state2.negated=!0,state2.start++,!0},increment=(type)=>{state2[type]++,stack.push(type)},decrement=(type)=>{state2[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state2.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state2.output=state2.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state2.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state2.parens,token.output=state2.output,token.startIndex=state2.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state2.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal4=input.slice(token.startIndex,state2.index+1),body=input.slice(token.startIndex+2,state2.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open6=tokens[token.tokensIndex];open6.type="text",open6.value=literal4,open6.output=safeOutput||utils.escapeRegex(literal4);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state2.output=token.output+open6.output,state2.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse10(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state2.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc3,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc3)return esc3+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc3)return esc3+first+(rest?star:"");return star}return esc3?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state2.output=input,state2;return state2.output=utils.wrapOutput(output,state2,options),state2}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state2.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state2.brackets===0){push({type:"text",value});continue}}if(state2.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix13=POSIX_REGEX_SOURCE[rest2];if(posix13){if(prev.value=pre+posix13,state2.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state2.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state2.quotes=state2.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state2.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state2.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state2.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state2.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state2.output=state2.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state2.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state2.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open6={type:"brace",value,output:"(",outputIndex:state2.output.length,tokensIndex:state2.tokens.length};braces.push(open6),push(open6);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state2.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state2.output.slice(0,brace.outputIndex),toks=state2.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state2.output=out;for(let t of toks)state2.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state2.index===state2.start+1){state2.start=state2.index+1,state2.consumed="",state2.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state2.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state2.braces+state2.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state2.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state2.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state2.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state2.backtrack=!0,state2.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state2.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state2.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}let isEnd=eos()||state2.parens>0&&rest===")".repeat(state2.parens)&&!extglobs.some((extglob)=>extglob.type==="negate");if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state2.output=prev.output,state2.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&isEnd){state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state2.globstar=!0,state2.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state2.output+=prior.output+prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state2.output=prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state2.output=state2.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state2.output+=prev.output,state2.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state2.index===state2.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state2.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state2.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state2.output+=nodot,prev.output+=nodot;if(peek()!=="*")state2.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state2.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state2.output=utils.escapeLast(state2.output,"["),decrement("brackets")}while(state2.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state2.output=utils.escapeLast(state2.output,"("),decrement("parens")}while(state2.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state2.output=utils.escapeLast(state2.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state2.backtrack===!0){state2.output="";for(let token of state2.tokens)if(state2.output+=token.output!=null?token.output:token.value,token.suffix)state2.output+=token.suffix}return state2};parse10.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants5.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state2={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state2),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse10});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse10=require_parse(),utils=require_utils2(),constants5=require_constants(),isObject3=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state3=isMatch(str);if(state3)return state3}return!1}}let isState=isObject3(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix13=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state2=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix13}),result={glob,state:state2,regex,posix:posix13,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state2;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix13}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix13?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix13);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options,posix13=options&&options.windows)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input,{windows:posix13}))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse10(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state2,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state2.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state2.output})${append}`;if(state2&&state2.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state2;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse10.fastpaths(input,options);if(!parsed.output)parsed=parse10(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants5;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils2();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count2=1){let requested=Number(count2);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import{execFileSync}from"node:child_process";import*as fsSync9 from"node:fs";import*as path89 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error93){return log("[Guardrails] hashArgs failed",{error:error93 instanceof Error?error93.message:String(error93)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function gitEnvWithoutRepoRedirectors2(){let env={...process.env};return delete env.GIT_DIR,delete env.GIT_WORK_TREE,delete env.GIT_INDEX_FILE,delete env.GIT_COMMON_DIR,env}function parseWorktreeListPorcelain(output){let records=[];for(let line of output.split(`
|
|
1049
1049
|
`)){if(line.startsWith("worktree ")){let wtPath=line.slice(9).trim();if(wtPath)records.push({path:wtPath,attributes:new Set});continue}let record3=records[records.length-1];if(!record3)continue;let separator=line.indexOf(" "),attribute=separator===-1?line:line.slice(0,separator);if(attribute)record3.attributes.add(attribute)}return records}function canonicalizeWindowsPathNative(p){if(process.platform!=="win32")return p;try{let native=fsSync9.realpathSync.native(p);return native.startsWith(String.fromCharCode(92,92,63,92))?native.slice(4):native}catch{return}}function canonicalizeWindowsPathTailTolerant(p){if(process.platform!=="win32")return p;let tail=[],probe2=p;for(;;){let native=canonicalizeWindowsPathNative(probe2);if(native!==void 0)return tail.length===0?native:path89.join(native,...tail.reverse());let parent=path89.dirname(probe2);if(parent===probe2)return p;tail.push(path89.basename(probe2)),probe2=parent}}function isValidWorktreeRecord(repoRootRecord,record3){if(record3===repoRootRecord)try{return fsSync9.statSync(path89.join(record3.path,".git")).isDirectory()}catch{return!1}if(record3.attributes.has("bare"))return!1;let dotGitPath=path89.join(record3.path,".git"),dotGitStat;try{dotGitStat=fsSync9.lstatSync(dotGitPath)}catch{return!1}if(!dotGitStat.isFile())return!1;let gitDirLine;try{gitDirLine=fsSync9.readFileSync(dotGitPath,"utf8").trim()}catch{return!1}if(!gitDirLine.startsWith("gitdir:"))return!1;let gitDirRef=gitDirLine.slice(7).trim();if(!gitDirRef)return!1;let gitDirPath=path89.isAbsolute(gitDirRef)?gitDirRef:path89.resolve(record3.path,gitDirRef),registrationGitdirFile;try{registrationGitdirFile=fsSync9.realpathSync(path89.join(gitDirPath,"gitdir"))}catch{return!1}if(repoRootRecord){let worktreesRoot;try{worktreesRoot=path89.join(fsSync9.realpathSync(path89.join(repoRootRecord.path,".git")),"worktrees")}catch{return!1}if(!isPathIdentityWithin(registrationGitdirFile,worktreesRoot))return!1}let backReference;try{backReference=fsSync9.readFileSync(registrationGitdirFile,"utf8").trim()}catch{return!1}try{return pathIdentitiesEqual(fsSync9.realpathSync(dotGitPath),fsSync9.realpathSync(backReference))}catch{return!1}}function getLinkedGitWorktrees(dir){let cached3=gitWorktreeCache.get(dir);if(cached3!==void 0)return cached3;let worktrees=[];try{let output=execFileSync(resolveGitExecutable(),["worktree","list","--porcelain"],{cwd:dir,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1500,maxBuffer:4194304,windowsHide:!0,env:gitEnvWithoutRepoRedirectors2()}),records=parseWorktreeListPorcelain(output),repoRootRecord=records[0];for(let record3 of records){if(!isValidWorktreeRecord(repoRootRecord,record3))continue;let native=canonicalizeWindowsPathNative(record3.path);if(native===void 0)continue;worktrees.push(native)}}catch{}return gitWorktreeCache.set(dir,worktrees),worktrees}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached3=pathNormalizationCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let absolutePath=path89.isAbsolute(filePath)?filePath:path89.resolve(cwd,filePath),normalized=fsSync9.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path89.isAbsolute(filePath)?filePath:path89.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached3=globMatcherCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path89.resolve(cwd),normalizedTarget=path89.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path89.relative(normalizedCwd,current);if(rel===""||rel===".."||rel.startsWith(`..${path89.sep}`)||path89.isAbsolute(rel))break;ancestors.push(current);let parent=path89.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat11=null;try{stat11=fsSync9.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat11.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink/junction — writing through a symlink or junction could redirect the write outside the working directory`}return null}function matchesAuthorityDenyPrefix(candidate,prefix,cwd,flavor=getPathFlavor()){let pathImpl=flavor==="win32"?path89.win32:path89.posix,normalizeInput=(value)=>flavor==="win32"?value.replace(/\//g,"\\"):value,normalizedPrefixInput=normalizeInput(prefix),requiresComponentBoundary=normalizedPrefixInput.endsWith(pathImpl.sep),root=pathImpl.resolve(normalizeInput(cwd)),target=pathImpl.resolve(root,normalizeInput(candidate)),denied=pathImpl.resolve(root,normalizedPrefixInput);if(!isPathIdentityWithin(target,root,flavor)||!isPathIdentityWithin(denied,root,flavor))return!1;let identity=(value)=>flavor==="win32"?value.toLowerCase():value,targetIdentity=identity(target),deniedIdentity=identity(denied);return requiresComponentBoundary?targetIdentity===deniedIdentity||targetIdentity.startsWith(`${deniedIdentity}${pathImpl.sep}`):targetIdentity.startsWith(deniedIdentity)}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path89){let flavor=pathLib===path89.win32||pathLib.parse("C:\\probe").root!==""?"win32":"posix";return isOnDifferentPathRoot(targetAbsolute,cwdAbsolute,flavor)}function denyAuthority(agent,normalizedPath,input){let safeAgent=sanitizeDiagnosticText(agent,96),safePath=sanitizeDiagnosticText(normalizedPath,320),safeDetail=sanitizeDiagnosticText(input.detail,640);return{allowed:!1,code:input.code,layer:input.layer,rule:sanitizeDiagnosticText(input.rule,128),path:safePath,agent:safeAgent,reason:sanitizeDiagnosticText(`${input.code}: Path blocked: ${safeDetail} [agent=${safeAgent}; path=${safePath}]`,1024),recovery:input.recovery,zone:input.zone}}function formatAllowedHints(rules){let fmt=(items)=>{if(!items||items.length===0)return"(none)";if(items.length<=MAX_ALLOWED_HINT_ENTRIES)return items.join(", ");let omitted=items.length-MAX_ALLOWED_HINT_ENTRIES;return`${items.slice(0,MAX_ALLOWED_HINT_ENTRIES).join(", ")}, … (+${omitted} more)`},parts=[];if(rules.allowedExact&&rules.allowedExact.length>0)parts.push(`Allowed exact paths: ${fmt(rules.allowedExact)}`);if(parts.push(`Allowed prefixes: ${fmt(rules.allowedPrefix)}`),parts.push(`Allowed globs: ${fmt(rules.allowedGlobs)}`),rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0)parts.push(`Allowed case-sensitive globs: ${fmt(rules.allowedCaseSensitiveGlobs)}`);return parts.push("Block rules (blocked zones/prefixes/globs/exact) and universal deny paths still apply."),parts.join(" ")}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options={}){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),unsafePathReason=unsafePathTextReason(filePath);if(unsafePathReason)return denyAuthority(agentName,filePath,{code:"AUTHORITY_INVALID_PATH",layer:"path-validation",rule:"safe-path-text",detail:unsafePathReason});let normalizedPath,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path89.resolve(dir,normalizedWithSymlinks),normalizedPath=path89.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path89.resolve(dir,filePath),normalizedPath=path89.relative(dir,resolvedTarget).replace(/\\/g,"/")}let effectiveDir=dir,nativeTarget2=canonicalizeWindowsPathTailTolerant(resolvedTarget),matchWorktreeRoot=()=>{let worktrees=getLinkedGitWorktrees(dir),best;for(let wt of worktrees){let relToWt=path89.relative(wt,nativeTarget2).replace(/\\/g,"/");if(relToWt!==".."&&!relToWt.startsWith("../")&&!isOnDifferentFilesystemRoot(nativeTarget2,wt)){if(!best||wt.length>best.wt.length)best={wt,rel:relToWt}}}if(best)effectiveDir=best.wt,normalizedPath=best.rel;return best?.wt},findPlantedLinkBelow=(root)=>{let ancestors=[],current=nativeTarget2;while(!0){let rel=path89.relative(root,current);if(rel===""||rel===".."||rel.startsWith(`..${path89.sep}`)||path89.isAbsolute(rel))break;ancestors.push(current);let parent=path89.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors)try{if(fsSync9.lstatSync(ancestor).isSymbolicLink())return ancestor}catch(err){if(err.code==="ENOENT")continue;return ancestor}return null};if(isOnDifferentFilesystemRoot(resolvedTarget,dir)){let matchedWorktree=matchWorktreeRoot();if(!matchedWorktree)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"same-filesystem-root",detail:"target is on a different drive or filesystem root"});let plantedLink=findPlantedLinkBelow(matchedWorktree);if(plantedLink)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:`re-rooted target crosses symlink/junction "${plantedLink}" inside the matched worktree`})}else if(normalizedPath===".."||normalizedPath.startsWith("../")){let matchedWorktree=matchWorktreeRoot();if(!matchedWorktree)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:"target resolves outside the working directory"});let plantedLink=findPlantedLinkBelow(matchedWorktree);if(plantedLink)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:`re-rooted target crosses symlink/junction "${plantedLink}" inside the matched worktree`})}let classifiedRules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent],unclassifiedWhileDisabled=!classifiedRules&&options.authorityEnabled===!1&&normalizedAgent!=="unknown",rules=classifiedRules??(unclassifiedWhileDisabled?{}:void 0);if(!rules)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNKNOWN_AGENT",layer:"role-capability",rule:"known-agent-role",detail:"Unknown agent: no authority classification exists"});let flavor=getPathFlavor(),matchesPathPrefix=(candidate,prefix)=>isPathIdentityWithin(path89.resolve(effectiveDir,candidate),path89.resolve(effectiveDir,prefix),flavor),matchesGlob=(glob)=>getGlobMatcher(glob)(normalizedPath);for(let prefix of options.universalDenyPrefixes??[])if(matchesAuthorityDenyPrefix(normalizedPath,prefix,effectiveDir,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNIVERSAL_DENY",layer:"universal-deny",rule:`universal:${prefix}`,detail:`target is under universal deny prefix ${prefix}`});let isCoderAgent=normalizedAgent==="coder"||strippedAgent==="coder";if(isCoderAgent&&isPolicyProtectedPath(normalizedPath,{includeDefaults:!1,additional:[".git",".swarm"]}))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"coder-control-state-protection",detail:"coder writes to repository control state (.git/.swarm) are always protected"});if(unclassifiedWhileDisabled&&isPolicyProtectedPath(normalizedPath,{includeDefaults:!1,additional:[".git",".swarm"]}))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"unclassified-agent-control-state-protection",detail:"unclassified agent writes to repository control state (.git/.swarm) are always protected"});if(Object.hasOwn(AUTHORITY_ROLE_CAPABILITIES,strippedAgent)){let matchedVerifier=[...BUILT_IN_VERIFIER_CONFIG_GLOBS,...options.verifierConfigPaths??[]].find(matchesGlob);if(matchedVerifier)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_VERIFIER_CONFIG",layer:"protected-path",rule:`verifier-config:${matchedVerifier}`,detail:`Path blocked (glob ${matchedVerifier}): swarm roles cannot write verifier-owned configuration in the config zone`})}let canonicalCapability=AUTHORITY_ROLE_CAPABILITIES[strippedAgent];if(canonicalCapability==="read-only"||canonicalCapability==="dedicated-tool-only")return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:`role-capability:${canonicalCapability}`,detail:canonicalCapability==="dedicated-tool-only"?"role may mutate state only through dedicated tools":"agent role is read-only"});if(rules.readOnly)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:"role-policy:read-only",detail:"agent role is read-only"});if(isCoderAgent&&options.declaredScope!=null&&options.declaredScope.length>0&&isPathWithinDeclaredScope(normalizedPath,options.declaredScope,effectiveDir))return{allowed:!0,layer:"declared-scope",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(options.authorityEnabled===!1)return{allowed:!0,layer:"role-policy",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(pathIdentitiesEqual(normalizedPath,blocked,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedExact:${blocked}`,detail:`path is blocked by exact role policy ${blocked}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(matchesGlob(glob))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedGlob:${glob}`,detail:`Path blocked (glob ${glob}) by role policy`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>pathIdentitiesEqual(normalizedPath,allowed,flavor)))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath);if(rules.blockedZones.includes(zone))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedZone:${zone}`,detail:`path is in ${zone} zone`,recovery:isCoderAgent?"declare_scope":void 0,zone})}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some(matchesGlob))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath)}))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(matchesPathPrefix(normalizedPath,prefix))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedPrefix:${prefix}`,detail:`path is under blocked role prefix ${prefix}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>matchesPathPrefix(normalizedPath,prefix)))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix",detail:`path is not in allowed list for this role. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0})}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix:empty",detail:`path is not in allowed list because the role allowlist is empty. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0});return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options={}){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),{...options,authorityEnabled:authorityConfig?.enabled??options.authorityEnabled,universalDenyPrefixes:authorityConfig?.universal_deny_prefixes??options.universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths??options.verifierConfigPaths})}var import_picomatch,pathNormalizationCache,globMatcherCache,GIT_WORKTREE_CACHE_MAX_AGE_MS=60000,gitWorktreeCache,AUTHORITY_ROLE_CAPABILITIES,NON_WRITING_SWARM_RULES,DEFAULT_AGENT_AUTHORITY_RULES,BUILT_IN_VERIFIER_CONFIG_GLOBS,MAX_ALLOWED_HINT_ENTRIES=20;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_core_events();init_path_identity();init_protected_path_policy();init_utils();init_arg_hash();init_git_executable();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200}),gitWorktreeCache=new QuickLRU({maxSize:50,maxAge:GIT_WORKTREE_CACHE_MAX_AGE_MS});AUTHORITY_ROLE_CAPABILITIES={architect:"direct-write",coder:"direct-write",reviewer:"direct-write",critic:"direct-write",critic_oversight:"dedicated-tool-only",critic_finding_validator:"dedicated-tool-only",explorer:"read-only",sme:"read-only",researcher:"read-only",test_engineer:"direct-write",docs:"direct-write",docs_design:"direct-write",designer:"direct-write",critic_sounding_board:"read-only",critic_drift_verifier:"read-only",critic_hallucination_verifier:"read-only",critic_architecture_supervisor:"read-only",curator_init:"dedicated-tool-only",curator_phase:"dedicated-tool-only",curator_postmortem:"dedicated-tool-only",curator_consolidation:"dedicated-tool-only",council_generalist:"read-only",council_skeptic:"read-only",council_domain_expert:"read-only",skill_improver:"dedicated-tool-only",spec_writer:"dedicated-tool-only"},NON_WRITING_SWARM_RULES=Object.fromEntries(Object.entries(AUTHORITY_ROLE_CAPABILITIES).filter(([,capability])=>capability==="read-only"||capability==="dedicated-tool-only").map(([agent])=>[agent,{readOnly:!0}])),DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},...NON_WRITING_SWARM_RULES,architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}};BUILT_IN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.json","**/biome.jsonc","**/tsconfig*.json","**/.secretscanignore","**/.golangci*"]});import{createHash as createHash40}from"node:crypto";import*as fs55 from"node:fs";import*as path90 from"node:path";function fingerprint(filePath,budget){try{let stat11=fs55.lstatSync(filePath);if(stat11.isSymbolicLink())return{kind:"unsafe"};if(!stat11.isFile())return{kind:"unsafe"};if(stat11.size>MAX_HASH_BYTES||stat11.size>budget.remaining)return{kind:"unsafe"};budget.remaining-=stat11.size;let result={kind:"file",size:stat11.size,mtimeMs:stat11.mtimeMs};return result.hash=createHash40("sha256").update(fs55.readFileSync(filePath)).digest("hex"),result}catch(error93){return error93.code==="ENOENT"?{kind:"missing"}:{kind:"unsafe"}}}function changed(before,after){if(before.kind==="unsafe"||after.kind==="unsafe")return!1;if(before.kind!==after.kind)return!0;if(before.kind==="missing")return!1;if(before.hash!==void 0||after.hash!==void 0)return before.hash!==after.hash;return before.size!==after.size||before.mtimeMs!==after.mtimeMs}function effectFor(tool3,args2,targetCount){if(targetCount!==1||!args2||typeof args2!=="object")return{};let record3=args2;if(tool3==="write"||tool3==="create_file"){for(let key of["content","file_text","text"])if(typeof record3[key]==="string")return{exactContent:record3[key]}}if(tool3==="edit"||tool3==="replace"){for(let key of["newString","new_string","replacement"])if(typeof record3[key]==="string"&&record3[key]!=="")return{containsText:record3[key]}}return{}}function matchesExpected(filePath,expected,budget){if(expected.exactContent===void 0&&expected.containsText===void 0)return!0;try{let stat11=fs55.statSync(filePath);if(!stat11.isFile()||stat11.size>MAX_HASH_BYTES||stat11.size>budget.remaining)return!1;budget.remaining-=stat11.size;let content=fs55.readFileSync(filePath,"utf8");if(expected.exactContent!==void 0)return content===expected.exactContent;return content.includes(expected.containsText??"")}catch{return!1}}function numericExitCodes(metadata){if(!metadata||typeof metadata!=="object")return[];let record3=metadata;return["exitCode","exit_code","exit"].map((key)=>record3[key]).filter((value)=>typeof value==="number")}function directSuccess(output){let text=typeof output.output==="string"?output.output.trim():"",metadata=output.metadata&&typeof output.metadata==="object"?output.metadata:null;if(numericExitCodes(output.metadata).some((code)=>code!==0))return!1;if(metadata?.success===!0)return!0;if(metadata&&typeof metadata.status==="string"&&["success","completed","ok","applied"].includes(metadata.status.toLowerCase()))return!0;try{let parsed=JSON.parse(text);if(parsed.success===!0&&parsed.dryRun!==!0)return!0}catch{}return/^(?:Wrote file successfully\.|Edit applied successfully\.|Done!|Patch applied successfully\.|File (?:created|updated) successfully\.)/i.test(text)}function successful(tool3,output){if(tool3==="bash"||tool3==="shell"){let exitCodes=numericExitCodes(output.metadata);return exitCodes.length>0&&exitCodes.every((code)=>code===0)}return directSuccess(output)}function createScopeLeaseRenewalTracker(refresh=refreshScopeBindingLease,now=Date.now){let candidates=new Map,candidateKey=(sessionID,callID)=>`${sessionID}\x00${callID}`,sweep=()=>{let cutoff=now()-CANDIDATE_TTL_MS;for(let[key,candidate]of candidates)if(candidate.createdAt<cutoff)candidates.delete(key);while(candidates.size>=MAX_CANDIDATES2){let oldest=candidates.keys().next().value;if(oldest===void 0)break;candidates.delete(oldest)}};return{remember(input){sweep();let binding=input.binding;if(binding.activation!=="active"||binding.lifecycleState!=="live"||binding.expiresAt<=now()||binding.ownerSessionId!==input.sessionID||input.targets.length===0||input.targets.length>MAX_TARGETS)return;let uniqueTargets=[...new Set(input.targets.map((target)=>path90.resolve(target)))];if(uniqueTargets.length===0||uniqueTargets.length>MAX_TARGETS)return;let expected=effectFor(input.tool,input.args,uniqueTargets.length),hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},targets=uniqueTargets.map((target)=>({path:target,before:fingerprint(target,hashBudget),expected}));if(targets.some((target)=>target.before.kind==="unsafe"))return;candidates.set(candidateKey(input.sessionID,input.callID),{createdAt:now(),callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:input.directory,bindingId:binding.bindingId,generationId:binding.generationId,expectedRevision:binding.revision,taskId:binding.taskId,targets})},async consume(input){let key=candidateKey(input.sessionID,input.callID),candidate=candidates.get(key);if(candidates.delete(key),!candidate||candidate.sessionID!==input.sessionID||candidate.tool!==input.tool||now()-candidate.createdAt>CANDIDATE_TTL_MS||!input.output||!successful(candidate.tool,input.output))return null;let hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},contentBudget={remaining:MAX_AGGREGATE_HASH_BYTES};for(let target of candidate.targets){let after=fingerprint(target.path,hashBudget);if(!changed(target.before,after)||!matchesExpected(target.path,target.expected,contentBudget))return null}return refresh({directory:candidate.directory,bindingId:candidate.bindingId,generationId:candidate.generationId,expectedRevision:candidate.expectedRevision,activeSessionId:candidate.sessionID,taskId:candidate.taskId})}}}var MAX_CANDIDATES2=256,MAX_TARGETS=256,MAX_HASH_BYTES=4194304,MAX_AGGREGATE_HASH_BYTES=8388608,CANDIDATE_TTL_MS=600000;var init_scope_lease_renewal=__esm(()=>{init_scope_persistence()});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;let rejections=input.rejectionCount??0,resolutionPath,taskId=input.taskId??"unknown",conflictDedupeKey=`conflict:${taskId}:${rejections}`;if(rejections>=3)resolutionPath="soundingboard",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT ESCALATION (rejections=${rejections}): ${input.sourceAgent} vs ${input.targetAgent} on task ${taskId}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`,{dedupeKey:conflictDedupeKey});else resolutionPath="self_resolve",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT DETECTED (rejections=${rejections}): ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${taskId}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`,{dedupeKey:conflictDedupeKey});let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state();init_telemetry()});import{createHash as createHash41}from"node:crypto";import*as fs56 from"node:fs";import*as path91 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file3){if(file3.includes("\x00")||hasControlCharacter(file3))return null;let root=path91.resolve(directory),absolute=path91.resolve(root,file3),relative23=path91.relative(root,absolute).replaceAll("\\","/");if(!relative23||relative23===".."||relative23.startsWith("../")||path91.isAbsolute(relative23))return null;return relative23}function isWithinRoot2(root,candidate){let relative23=path91.relative(root,candidate);return relative23===""||relative23!==".."&&!relative23.startsWith(`..${path91.sep}`)&&!path91.isAbsolute(relative23)}function deletedPathIsContained(canonicalRoot,absolute){let current=path91.dirname(absolute);for(;;){try{let canonical=_internals85.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}let parent=path91.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file3,options={}){if(typeof directory!=="string"||typeof file3!=="string")return{kind:"capture_failed",file:typeof file3==="string"?file3:"",code:"invalid_request",retryable:!1};if(file3.includes("\x00")||hasControlCharacter(file3))return{kind:"capture_failed",file:file3,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file3);if(!normalized)return{kind:"capture_failed",file:file3,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path91.resolve(directory,normalized);try{canonicalRoot=_internals85.realpathSync(path91.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals85.realpathSync(path91.dirname(absolute))}catch(error93){if(error93.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals85.realpathSync(path91.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 _internals85.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error93.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals85.lstat(absolute)}catch(error93){if(error93.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error93.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals85.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path91.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=fs56.constants.O_RDONLY|(process.platform==="win32"?0:fs56.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals85.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals85.open(absolute,openFlags)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals85.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash4=createHash41("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals85.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals85.read(fd,chunk,0,chunk.byteLength,null)}catch(error93){let code=error93.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash4.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals85.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=_internals85.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=_internals85.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path91.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash4.digest("hex")}}finally{if(fd!==void 0)try{_internals85.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,_internals85;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals85={open:fs56.openSync,fstat:(fd,options)=>fs56.fstatSync(fd,options),read:fs56.readSync,close:fs56.closeSync,lstat:fs56.lstatSync,stat:(path92,options)=>fs56.statSync(path92,options),realpathSync:fs56.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record3=output,nestedRecords=[record3.metadata,record3.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record3,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state2)=>NON_SUCCESS_STATES.has(state2)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state2)=>!knownStates.has(state2)))return"non_success";let metadata=nestedRecords[0];if(states.some((state2)=>RUNNING_STATES.has(state2))||metadata?.background===!0)return"running";if(states.some((state2)=>SUCCESS_STATES.has(state2)))return"success";if(typeof record3.output==="string")return"success";return Object.keys(record3).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state()});import*as fs57 from"node:fs";import*as path92 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state2=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state2);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state2}function clearStreak(state2){state2.nonProgressCalls=0,state2.warnIssued=!1,state2.denyTelemetryIssued=!1,state2.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state2){state2.armed=!1,state2.workspaceBaseline=null,state2.needsWorkspaceBaseline=!1,clearStreak(state2),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state2){if(!state2.armed)state2.armed=!0,state2.needsWorkspaceBaseline=!0,clearStreak(state2);_internals86.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool3,args2){if(!isTaskToolId(tool3??""))return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs57.readFileSync(path92.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(count2){return`EXECUTION STALL: ${count2} 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(count2,normalizedTool){return`EXECUTION_STALL: ${count2} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool:tool3,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals86.now(),state2=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state2.armed&&now-state2.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state2);state2.lastToolCallAt=now;let role=canonicalDispatchRole(tool3,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state2)}if(!state2.armed)return;state2.nonProgressCalls+=1,state2.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state2.nonProgressCalls>=warnCalls&&!state2.warnIssued){state2.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state2.nonProgressCalls));telemetry.executionStallWarning(sessionID,state2.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool:tool3,options}=params,denial=null;try{if(options?.enabled===!1)return;let state2=stallStates.get(sessionID);if(!state2?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state2.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state2.denyTelemetryIssued){state2.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state2.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state2.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals86.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals86.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:tool3,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool3??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals86.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state2=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state2);if(!state2.armed)return;if(taskSettled&&_internals86.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}if(progress){clearStreak(state2),state2.needsWorkspaceBaseline=!0;return}if(state2.needsWorkspaceBaseline){state2.needsWorkspaceBaseline=!1,state2.callsSinceWorkspaceProbe=0;try{state2.workspaceBaseline=await _internals86.captureWorkspaceSnapshotAsync(directory)}catch{state2.workspaceBaseline=null}return}if(state2.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state2.callsSinceWorkspaceProbe=0,_internals86.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}let probe2=await probeWorkspaceProgress(directory,state2.workspaceBaseline);if(state2.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state2)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals86;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state();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;_internals86={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path93 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path93.relative(path93.resolve(cwd),path93.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=path93.resolve(directory,".swarm"),resolved=path93.resolve(directory,filePath),relative24=path93.relative(swarmDir,resolved);return relative24.startsWith("..")||path93.isAbsolute(relative24)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config3){let budget=config3.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS2){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function makeInjectionBudgetReceipt(data){let receipt=Object.freeze({});return injectionBudgetReceipts.set(receipt,{...data,state:"pending"}),receipt}function settleInjectionBudgetReceipt(receipt,action){let data=injectionBudgetReceipts.get(receipt);if(!data||data.state!=="pending")return!1;let ledger=turnLedgers.get(data.sessionID);if(!ledger||ledger.generation!==data.generation)return data.state="stale",!1;let accounting=ledger.producers.get(data.producer);if(!accounting||accounting!==data.accounting||accounting.surface!==data.surface)return data.state="stale",!1;if(action==="commit")return data.state="committed",!0;if(accounting.requested=Math.max(0,accounting.requested-data.requestedTokens),accounting.granted=Math.max(0,accounting.granted-data.grantedTokens),data.retractEmissionOnRefund){let retracted=Math.min(accounting.emitted,data.emittedTokensOnRefund);accounting.emitted-=retracted,accounting.truncated+=retracted}if(accounting.requested===0&&accounting.granted===0&&accounting.emitted===0&&accounting.truncated===0)ledger.producers.delete(data.producer);return ledger.used=Math.max(0,ledger.used-data.chargedTokens),data.state="refunded",!0}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{result:{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1}};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted,charged=0;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),charged=granted,ledger.used+=charged}return accounting.granted+=granted,{result:{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive},receiptData:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function claimTurnBudget(sessionID,producer,requestedTokens,opts){return applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts).result}function claimTurnBudgetWithReceipt(sessionID,producer,requestedTokens,opts){let mutation=applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts);return{...mutation.result,receipt:mutation.receiptData?makeInjectionBudgetReceipt(mutation.receiptData):void 0}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface)}function applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),requested=Math.max(0,requestedTokens);accounting.requested+=requested;let granted=Math.max(0,grantedTokens);accounting.granted+=granted;let charged=0;if(ledger.ceilingActive)charged=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used)),ledger.used+=charged;return{data:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function recordProducerGrantWithReceipt(sessionID,producer,requestedTokens,grantedTokens,surface,options={}){let mutation=applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,options.expectedGeneration);if(!mutation)return;return makeInjectionBudgetReceipt({...mutation.data,retractEmissionOnRefund:options.retractEmissionOnRefund===!0,emittedTokensOnRefund:Math.max(0,options.emittedTokensOnRefund??0)})}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options){applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options?.expectedGeneration)}function applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),emitted=Math.max(0,emittedTokens);return accounting.emitted+=emitted,accounting.truncated+=Math.max(0,truncatedTokens),{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:0,grantedTokens:0,chargedTokens:0,emittedTokensOnRefund:emitted,retractEmissionOnRefund:!0}}function recordProducerEmissionWithReceipt(sessionID,producer,emittedTokens,surface,options){let receiptData=applyProducerEmission(sessionID,producer,emittedTokens,0,surface,options?.expectedGeneration);return receiptData?makeInjectionBudgetReceipt(receiptData):void 0}function deductProducerEmission(sessionID,producer,removedTokens,options){let ledger=turnLedgers.get(sessionID);if(!ledger||options?.expectedGeneration!==void 0&&ledger.generation!==options.expectedGeneration)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,accounting])=>({producer,requested:accounting.requested,granted:accounting.granted,emitted:accounting.emitted,truncated:accounting.truncated,surface:accounting.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function commitInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"commit")}function refundInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"refund")}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var injectionBudgetReceipts,turnLedgers,MAX_TRACKED_SESSIONS2=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();injectionBudgetReceipts=new WeakMap,turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&"A_ERROR_PATTERN.test(signal)}function isStickyModelError(signal){return MODEL_UNAVAILABLE_PATTERN.test(signal)||isQuotaError(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,MODEL_UNAVAILABLE_PATTERN,QUOTA_ERROR_PATTERN,REQUEST_SHAPE_REJECTION_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|model.?unavailable|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,MODEL_UNAVAILABLE_PATTERN=/model.?unavailable/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,REQUEST_SHAPE_REJECTION_PATTERN=/\b(?:single|one|only|exactly)[^.]{0,48}?\bsystem\s+messages?\b|\bmultiple\s+system\s+messages?\b|\bsystem\s+messages?\s+(?:are\s+)?not\s+supported\b/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set3,key){if(set3.has(key))return!1;while(set3.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set3.values().next().value;if(oldest===void 0)break;set3.delete(oldest)}return set3.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals87.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,_internals87,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"};_internals87={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map3,sessionId,messageId){map3.delete(sessionId),map3.set(sessionId,messageId);while(map3.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map3.keys().next().value;if(stalest===void 0)break;map3.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
|
|
1050
1050
|
`)}function getMostRecentAssistantText(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="assistant")return getMessageText(messages[i]);return""}function isTransientProviderFailureText(text){if(!text.trim())return!1;if(!/provider[_\s-]?unavailable|network\s+connection\s+lost|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN|connection\s+reset|connection\s+refused/i.test(text))return!1;let status=extractStatusCode(text);return status!==null&&TRANSIENT_STATUS_CODES.has(status)||TRANSIENT_MODEL_ERROR_PATTERN.test(text)}function getProviderFailureFingerprint(text){return String(hashArgs({providerFailure:text.slice(-4000)}))}function createMessagesTransformHandler(ctx){let{effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId}=ctx;return async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastMessage=messages[messages.length-1],sessionId=lastMessage.info?.sessionID;if(!sessionId)return;let session=swarmState.agentSessions.get(sessionId),activeAgent=swarmState.activeAgent.get(sessionId)??session?.agentName,targetAgent=[...messages].reverse().find((message)=>message.info?.role==="user"&&typeof message.info.agent==="string"&&message.info.agent.length>0)?.info.agent;{let configuredModel=targetAgent?ctx.resolveAgentModel?.(targetAgent):void 0,targetModel=configuredModel?parseAgentModel(configuredModel):void 0,{modelID}=targetModel??extractModelInfo(messages);if(modelID&&isLowCapabilityModel(modelID))for(let msg of messages){if(msg.info?.role!=="system")continue;for(let part of msg.parts)try{if(part==null)continue;if(part.type!=="text"||typeof part.text!=="string")continue;if(!part.text.includes("<!-- BEHAVIORAL_GUIDANCE_START -->"))continue;part.text=part.text.replace(/<!--\s*BEHAVIORAL_GUIDANCE_START\s*-->[\s\S]*?<!--\s*BEHAVIORAL_GUIDANCE_END\s*-->/g,"[Enforcement: programmatic gates active]")}catch(error93){log("[Guardrails] behavioral guidance replacement failed",{error:error93 instanceof Error?error93.message:String(error93)})}}}let isArchitectSession=activeAgent?stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME:session?stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME:!1;if(isArchitectSession&&session){let{modelID,providerID}=extractModelInfo(messages);if(modelID){let observedFull=providerID?`${providerID}/${modelID}`:modelID,previousObserved=session.lastObservedModel;if(session.sessionRehydratedAt>0&&session.model_fallback_index===0&&previousObserved&&previousObserved!==observedFull&&!session.resumeModelAdvisoryDone)pushAdvisory(session,`MODEL CHANGED ACROSS RESUME: this run previously observed model "${previousObserved}"; the active model is now "${observedFull}". If this switch was unintended, re-select the intended model (or use /swarm handoff) before continuing.`),session.resumeModelAdvisoryDone=!0;if(!session.configModelAdvisoryDone&&session.model_fallback_index===0){let configuredArchitect=getSwarmAgents()?.architect?.model;if(configuredArchitect&&configuredArchitect!==observedFull&&configuredArchitect!==modelID)pushAdvisory(session,`MODEL CONFIG NOTE: your config pins the architect to "${configuredArchitect}", but the UI has "${observedFull}" active. The UI selection wins for the primary/architect role (its configured model is intentionally not applied), so this difference is expected — switch the UI model if you meant to run "${configuredArchitect}".`),session.configModelAdvisoryDone=!0}session.lastObservedModel=observedFull,session.lastObservedProviderID=providerID}}let guidanceCarriers=findGuidanceCarriers(messages);if(isArchitectSession&&session){let lastAssistantText=getMostRecentAssistantText(messages);if(isTransientProviderFailureText(lastAssistantText)){let fingerprint2=getProviderFailureFingerprint(lastAssistantText),alreadyPending=session.pendingAdvisoryMessages?.some((message)=>message.startsWith(TRANSIENT_PROVIDER_RECOVERY_TAG)),alreadyInjected=guidanceCarriers.some((message)=>getMessageText(message).includes(TRANSIENT_PROVIDER_RECOVERY_TAG));if(session.lastProviderRecoveryFingerprint!==fingerprint2&&!alreadyPending&&!alreadyInjected)pushAdvisory(session,`${TRANSIENT_PROVIDER_RECOVERY_TAG}: The previous Architect response appears to have been interrupted by a transient provider/network error. On this turn, continue from the last stable step, inspect current repo or plan state if needed, and keep working instead of treating the interrupted response as task completion.`),session.lastProviderRecoveryFingerprint=fingerprint2}else session.lastProviderRecoveryFingerprint=void 0}if(isArchitectSession){let countedMsgId=lastCountedAssistantMsgId.get(sessionId);if(countedMsgId!==void 0){let countedIdx=messages.findIndex((m)=>m.info?.id===countedMsgId);if(countedIdx<0)lastCountedAssistantMsgId.delete(sessionId);else if(messages.slice(countedIdx+1).some((m)=>m.info?.role==="user"))consecutiveNoToolTurns.set(sessionId,0),lastCountedAssistantMsgId.delete(sessionId)}let lastAssistantMsg;for(let i=messages.length-1;i>=0;i--)if(messages[i].info?.role==="assistant"){lastAssistantMsg=messages[i];break}if(lastAssistantMsg)if(lastAssistantMsg.parts?.some((part)=>part.type==="tool_use"))consecutiveNoToolTurns.set(sessionId,0);else{let textLen=lastAssistantMsg.parts?.filter((p)=>p.type==="text"&&typeof p.text==="string").reduce((sum,p)=>sum+p.text.length,0)??0,lastAssistantMsgId=lastAssistantMsg.info?.id,countsAsMedium=textLen>=RUNAWAY_MEDIUM_MIN&&textLen<=4000&&typeof lastAssistantMsgId==="string"&&lastAssistantMsgId.length>0&&isExecutionEpisodeArmed(sessionId);if(countsAsMedium&&lastAssistantMsgId)rememberCountedAssistantMsg(lastCountedAssistantMsgId,sessionId,lastAssistantMsgId);if(textLen>4000||countsAsMedium){let count2=(consecutiveNoToolTurns.get(sessionId)??0)+1;consecutiveNoToolTurns.set(sessionId,count2);let maxTurns=cfg.runaway_output_max_turns;if(count2>=maxTurns){let stopCarrier=ensureGuidanceCarrier(messages,"guardrails");if(!messageTextOf(stopCarrier).includes("RUNAWAY OUTPUT STOP"))prependGuidanceText(stopCarrier,"guardrails",`[RUNAWAY OUTPUT STOP]
|
|
1051
1051
|
You have produced ${count2} consecutive responses without using any tools. You MUST call a tool in your next response.
|
|
@@ -1195,13 +1195,13 @@ ${line}`)}else{let prefix=fileEndsWithNewline2(filePath)?"":`
|
|
|
1195
1195
|
`:`${outLines[0]}
|
|
1196
1196
|
`),emitHealth2(directory,{trigger,accepted:folded.totalDecisions+finalRetained.length,compacted:toFold.size-dropped,retained:finalRetained.length,dropped,corrupt:folded.corrupt,oldest:folded.oldestTimestamp,newest:folded.newestTimestamp,bytes:fileSizeOrZero2(filePath),limitBytes:_internals92.limits.activeMaxBytes})}function runMaintenance2(directory){try{let filePath=shellAuditFilePath(directory);if(!_internals92.existsSync(filePath))return;let drainThreshold=_internals92.limits.activeMaxBytes+_internals92.limits.headerMaxBytes+2048;withShellAuditStoreLock(directory,()=>{foldPass2(directory,"compaction",!1);let prevSize=Number.POSITIVE_INFINITY;for(let pass=0;pass<64;pass+=1){let size=fileSizeOrZero2(filePath);if(size<=drainThreshold)break;if(size>=prevSize)break;prevSize=size,foldPass2(directory,"compaction",!1)}return!0})}catch{warnThrottled2("maintenance pass failed")}}function finalizeShellAuditForClose(directory,options){try{let filePath=shellAuditFilePath(directory);if(!_internals92.existsSync(filePath))return;withShellAuditStoreLock(directory,()=>{let prev=Number.POSITIVE_INFINITY;for(let pass=0;pass<1e4;pass+=1){let view=readStoreFull2(directory);if(view.manifest!==null)break;if(view.lines.length===0)break;if(view.lines.length>=prev)break;prev=view.lines.length,foldPass2(directory,"close",!1)}foldPass2(directory,"close",!0);let transform3=options?.lineTransform;if(transform3!==void 0){let view=readStoreFull2(directory);if(view.manifest!==null){let manifest={...view.manifest,folded:cloneFolded2(view.manifest.folded),updatedAt:new Date().toISOString()},outLines=[`${JSON.stringify(manifest)}`];for(let entry of view.lines)outLines.push(transform3(entry.line));try{atomicReplace2(directory,`${outLines.join(`
|
|
1197
1197
|
`)}
|
|
1198
|
-
`)}catch{warnThrottled2("archive re-redaction rewrite failed")}}}return!0})}catch{warnThrottled2("finalize failed")}}function emitShellAuditHealth(directory,payload){try{let healthPayload={trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes};telemetry.shellAuditHealth(healthPayload),observeStoreHealth({directory,kind:"shell_audit_health",payload:healthPayload})}catch{}}function emitHealth2(directory,payload){_internals92.emitHealth(directory,payload)}var SHELL_AUDIT_LIMITS,MANIFEST_TYPE2="swarm-shell-audit-manifest",MANIFEST_SCHEMA2=1,BY_TYPE_MAX_KEYS2=16,BY_TYPE_OTHER2="__other__",_internals92,LOCK_RETRY_ATTEMPTS2=20,LOCK_RETRY_DELAY_MS2=5,LOCK_STALE_MS3=300000,sleepScratch2,RENAME_RETRY_DELAYS_MS3,RETRYABLE_RENAME_CODES3,_appendCount3=0,_lastWarnAt2=0,EMPTY_VIEW,SHELL_AUDIT_STORE_LOCKED="SHELL_AUDIT_STORE_LOCKED",SHELL_AUDIT_LINE_TOO_LARGE="SHELL_AUDIT_LINE_TOO_LARGE";var init_shell_audit_store=__esm(()=>{init_learning_health();init_telemetry();init_logger();SHELL_AUDIT_LIMITS={activeMaxBytes:1048576,securityMaxEntries:4000,allowedMaxEntries:2000,allowedAgeMaxMs:259200000,compactMaxBytes:262144,readMaxBytes:262144,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:16384,maxLineBytes:65536,maxCommandChars:4096,maxReasonChars:1024,migrationMaxBytes:8388608};_internals92={appendFileSync:fs62.appendFileSync,readFileSync:fs62.readFileSync,existsSync:fs62.existsSync,mkdirSync:fs62.mkdirSync,statSync:fs62.statSync,renameSync:fs62.renameSync,writeFileSync:fs62.writeFileSync,unlinkSync:fs62.unlinkSync,openSync:fs62.openSync,closeSync:fs62.closeSync,readSync:fs62.readSync,now:()=>Date.now(),limits:SHELL_AUDIT_LIMITS,emitHealth:emitShellAuditHealth};sleepScratch2=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS3=[10,25,50,100,200],RETRYABLE_RENAME_CODES3=new Set(["EPERM","EBUSY","EACCES","EEXIST"]);EMPTY_VIEW={manifest:null,lines:[],corruptLines:0,prefixFolded:null}});import{createHash as createHash48}from"node:crypto";import*as path101 from"node:path";function isPlainObject3(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function validateEntry(entry){if(!isPlainObject3(entry))return log("guardrail audit: rejected non-object entry",entry),!1;for(let field of REQUIRED_STRING_FIELDS)if(typeof entry[field]!=="string")return log("guardrail audit: rejected entry missing string field",{field,entry}),!1;if(!["shell","file_write","scope_violation","destructive_block","sandbox_wrap","sandbox_skip"].includes(entry.type))return log("guardrail audit: rejected entry with invalid type",{type:entry.type,entry}),!1;switch(entry.type){case"shell":break;case"file_write":{let required3=["path","reason","resolvedScope"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected file_write entry missing string field",{field,entry}),!1;break}case"scope_violation":{let required3=["path","declaredScope","resolvedScope","action"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected scope_violation entry missing string field",{field,entry}),!1;break}case"destructive_block":{let required3=["command","destructiveCategory"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected destructive_block entry missing string field",{field,entry}),!1;break}case"sandbox_wrap":{let required3=["command","executorMechanism"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected sandbox_wrap entry missing string field",{field,entry}),!1;break}case"sandbox_skip":{let required3=["command","executorMechanism","skipReason"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected sandbox_skip entry missing string field",{field,entry}),!1;break}}return!0}function truncateUtf8Safe(text,maxChars){if(text.length<=maxChars)return text;let cut=text.slice(0,maxChars),last=cut.charCodeAt(cut.length-1);if(last>=55296&&last<=56319)return`${cut.slice(0,-1)}…[truncated]`;return`${cut}…[truncated]`}function hashRedactedCommand(redacted){return createHash48("sha256").update(redacted,"utf-8").digest("hex").slice(0,16)}function redactPath(filePath){if(typeof filePath!=="string")return"";if(filePath.length===0)return filePath;let rawPosixHomeMatch=filePath.match(/^(\/home\/[^/]+)(\/.*)$/);if(rawPosixHomeMatch)return`~${rawPosixHomeMatch[2]}`;let rawMacHomeMatch=filePath.match(/^(\/Users\/[^/]+)(\/.*)$/);if(rawMacHomeMatch)return`~${rawMacHomeMatch[2]}`;let normalized=path101.normalize(filePath),windowsHomeMatch=normalized.match(/^([A-Za-z]:\\[Uu][Ss][Ee][Rr][Ss]\\[^\\]+)(\\.*)$/i);if(windowsHomeMatch)return`~\\${windowsHomeMatch[2]}`;let uncHomeMatch=normalized.match(/^\\\\[^\\]+\\([^\\]+)\\([^\\]+)(\\.*)$/);if(uncHomeMatch)return`~\\${uncHomeMatch[1]}\\${uncHomeMatch[2]}${uncHomeMatch[3]}`;return normalized}function redactEmbeddedPaths(text){return text.replace(/\/home\/[^/\s]+(\/[^\s"'`)]*)?/g,(match)=>redactPath(match)).replace(/\/Users\/[^/\s]+(\/[^\s"'`)]*)?/g,(match)=>redactPath(match)).replace(/[A-Za-z]:\\Users\\[^\\\s]+(\\[^\s"'`)]*)?/gi,(match)=>redactPath(match)).replace(/\\\\[^\\\s]+\\[^\\\s]+\\[^\\\s]+(\\[^\s"'`)]*)?/g,(match)=>redactPath(match))}function redactDecisionLineForArchive(line){let parsed;try{parsed=JSON.parse(line)}catch{return line}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return line;let record3=parsed,changed2=!1;if(typeof record3.command==="string"){let redacted=redactShellCommand(record3.command);if(redacted!==record3.command){if(record3.command=redacted,changed2=!0,typeof record3.commandHash==="string")record3.commandHash=hashRedactedCommand(redacted)}}if(typeof record3.path==="string"){let redacted=redactPath(record3.path);if(redacted!==record3.path)record3.path=redacted,changed2=!0}if(typeof record3.reason==="string"){let redacted=redactEmbeddedPaths(record3.reason);if(redacted!==record3.reason)record3.reason=redacted,changed2=!0}for(let field of["declaredScope","resolvedScope"])if(typeof record3[field]==="string"){let redacted=redactPath(record3[field]);if(redacted!==record3[field])record3[field]=redacted,changed2=!0}return changed2?JSON.stringify(record3):line}async function appendGuardrailDecision(entry,ctx){if(!ctx.enabled)return;if(!validateEntry(entry))return;let maxCommand=SHELL_AUDIT_LIMITS.maxCommandChars,maxReason=SHELL_AUDIT_LIMITS.maxReasonChars,line;switch(entry.type){case"shell":line=`${JSON.stringify({ts:entry.ts,sessionID:entry.sessionID,agent:entry.agent,tool:entry.tool,command:truncateUtf8Safe(redactShellCommand(entry.command),maxCommand)})}
|
|
1198
|
+
`)}catch{warnThrottled2("archive re-redaction rewrite failed")}}}return!0})}catch{warnThrottled2("finalize failed")}}function emitShellAuditHealth(directory,payload){try{let healthPayload={trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes};telemetry.shellAuditHealth(healthPayload),observeStoreHealth({directory,kind:"shell_audit_health",payload:healthPayload})}catch{}}function emitHealth2(directory,payload){_internals92.emitHealth(directory,payload)}var SHELL_AUDIT_LIMITS,MANIFEST_TYPE2="swarm-shell-audit-manifest",MANIFEST_SCHEMA2=1,BY_TYPE_MAX_KEYS2=16,BY_TYPE_OTHER2="__other__",_internals92,LOCK_RETRY_ATTEMPTS2=20,LOCK_RETRY_DELAY_MS2=5,LOCK_STALE_MS3=300000,sleepScratch2,RENAME_RETRY_DELAYS_MS3,RETRYABLE_RENAME_CODES3,_appendCount3=0,_lastWarnAt2=0,EMPTY_VIEW,SHELL_AUDIT_STORE_LOCKED="SHELL_AUDIT_STORE_LOCKED",SHELL_AUDIT_LINE_TOO_LARGE="SHELL_AUDIT_LINE_TOO_LARGE";var init_shell_audit_store=__esm(()=>{init_learning_health();init_telemetry();init_logger();SHELL_AUDIT_LIMITS={activeMaxBytes:1048576,securityMaxEntries:4000,allowedMaxEntries:2000,allowedAgeMaxMs:259200000,compactMaxBytes:262144,readMaxBytes:262144,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:16384,maxLineBytes:65536,maxCommandChars:4096,maxReasonChars:1024,maxPathChars:320,migrationMaxBytes:8388608};_internals92={appendFileSync:fs62.appendFileSync,readFileSync:fs62.readFileSync,existsSync:fs62.existsSync,mkdirSync:fs62.mkdirSync,statSync:fs62.statSync,renameSync:fs62.renameSync,writeFileSync:fs62.writeFileSync,unlinkSync:fs62.unlinkSync,openSync:fs62.openSync,closeSync:fs62.closeSync,readSync:fs62.readSync,now:()=>Date.now(),limits:SHELL_AUDIT_LIMITS,emitHealth:emitShellAuditHealth};sleepScratch2=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS3=[10,25,50,100,200],RETRYABLE_RENAME_CODES3=new Set(["EPERM","EBUSY","EACCES","EEXIST"]);EMPTY_VIEW={manifest:null,lines:[],corruptLines:0,prefixFolded:null}});import{createHash as createHash48}from"node:crypto";import*as path101 from"node:path";function isPlainObject3(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function validateEntry(entry){if(!isPlainObject3(entry))return log("guardrail audit: rejected non-object entry",entry),!1;for(let field of REQUIRED_STRING_FIELDS)if(typeof entry[field]!=="string")return log("guardrail audit: rejected entry missing string field",{field,entry}),!1;if(!["shell","file_write","scope_violation","destructive_block","sandbox_wrap","sandbox_skip"].includes(entry.type))return log("guardrail audit: rejected entry with invalid type",{type:entry.type,entry}),!1;switch(entry.type){case"shell":break;case"file_write":{let required3=["path","reason","resolvedScope"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected file_write entry missing string field",{field,entry}),!1;break}case"scope_violation":{let required3=["path","declaredScope","resolvedScope","action"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected scope_violation entry missing string field",{field,entry}),!1;if(entry.operator!==void 0&&typeof entry.operator!=="string")return log("guardrail audit: rejected scope_violation entry with non-string operator",{entry}),!1;break}case"destructive_block":{let required3=["command","destructiveCategory"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected destructive_block entry missing string field",{field,entry}),!1;break}case"sandbox_wrap":{let required3=["command","executorMechanism"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected sandbox_wrap entry missing string field",{field,entry}),!1;break}case"sandbox_skip":{let required3=["command","executorMechanism","skipReason"];for(let field of required3)if(typeof entry[field]!=="string")return log("guardrail audit: rejected sandbox_skip entry missing string field",{field,entry}),!1;break}}return!0}function truncateUtf8Safe(text,maxChars){if(text.length<=maxChars)return text;let cut=text.slice(0,maxChars),last=cut.charCodeAt(cut.length-1);if(last>=55296&&last<=56319)return`${cut.slice(0,-1)}…[truncated]`;return`${cut}…[truncated]`}function hashRedactedCommand(redacted){return createHash48("sha256").update(redacted,"utf-8").digest("hex").slice(0,16)}function redactPath(filePath){if(typeof filePath!=="string")return"";if(filePath.length===0)return filePath;let rawPosixHomeMatch=filePath.match(/^(\/home\/[^/]+)(\/.*)$/);if(rawPosixHomeMatch)return`~${rawPosixHomeMatch[2]}`;let rawMacHomeMatch=filePath.match(/^(\/Users\/[^/]+)(\/.*)$/);if(rawMacHomeMatch)return`~${rawMacHomeMatch[2]}`;let normalized=path101.normalize(filePath),windowsHomeMatch=normalized.match(/^([A-Za-z]:\\[Uu][Ss][Ee][Rr][Ss]\\[^\\]+)(\\.*)$/i);if(windowsHomeMatch)return`~\\${windowsHomeMatch[2]}`;let uncHomeMatch=normalized.match(/^\\\\[^\\]+\\([^\\]+)\\([^\\]+)(\\.*)$/);if(uncHomeMatch)return`~\\${uncHomeMatch[1]}\\${uncHomeMatch[2]}${uncHomeMatch[3]}`;return normalized}function redactEmbeddedPaths(text){return text.replace(/\/home\/[^/\s]+(\/[^\s"'`)]*)?/g,(match)=>redactPath(match)).replace(/\/Users\/[^/\s]+(\/[^\s"'`)]*)?/g,(match)=>redactPath(match)).replace(/[A-Za-z]:\\Users\\[^\\\s]+(\\[^\s"'`)]*)?/gi,(match)=>redactPath(match)).replace(/\\\\[^\\\s]+\\[^\\\s]+\\[^\\\s]+(\\[^\s"'`)]*)?/g,(match)=>redactPath(match))}function redactDecisionLineForArchive(line){let parsed;try{parsed=JSON.parse(line)}catch{return line}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return line;let record3=parsed,changed2=!1;if(typeof record3.command==="string"){let redacted=redactShellCommand(record3.command);if(redacted!==record3.command){if(record3.command=redacted,changed2=!0,typeof record3.commandHash==="string")record3.commandHash=hashRedactedCommand(redacted)}}if(typeof record3.path==="string"){let redacted=redactPath(record3.path);if(redacted!==record3.path)record3.path=redacted,changed2=!0}if(typeof record3.reason==="string"){let redacted=redactEmbeddedPaths(record3.reason);if(redacted!==record3.reason)record3.reason=redacted,changed2=!0}if(typeof record3.operator==="string"){let redacted=truncateUtf8Safe(redactEmbeddedPaths(record3.operator),32);if(redacted!==record3.operator)record3.operator=redacted,changed2=!0}for(let field of["declaredScope","resolvedScope"])if(typeof record3[field]==="string"){let redacted=redactPath(record3[field]);if(redacted!==record3[field])record3[field]=redacted,changed2=!0}return changed2?JSON.stringify(record3):line}async function appendGuardrailDecision(entry,ctx){if(!ctx.enabled)return;if(!validateEntry(entry))return;let maxCommand=SHELL_AUDIT_LIMITS.maxCommandChars,maxReason=SHELL_AUDIT_LIMITS.maxReasonChars,maxPath=SHELL_AUDIT_LIMITS.maxPathChars,line;switch(entry.type){case"shell":line=`${JSON.stringify({ts:entry.ts,sessionID:entry.sessionID,agent:entry.agent,tool:entry.tool,command:truncateUtf8Safe(redactShellCommand(entry.command),maxCommand)})}
|
|
1199
1199
|
`;break;case"destructive_block":case"sandbox_wrap":case"sandbox_skip":{let command=truncateUtf8Safe(redactShellCommand(entry.command),maxCommand);line=`${JSON.stringify({...entry,command,commandHash:hashRedactedCommand(command)})}
|
|
1200
|
-
`;break}case"file_write":line=`${JSON.stringify({...entry,path:redactPath(entry.path),reason:truncateUtf8Safe(redactEmbeddedPaths(entry.reason),maxReason),resolvedScope:redactPath(entry.resolvedScope)})}
|
|
1201
|
-
`;break;case"scope_violation":line=`${JSON.stringify({...entry,path:redactPath(entry.path),declaredScope:redactPath(entry.declaredScope),resolvedScope:redactPath(entry.resolvedScope)})}
|
|
1202
|
-
`;break}try{appendShellAuditLineSync(ctx.directory,line)}catch(error93){log("guardrail audit: append failed",{directory:ctx.directory,error:error93})}}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 fsSync10 from"node:fs";import*as os14 from"node:os";import*as path102 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path102.join(dir,"package.json");if(!_internals93.existsSync(manifestPath))return null;let name=JSON.parse(_internals93.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=path102.dirname(fileURLToPath3(_internals93.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path102.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 cached3=selfDevelopmentWorkspaces.get(resolved);if(cached3!==void 0)return cached3;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=path102.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path102.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals93.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path102.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(!path102.isAbsolute(expanded))continue;try{resolved.push(path102.resolve(expanded))}catch{}}return resolved}function enforceInternalsGuard(params){let{sessionID,tool:tool3,args:args2,directory,options}=params;if(options?.enabled===!1)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!GUARDED_TOOLS.has(normalizedTool))return;let match=null,relativeTarget="";try{let packageRoot=_internals93.resolvePackageRoot();if(!packageRoot)return;if(_internals93.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path102.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path102.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,_internals93;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;_internals93={moduleUrl:()=>import.meta.url,existsSync:(p)=>fsSync10.existsSync(p),readFileSync:(p,enc)=>fsSync10.readFileSync(p,enc),homedir:()=>os14.homedir(),resolvePackageRoot,isSelfDevelopmentWorkspace,resetCaches:()=>{cachedPackageRoot=void 0,selfDevelopmentWorkspaces.clear()}}});import*as fs63 from"node:fs";import*as path103 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 isPosixRmdirExecutor(tool3,windowsShell,detectionCommand,platform=process.platform){if(windowsShell!==null)return!1;if(tool3!=="bash"&&platform==="win32")return!1;return!declaresWindowsWrapperLoose(detectionCommand)&&!CMD_WRAPPER_DECLARATION.test(detectionCommand)}function isControlStateRelativePath(relative31){return isPolicyProtectedPath(relative31.toLowerCase(),{includeDefaults:!1,additional:RMDIR_EXEMPTION_CONTROL_STATE})}function isEmptyDirectoryRemovalWithinWorkspace(targetPath,workspace){try{let lexicalRoot=path103.resolve(workspace);if(isControlStateRelativePath(path103.relative(lexicalRoot,path103.resolve(lexicalRoot,targetPath))))return!1;let root=fs63.realpathSync.native(lexicalRoot),absolute=path103.resolve(root,targetPath),parent=fs63.realpathSync.native(path103.dirname(absolute)),canonical=path103.join(parent,path103.basename(absolute));if(isControlStateRelativePath(path103.relative(root,canonical)))return!1;let stat11;try{stat11=fs63.lstatSync(canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}if(stat11&&(!stat11.isDirectory()||stat11.isSymbolicLink()))return!1;return!pathIdentitiesEqual(canonical,root)&&isPathIdentityWithin(canonical,root)}catch{return!1}}function resolveWindowsWriteAuthority(tool3,command,detectedShellType,shaped,platform=process.platform,hostShell){let cmdWrapper=CMD_WRAPPER_DECLARATION.test(command),psWrapper=declaresWindowsWrapperLoose(command),inheritedWindows=detectedShellType==="powershell"||detectedShellType==="cmd";if(cmdWrapper)return"cmd";if(psWrapper||shaped)return"powershell";if(tool3==="bash")return null;if(tool3==="shell"&&hostShell!==void 0&&hostShell!=="")return hostShellGrammarFamily(hostShell)==="windows"&&inheritedWindows?detectedShellType:null;let posixShellTool=tool3==="bash"||tool3==="shell";if(inheritedWindows&&!posixShellTool)return detectedShellType;if(inheritedWindows&&posixShellTool&&platform==="win32")return detectedShellType;return null}function createToolBeforeHandler(ctx){let{effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,getSandboxExecutor,assessSandboxEnforcement:assessSandboxEnforcement2,rememberReviewerScopeWrite,rememberScopeLeaseCandidate}=ctx,enforcePolicy=ctx.enforcePolicy!==!1;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 resolveActiveScopeBindingObserving(sessionID){try{return resolveActiveScopeBinding(sessionID)}catch{return null}}function resolveDeclaredScope(sessionID,observing=!1){let session=swarmState.agentSessions.get(sessionID);if(!session?.currentTaskId)return session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null;return(observing?resolveActiveScopeBindingObserving(sessionID):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,tool3){let normalizedTool=normalizeToolName(tool3).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,tool3,args2){if(tool3!=="bash"&&tool3!=="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,tool3,args2,commandOverride,options){let enforce=options?.enforce!==!1;if(tool3!=="bash"&&tool3!=="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=tool3,detectedShellType=detectShellType(command),shaped=isPowerShellShaped(command),shellType=detectedShellType;if(enforce&&(shellType==="powershell"||shellType==="cmd"?[shellType,"posix"]:["posix"]).some((candidate)=>detectInteractiveSession(command,candidate)))throw Error("BLOCKED: interactive/session tool detected — rejecting for safety");let windowsShell=resolveWindowsWriteAuthority(normalizedTool,command,detectedShellType,shaped,process.platform,normalizedTool==="shell"?getObservedHostShell():void 0),wrapperDeclaredHere=declaresWindowsWrapperLoose(command),windowsAuthoritative=wrapperDeclaredHere||normalizedTool!=="bash",detect=(c)=>{let posix15=detectPosixWrites(c);if(windowsShell===null)return posix15;return mergeWriteAnalyses(posix15,detectWindowsWrites(c,windowsShell),windowsAuthoritative,wrapperDeclaredHere)},suppressParseError=(c)=>enforce&&isPowerShellReadOnlyPipeline(c),primaryAnalysis=detect(command);if(enforce&&primaryAnalysis.parseError&&!suppressParseError(command))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(`
|
|
1203
|
-
`):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(didUnwrap){let regained=primaryAnalysis.writes.filter((w)=>!(w.category==="interpreter_eval"&&w.path===null&&!w.operator.endsWith("[eval stdin]")));if(regained.length>0)analysis={...analysis,writes:[...analysis.writes,...regained],hasWrites:analysis.hasWrites||regained.length>0};if(analysis.parseError&&!primaryAnalysis.parseError)analysis=primaryAnalysis}if(enforce&&analysis.parseError&&!suppressParseError(analysis===primaryAnalysis?command:detectionCommand))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,!enforce),shellWriteAgent=swarmState.activeAgent.get(sessionID);if(!shellWriteAgent){if(enforce)throw Error(`WRITE BLOCKED: No active agent registered for session "${sessionID}". Agent identity must be established (e.g. via a chat message or Task delegation) before shell writes can be authorized.`);return}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(enforce&&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),enforceWriteAuthorization=(target,opts)=>{if(enforce&&noScopeLenient&&universalDenyPrefixes.length>0){for(let prefix of universalDenyPrefixes)if(matchesAuthorityDenyPrefix(target,prefix,shellDirectory))throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${target}" (via shell). Reason: Path is under universal deny prefix "${prefix}"`)}if(noScopeLenient)return"lenient";let authorityCheck=checkFileAuthorityWithRules(shellWriteAgent,target,shellDirectory,precomputedAuthorityRules,{declaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(enforce&&!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"protected_state_mutation",paths:[target]}):void 0;throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${target}" (via shell). Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}if(enforce&&declaredScope&&declaredScope.length>0&&!isInDeclaredScope(target,declaredScope,shellDirectory)&&!(opts?.exemptEmptyDirectoryRemoval===!0&&isPosixRmdirExecutor(normalizedTool,windowsShell,detectionCommand)&&isEmptyDirectoryRemovalWithinWorkspace(target,shellDirectory))){let safeTarget=sanitizeDiagnosticText(target,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.`)}return"enforced"};for(let write of resolvedWrites){if(write.resolvedPath===null){if(write.original.category==="here_doc"&&write.original.path===null)continue;if(enforce&&write.original.category==="interpreter_eval"){if(write.original.capability===!0&&(isImmutableNonWriter||declaredScope!==null&&declaredScope!==void 0&&declaredScope.length>0)){enforceWriteAuthorization(write.evalDirectory??shellDirectory);continue}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.`)}if(enforce)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.`);continue}if(enforceWriteAuthorization(write.resolvedPath,{exemptEmptyDirectoryRemoval:write.original.emptyDirectoryRemoval===!0})==="lenient")continue;if(isCoder&&session?.currentTaskId){let writeBinding=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path103.relative(path103.resolve(shellDirectory),path103.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=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(binding)rememberScopeLeaseCandidate?.({callID,sessionID,tool:tool3,directory:shellDirectory,binding,targets:resolvedWrites.flatMap((write)=>write.resolvedPath===null?[]:[path103.resolve(shellDirectory,write.resolvedPath)]),args:args2})}}function isSandboxWrapperInvocation(raw){let head=raw.replace(/^\s*(?:(?:exec|(?:\/(?:usr\/)?bin\/)?env)(?:\s+(?:-\S+|[A-Za-z_]\w*=\S*))*\s+)*/,"");return/^(?:\/(?:usr\/(?:local\/)?)?bin\/)?bwrap(?:\s|$)/.test(head)}async function applySandboxExecution(sessionID,callID,tool3,args2,agent,command,auditEnabled){if(tool3!=="bash"&&tool3!=="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:tool3,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:tool3,command,executorMechanism:executor?.mechanism??"none",skipReason:"executor not available"},{directory:effectiveDirectory,enabled:auditEnabled});return}let declaredPaths=resolveDeclaredScope(sessionID,!enforcePolicy);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])];if(normalizeSandboxMechanism2(executor.mechanism)==="bubblewrap"&&isSandboxWrapperInvocation(rawCommand))throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"command already invokes the sandbox wrapper"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: the command already invokes bwrap. Every bash call is sandboxed by the harness (${executor.mechanism}); a nested wrapper fails with "No permissions to create new namespace". Re-issue the plain command without the bwrap prefix.`);let workspaceRoot=sessionWorkspaceDirectory(sessionID),readonlyWorkspaceRoot=workspaceRoot;try{readonlyWorkspaceRoot=fs63.realpathSync(workspaceRoot)}catch{}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,readonly_roots:[readonlyWorkspaceRoot]});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:tool3,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:tool3,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,tool3,args2){if(!swarmState.agentSessions.get(sessionID)?.delegationActive&&isArchitect(sessionID)){let coderDeleg=isAgentDelegation(tool3,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,tool3,args2){if(!isTaskToolId(tool3))return;let loopArgs=args2,loopResult=detectLoop(sessionID,tool3,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(`
|
|
1204
|
-
`),timestamp:Date.now()}}}}function handleTestSuiteBlocking(tool3,args2){if(tool3!=="bash"&&tool3!=="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(tool3,args2){if(tool3!=="apply_patch"&&tool3!=="swarm_apply_patch"&&tool3!=="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,tool3,args2){let toolArgs=args2,targetPath=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(tool3==="apply_patch"||tool3==="swarm_apply_patch"||tool3==="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=path103.resolve(effectiveDirectory,targetPath).toLowerCase(),planMdPath=path103.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path103.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=path103.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&&(tool3==="apply_patch"||tool3==="swarm_apply_patch"||tool3==="patch"))for(let p of extractPatchTargetPaths(tool3,args2)){let resolvedP=path103.resolve(effectiveDirectory,p),planMdPath=path103.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path103.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase(),specStalenessPath=path103.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:tool3,sessionID,targetPath:p,writeCount:session.architectWriteCount});break}}if(typeof targetPath==="string"&&targetPath.length>0&&isOutsideSwarmDir(targetPath,effectiveDirectory)&&isSourceCodePath(path103.relative(effectiveDirectory,path103.resolve(effectiveDirectory,targetPath)))){let session=swarmState.agentSessions.get(sessionID);if(session){if(session.architectWriteCount++,warn("Architect direct code edit detected",{tool:tool3,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:tool3,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,tool3,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 hash4=hashArgs(args2);if(window2.recentToolCalls.push({tool:tool3,argsHash:hash4,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)=>{if(enforcePolicy)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";if(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),enforcePolicy)handleLoopDetection(input.sessionID,input.tool,output.args);if(enforcePolicy&&isSwarmOwnedSession(input.sessionID))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});if(enforcePolicy)handleInterpreterGating(input.sessionID,input.tool);try{if(enforcePolicy)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,{enforce:enforcePolicy})}catch(err){let toolArgs=output.args,declaredScope=resolveDeclaredScope(input.sessionID,!0),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),enforcePolicy)await applySandboxExecution(input.sessionID,input.callID,input.tool,output.args,agentNameForSandbox,rawShellCommand,shellAuditEnabled);if(enforcePolicy)enforceSpecDriftGate(effectiveDirectory,input.tool);if(enforcePolicy&&isArchitect(input.sessionID)&&isWriteTool(input.tool))handlePlanAndScopeProtection(input.sessionID,input.tool,output.args);if(input.tool==="apply_patch"||input.tool==="swarm_apply_patch"||input.tool==="patch"){let patchArgs=output.args,structuralPatch=typeof patchArgs?.input==="string"?patchArgs.input:typeof patchArgs?.patch==="string"?patchArgs.patch:typeof patchArgs?.diff==="string"?patchArgs.diff:void 0;if(structuralPatch===void 0)for(let key2 of PATCH_PAYLOAD_KEYS){let value=patchArgs?.[key2];if(typeof value==="string"){structuralPatch=value;break}}if(structuralPatch===void 0&&Array.isArray(patchArgs?.cmd)&&typeof patchArgs.cmd[1]==="string")structuralPatch=patchArgs.cmd[1];if(structuralPatch===void 0&&typeof patchArgs?.cmd==="string")structuralPatch=patchArgs.cmd;if((structuralPatch??"").length>1e6)throw Error("WRITE BLOCKED: Patch payload exceeds 1 MB — authority cannot be verified for all modified paths. Split into smaller patches.")}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"){if(enforcePolicy)throw Error(`WRITE TARGET UNVERIFIABLE: ${resolution.reason}`)}else resolvedFileTargets=resolution.paths;let writeBinding=session?.currentTaskId&&isCoder?enforcePolicy?resolveActiveScopeBinding(input.sessionID):resolveActiveScopeBindingObserving(input.sessionID):null;if(writeBinding)rememberScopeLeaseCandidate?.({callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:writeDirectory,binding:writeBinding,targets:(resolvedFileTargets??[]).map((target)=>path103.resolve(writeDirectory,target)),args:output.args})}if(isWriteTool(input.tool))for(let targetPath of resolvedFileTargets??[]){let agentName=swarmState.activeAgent.get(input.sessionID);if(!agentName){if(!enforcePolicy)continue;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){if(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,!enforcePolicy);return scope!=null&&scope.length>0?scope.join(", "):""})()},{directory:effectiveDirectory,enabled:shellAuditEnabled}),enforcePolicy)throw Error(lstatBlock)}let writeBinding=session?.currentTaskId&&isCoder?enforcePolicy?resolveActiveScopeBinding(input.sessionID):resolveActiveScopeBindingObserving(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;if(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}),!enforcePolicy)continue;throw 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=path103.relative(path103.resolve(writeDirectory),path103.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,writeDirectory)}if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path103.relative(path103.resolve(writeDirectory),path103.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);if(enforcePolicy)await checkGateLimits({sessionID:input.sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount})}if(enforcePolicy){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,RMDIR_EXEMPTION_CONTROL_STATE;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_protected_path_policy();init_state();init_telemetry();init_utils();init_core3();init_loop_detector();init_normalize_tool_name();init_shell_executor_context();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"}};RMDIR_EXEMPTION_CONTROL_STATE=[".git",".swarm"]});import*as fsSync11 from"node:fs";import*as path104 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(error93){let message=error93 instanceof Error?error93.message:String(error93),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 state2 of states){if(!isStrictTaskId(state2.taskId))continue;if(state2.state==="DISPATCHED"||state2.state==="PREPARED"){if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state2.taskId)).state==="coder_delegated")inFlightAtCoderDelegated.add(state2.taskId);continue}if(state2.state!=="COMMITTED")continue;if(state2.accepted!==!0)continue;if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state2.taskId)).state==="coder_delegated")eligible.push(state2)}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(error93){return warn("Durable gate attribution fallback failed",{error:String(error93)}),null}}function enforceSpecDriftGate(directory,toolName){if(!directory)return;if(!SPEC_DRIFT_BLOCKED_TOOLS.has(toolName))return;let stalePath=path104.join(directory,".swarm","spec-staleness.json");if(fsSync11.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?`
|
|
1200
|
+
`;break}case"file_write":line=`${JSON.stringify({...entry,path:truncateUtf8Safe(redactPath(entry.path),maxPath),reason:truncateUtf8Safe(redactEmbeddedPaths(entry.reason),maxReason),resolvedScope:truncateUtf8Safe(redactPath(entry.resolvedScope),maxPath)})}
|
|
1201
|
+
`;break;case"scope_violation":line=`${JSON.stringify({...entry,path:truncateUtf8Safe(redactPath(entry.path),maxPath),declaredScope:truncateUtf8Safe(redactPath(entry.declaredScope),maxPath),resolvedScope:truncateUtf8Safe(redactPath(entry.resolvedScope),maxPath),...typeof entry.operator==="string"?{operator:truncateUtf8Safe(redactEmbeddedPaths(entry.operator),32)}:{}})}
|
|
1202
|
+
`;break}try{appendShellAuditLineSync(ctx.directory,line)}catch(error93){log("guardrail audit: append failed",{directory:ctx.directory,error:error93})}}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",operator:"free-text-redacted",destructiveCategory:"enum",executorMechanism:"enum",skipReason:"enum"}),REQUIRED_STRING_FIELDS=["ts","sessionID","agent","tool","type"]});import*as fsSync10 from"node:fs";import*as os14 from"node:os";import*as path102 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path102.join(dir,"package.json");if(!_internals93.existsSync(manifestPath))return null;let name=JSON.parse(_internals93.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=path102.dirname(fileURLToPath3(_internals93.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path102.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 cached3=selfDevelopmentWorkspaces.get(resolved);if(cached3!==void 0)return cached3;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=path102.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path102.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals93.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path102.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(!path102.isAbsolute(expanded))continue;try{resolved.push(path102.resolve(expanded))}catch{}}return resolved}function enforceInternalsGuard(params){let{sessionID,tool:tool3,args:args2,directory,options}=params;if(options?.enabled===!1)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!GUARDED_TOOLS.has(normalizedTool))return;let match=null,relativeTarget="";try{let packageRoot=_internals93.resolvePackageRoot();if(!packageRoot)return;if(_internals93.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path102.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path102.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,_internals93;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;_internals93={moduleUrl:()=>import.meta.url,existsSync:(p)=>fsSync10.existsSync(p),readFileSync:(p,enc)=>fsSync10.readFileSync(p,enc),homedir:()=>os14.homedir(),resolvePackageRoot,isSelfDevelopmentWorkspace,resetCaches:()=>{cachedPackageRoot=void 0,selfDevelopmentWorkspaces.clear()}}});import*as fs63 from"node:fs";import*as path103 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 isPosixRmdirExecutor(tool3,windowsShell,detectionCommand,platform=process.platform){if(windowsShell!==null)return!1;if(tool3!=="bash"&&platform==="win32")return!1;return!declaresWindowsWrapperLoose(detectionCommand)&&!CMD_WRAPPER_DECLARATION.test(detectionCommand)}function isControlStateRelativePath(relative31){return isPolicyProtectedPath(relative31.toLowerCase(),{includeDefaults:!1,additional:RMDIR_EXEMPTION_CONTROL_STATE})}function isEmptyDirectoryRemovalWithinWorkspace(targetPath,workspace){try{let lexicalRoot=path103.resolve(workspace);if(isControlStateRelativePath(path103.relative(lexicalRoot,path103.resolve(lexicalRoot,targetPath))))return!1;let root=fs63.realpathSync.native(lexicalRoot),absolute=path103.resolve(root,targetPath),parent=fs63.realpathSync.native(path103.dirname(absolute)),canonical=path103.join(parent,path103.basename(absolute));if(isControlStateRelativePath(path103.relative(root,canonical)))return!1;let stat11;try{stat11=fs63.lstatSync(canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}if(stat11&&(!stat11.isDirectory()||stat11.isSymbolicLink()))return!1;return!pathIdentitiesEqual(canonical,root)&&isPathIdentityWithin(canonical,root)}catch{return!1}}function resolveWindowsWriteAuthority(tool3,command,detectedShellType,shaped,platform=process.platform,hostShell){let cmdWrapper=CMD_WRAPPER_DECLARATION.test(command),psWrapper=declaresWindowsWrapperLoose(command),inheritedWindows=detectedShellType==="powershell"||detectedShellType==="cmd";if(cmdWrapper)return"cmd";if(psWrapper||shaped)return"powershell";if(tool3==="bash")return null;if(tool3==="shell"&&hostShell!==void 0&&hostShell!=="")return hostShellGrammarFamily(hostShell)==="windows"&&inheritedWindows?detectedShellType:null;let posixShellTool=tool3==="bash"||tool3==="shell";if(inheritedWindows&&!posixShellTool)return detectedShellType;if(inheritedWindows&&posixShellTool&&platform==="win32")return detectedShellType;return null}function createToolBeforeHandler(ctx){let{effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,getSandboxExecutor,assessSandboxEnforcement:assessSandboxEnforcement2,rememberReviewerScopeWrite,rememberScopeLeaseCandidate}=ctx,enforcePolicy=ctx.enforcePolicy!==!1;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 resolveActiveScopeBindingObserving(sessionID){try{return resolveActiveScopeBinding(sessionID)}catch{return null}}function resolveDeclaredScope(sessionID,observing=!1){let session=swarmState.agentSessions.get(sessionID);if(!session?.currentTaskId)return session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null;return(observing?resolveActiveScopeBindingObserving(sessionID):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,tool3){let normalizedTool=normalizeToolName(tool3).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,tool3,args2){if(tool3!=="bash"&&tool3!=="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)}let rmdirSwitchVerb=/^(?:rmdir|rd)(?:\.exe)?\s*/i.exec(seg);if(rmdirSwitchVerb){let parsed=dcParseWindowsRecursiveDelete(seg.slice(rmdirSwitchVerb[0].length));if(parsed.fires){if(parsed.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:parsed.targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive directory delete",decision.reason)}}let delSwitchVerb=/^del(?:\.exe)?\s*/i.exec(seg);if(delSwitchVerb){let parsed=dcParseWindowsRecursiveDelete(seg.slice(delSwitchVerb[0].length));if(parsed.fires){if(parsed.targets.length===0)throwDestructiveBlock("recursive file delete","BLOCKED: Windows recursive file delete (del /s) detected. Verify the target is not a junction/symlink.");let decision=dcEvaluateRecursiveDeleteTargets({targets:parsed.targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive file delete",decision.reason)}}if(/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*\s-[Rr]ecurse\b/i.test(seg)||/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*\s-[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,tool3,args2,commandOverride,options){let enforce=options?.enforce!==!1;if(tool3!=="bash"&&tool3!=="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=tool3,detectedShellType=detectShellType(command),shaped=isPowerShellShaped(command),shellType=detectedShellType;if(enforce&&(shellType==="powershell"||shellType==="cmd"?[shellType,"posix"]:["posix"]).some((candidate)=>detectInteractiveSession(command,candidate)))throw Error("BLOCKED: interactive/session tool detected — rejecting for safety");let windowsShell=resolveWindowsWriteAuthority(normalizedTool,command,detectedShellType,shaped,process.platform,normalizedTool==="shell"?getObservedHostShell():void 0),wrapperDeclaredHere=declaresWindowsWrapperLoose(command),windowsAuthoritative=wrapperDeclaredHere||normalizedTool!=="bash",detect=(c)=>{let posix15=detectPosixWrites(c);if(windowsShell===null)return posix15;return mergeWriteAnalyses(posix15,detectWindowsWrites(c,windowsShell),windowsAuthoritative,wrapperDeclaredHere)},suppressParseError=(c)=>enforce&&isPowerShellReadOnlyPipeline(c),primaryAnalysis=detect(command);if(enforce&&primaryAnalysis.parseError&&!suppressParseError(command))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(`
|
|
1203
|
+
`):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(didUnwrap){let regained=primaryAnalysis.writes.filter((w)=>!(w.category==="interpreter_eval"&&w.path===null&&!w.operator.endsWith("[eval stdin]")));if(regained.length>0)analysis={...analysis,writes:[...analysis.writes,...regained],hasWrites:analysis.hasWrites||regained.length>0};if(analysis.parseError&&!primaryAnalysis.parseError)analysis=primaryAnalysis}if(enforce&&analysis.parseError&&!suppressParseError(analysis===primaryAnalysis?command:detectionCommand))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,!enforce),shellWriteAgent=swarmState.activeAgent.get(sessionID);if(!shellWriteAgent){if(enforce)throw Error(`WRITE BLOCKED: No active agent registered for session "${sessionID}". Agent identity must be established (e.g. via a chat message or Task delegation) before shell writes can be authorized.`);return}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(enforce&&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),enforceWriteAuthorization=(target,opts)=>{if(enforce&&noScopeLenient&&universalDenyPrefixes.length>0){for(let prefix of universalDenyPrefixes)if(matchesAuthorityDenyPrefix(target,prefix,shellDirectory))throw new ShellWriteBlockedError(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${target}" (via shell). Reason: Path is under universal deny prefix "${prefix}"`,{writeTarget:target,writeOperator:opts?.writeOperator})}if(noScopeLenient)return"lenient";let authorityCheck=checkFileAuthorityWithRules(shellWriteAgent,target,shellDirectory,precomputedAuthorityRules,{declaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(enforce&&!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"protected_state_mutation",paths:[target]}):void 0;throw new ShellWriteBlockedError(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${target}" (via shell). Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`,{writeTarget:target,writeOperator:opts?.writeOperator})}if(enforce&&declaredScope&&declaredScope.length>0&&!isInDeclaredScope(target,declaredScope,shellDirectory)&&!(opts?.exemptEmptyDirectoryRemoval===!0&&isPosixRmdirExecutor(normalizedTool,windowsShell,detectionCommand)&&isEmptyDirectoryRemovalWithinWorkspace(target,shellDirectory))){let safeTarget=sanitizeDiagnosticText(target,320),scopeSummary=declaredScope.slice(0,10).map((entry)=>sanitizeDiagnosticText(entry,160)).join(", "),omitted=Math.max(0,declaredScope.length-10);throw new ShellWriteBlockedError(`WRITE BLOCKED [shell-write-scope]: 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.`,{writeTarget:target,writeOperator:opts?.writeOperator})}return"enforced"};for(let write of resolvedWrites){if(write.resolvedPath===null){if(write.original.category==="here_doc"&&write.original.path===null)continue;if(enforce&&write.original.category==="interpreter_eval"){if(write.original.capability===!0&&(isImmutableNonWriter||declaredScope!==null&&declaredScope!==void 0&&declaredScope.length>0)){enforceWriteAuthorization(write.evalDirectory??shellDirectory,{writeOperator:write.original.operator});continue}throw new ShellWriteBlockedError(`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.`,{writeOperator:write.original.operator})}if(enforce)throw new ShellWriteBlockedError(`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.`,{writeOperator:write.original.operator});continue}if(enforceWriteAuthorization(write.resolvedPath,{exemptEmptyDirectoryRemoval:write.original.emptyDirectoryRemoval===!0,writeOperator:write.original.operator})==="lenient")continue;if(isCoder&&session?.currentTaskId){let writeBinding=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path103.relative(path103.resolve(shellDirectory),path103.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=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(binding)rememberScopeLeaseCandidate?.({callID,sessionID,tool:tool3,directory:shellDirectory,binding,targets:resolvedWrites.flatMap((write)=>write.resolvedPath===null?[]:[path103.resolve(shellDirectory,write.resolvedPath)]),args:args2})}}function isSandboxWrapperInvocation(raw){let head=raw.replace(/^\s*(?:(?:exec|(?:\/(?:usr\/)?bin\/)?env)(?:\s+(?:-\S+|[A-Za-z_]\w*=\S*))*\s+)*/,"");return/^(?:\/(?:usr\/(?:local\/)?)?bin\/)?bwrap(?:\s|$)/.test(head)}async function applySandboxExecution(sessionID,callID,tool3,args2,agent,command,auditEnabled){if(tool3!=="bash"&&tool3!=="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:tool3,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:tool3,command,executorMechanism:executor?.mechanism??"none",skipReason:"executor not available"},{directory:effectiveDirectory,enabled:auditEnabled});return}let declaredPaths=resolveDeclaredScope(sessionID,!enforcePolicy);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])];if(normalizeSandboxMechanism2(executor.mechanism)==="bubblewrap"&&isSandboxWrapperInvocation(rawCommand))throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"command already invokes the sandbox wrapper"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: the command already invokes bwrap. Every bash call is sandboxed by the harness (${executor.mechanism}); a nested wrapper fails with "No permissions to create new namespace". Re-issue the plain command without the bwrap prefix.`);let workspaceRoot=sessionWorkspaceDirectory(sessionID),readonlyWorkspaceRoot=workspaceRoot;try{readonlyWorkspaceRoot=fs63.realpathSync(workspaceRoot)}catch{}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,readonly_roots:[readonlyWorkspaceRoot]});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:tool3,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:tool3,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,tool3,args2){if(!swarmState.agentSessions.get(sessionID)?.delegationActive&&isArchitect(sessionID)){let coderDeleg=isAgentDelegation(tool3,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,tool3,args2){if(!isTaskToolId(tool3))return;let loopArgs=args2,loopResult=detectLoop(sessionID,tool3,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(`
|
|
1204
|
+
`),timestamp:Date.now()}}}}function handleTestSuiteBlocking(tool3,args2){if(tool3!=="bash"&&tool3!=="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(tool3,args2){if(tool3!=="apply_patch"&&tool3!=="swarm_apply_patch"&&tool3!=="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,tool3,args2){let toolArgs=args2,targetPath=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(tool3==="apply_patch"||tool3==="swarm_apply_patch"||tool3==="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=path103.resolve(effectiveDirectory,targetPath).toLowerCase(),planMdPath=path103.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path103.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=path103.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&&(tool3==="apply_patch"||tool3==="swarm_apply_patch"||tool3==="patch"))for(let p of extractPatchTargetPaths(tool3,args2)){let resolvedP=path103.resolve(effectiveDirectory,p),planMdPath=path103.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path103.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase(),specStalenessPath=path103.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:tool3,sessionID,targetPath:p,writeCount:session.architectWriteCount});break}}if(typeof targetPath==="string"&&targetPath.length>0&&isOutsideSwarmDir(targetPath,effectiveDirectory)&&isSourceCodePath(path103.relative(effectiveDirectory,path103.resolve(effectiveDirectory,targetPath)))){let session=swarmState.agentSessions.get(sessionID);if(session){if(session.architectWriteCount++,warn("Architect direct code edit detected",{tool:tool3,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:tool3,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,tool3,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 hash4=hashArgs(args2);if(window2.recentToolCalls.push({tool:tool3,argsHash:hash4,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)=>{if(enforcePolicy)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";if(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),enforcePolicy)handleLoopDetection(input.sessionID,input.tool,output.args);if(enforcePolicy&&isSwarmOwnedSession(input.sessionID))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});if(enforcePolicy)handleInterpreterGating(input.sessionID,input.tool);try{if(enforcePolicy)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,{enforce:enforcePolicy})}catch(err){let toolArgs=output.args,declaredScope=resolveDeclaredScope(input.sessionID,!0),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)),structuredWrite=err instanceof ShellWriteBlockedError?err:void 0,targetPath=(()=>{let p=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(typeof p==="string"&&p.length>0)return p;if(structuredWrite?.writeTarget)return structuredWrite.writeTarget;let rawMessage=err instanceof Error?err.message:String(err),extracted=/shell write target "([^"]+)"/.exec(rawMessage)??/is not authorised to write "([^"]+)"/.exec(rawMessage)??/(?: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",...structuredWrite?.writeOperator?{operator:structuredWrite.writeOperator}:{}},{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),enforcePolicy)await applySandboxExecution(input.sessionID,input.callID,input.tool,output.args,agentNameForSandbox,rawShellCommand,shellAuditEnabled);if(enforcePolicy)enforceSpecDriftGate(effectiveDirectory,input.tool);if(enforcePolicy&&isArchitect(input.sessionID)&&isWriteTool(input.tool))handlePlanAndScopeProtection(input.sessionID,input.tool,output.args);if(input.tool==="apply_patch"||input.tool==="swarm_apply_patch"||input.tool==="patch"){let patchArgs=output.args,structuralPatch=typeof patchArgs?.input==="string"?patchArgs.input:typeof patchArgs?.patch==="string"?patchArgs.patch:typeof patchArgs?.diff==="string"?patchArgs.diff:void 0;if(structuralPatch===void 0)for(let key2 of PATCH_PAYLOAD_KEYS){let value=patchArgs?.[key2];if(typeof value==="string"){structuralPatch=value;break}}if(structuralPatch===void 0&&Array.isArray(patchArgs?.cmd)&&typeof patchArgs.cmd[1]==="string")structuralPatch=patchArgs.cmd[1];if(structuralPatch===void 0&&typeof patchArgs?.cmd==="string")structuralPatch=patchArgs.cmd;if((structuralPatch??"").length>1e6)throw Error("WRITE BLOCKED: Patch payload exceeds 1 MB — authority cannot be verified for all modified paths. Split into smaller patches.")}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"){if(enforcePolicy)throw Error(`WRITE TARGET UNVERIFIABLE: ${resolution.reason}`)}else resolvedFileTargets=resolution.paths;let writeBinding=session?.currentTaskId&&isCoder?enforcePolicy?resolveActiveScopeBinding(input.sessionID):resolveActiveScopeBindingObserving(input.sessionID):null;if(writeBinding)rememberScopeLeaseCandidate?.({callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:writeDirectory,binding:writeBinding,targets:(resolvedFileTargets??[]).map((target)=>path103.resolve(writeDirectory,target)),args:output.args})}if(isWriteTool(input.tool))for(let targetPath of resolvedFileTargets??[]){let agentName=swarmState.activeAgent.get(input.sessionID);if(!agentName){if(!enforcePolicy)continue;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){if(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,!enforcePolicy);return scope!=null&&scope.length>0?scope.join(", "):""})()},{directory:effectiveDirectory,enabled:shellAuditEnabled}),enforcePolicy)throw Error(lstatBlock)}let writeBinding=session?.currentTaskId&&isCoder?enforcePolicy?resolveActiveScopeBinding(input.sessionID):resolveActiveScopeBindingObserving(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;if(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}),!enforcePolicy)continue;throw 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=path103.relative(path103.resolve(writeDirectory),path103.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,writeDirectory)}if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path103.relative(path103.resolve(writeDirectory),path103.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);if(enforcePolicy)await checkGateLimits({sessionID:input.sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount})}if(enforcePolicy){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,ShellWriteBlockedError,RMDIR_EXEMPTION_CONTROL_STATE;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_protected_path_policy();init_state();init_telemetry();init_utils();init_core3();init_loop_detector();init_normalize_tool_name();init_shell_executor_context();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"}};ShellWriteBlockedError=class ShellWriteBlockedError extends Error{writeTarget;writeOperator;constructor(message,details={}){super(message);if(this.name="ShellWriteBlockedError",typeof details.writeTarget==="string"&&details.writeTarget.length>0)this.writeTarget=details.writeTarget;if(typeof details.writeOperator==="string"&&details.writeOperator.length>0)this.writeOperator=details.writeOperator}};RMDIR_EXEMPTION_CONTROL_STATE=[".git",".swarm"]});import*as fsSync11 from"node:fs";import*as path104 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(error93){let message=error93 instanceof Error?error93.message:String(error93),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 state2 of states){if(!isStrictTaskId(state2.taskId))continue;if(state2.state==="DISPATCHED"||state2.state==="PREPARED"){if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state2.taskId)).state==="coder_delegated")inFlightAtCoderDelegated.add(state2.taskId);continue}if(state2.state!=="COMMITTED")continue;if(state2.accepted!==!0)continue;if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state2.taskId)).state==="coder_delegated")eligible.push(state2)}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(error93){return warn("Durable gate attribution fallback failed",{error:String(error93)}),null}}function enforceSpecDriftGate(directory,toolName){if(!directory)return;if(!SPEC_DRIFT_BLOCKED_TOOLS.has(toolName))return;let stalePath=path104.join(directory,".swarm","spec-staleness.json");if(fsSync11.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?`
|
|
1205
1205
|
Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:"";message+=`
|
|
1206
1206
|
|
|
1207
1207
|
--- spec diff (recorded vs current) ---`+sectionSummary+`
|
|
@@ -1237,10 +1237,10 @@ ${AUTO_INJECTED_ACCEPTANCE_REQUIREMENT}
|
|
|
1237
1237
|
`).slice(0,3).join(`
|
|
1238
1238
|
`),headingMatch=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/im.exec(nextLines);if(headingMatch)return headingMatch[1].toUpperCase()}let lines=text.split(`
|
|
1239
1239
|
`),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(`
|
|
1240
|
-
`).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;return approvedSnapshotCoversPlan(approved,plan)}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(!approvedSnapshotCoversPlan(approved,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(error93){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error93 instanceof Error?error93.message:String(error93)}`),{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((resolve55)=>setTimeout(resolve55,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,void 0,directory);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=path105.join(directory,".swarm","plan.json");if(fs64.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}}async function forceRecordRetrySoundingBoardApproval(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("APPROVE_RETRY_SOUNDING_BOARD_ARCHITECT_REQUIRED: approve_retry_sounding_board requires an active architect session. The coder retry circuit-breaker escape hatch is architect-only; a coder/reviewer cannot self-unblock.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('APPROVE_RETRY_UNKNOWN_TASK: approve_retry_sounding_board requires the exact plan task id (e.g. "2.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path105.join(directory,".swarm","plan.json");if(fs64.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 retry sounding-board approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a retry "+"sounding-board approval without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))).has(taskId))throw Error(`APPROVE_RETRY_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to record evidence for a foreign task id.`);let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence);if(!evidence||!workflow.authoritative)throw Error(`APPROVE_RETRY_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no retry state to recover.`);let prior;try{prior=readCoderRetryEscalations(directory,taskId,workflow.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("APPROVE_RETRY_AUDIT_INDEX_UNREADABLE: the retry audit authority index is unreadable, so the prior sounding_board_consultation cannot be verified. Repair the events store (see /swarm doctor) and retry.");throw error93}if(!prior.has("sounding_board_consultation"))throw Error(`APPROVE_RETRY_CONSULTATION_REQUIRED: task ${taskId} has no durable sounding_board_consultation escalation for retry epoch ${workflow.retryEpoch}. `+"Dispatch critic_sounding_board first — this tool records an obtained APPROVED verdict, it cannot substitute for the consultation.");let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,recordedAt=new Date().toISOString(),transitionId=`retry-sb-manual:${sessionID}:epoch${workflow.retryEpoch}`;await recordGateEvidence2(directory,taskId,"critic_sounding_board",sessionID,!1,{transitionId,expectedGeneration:workflow.generation});let auditEventRecorded=!0;try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:recordedAt,taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,rejectionCount:workflow.retryCount,rejectionHistory:[...workflow.retryHistory],phase:Number(taskId.split(".")[0])||0,action:"sounding_board_manual_approval",...sanitizedReason?{reason:sanitizedReason}:{}},{dedupeOnAuthorityKey:!0})}catch(err){auditEventRecorded=!1,warn(`[delegation-gate] sounding_board_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,recordedAt,auditEventRecorded}}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}async function hasExplicitEmptyPlanScope(directory,taskId){let planPath=path105.join(directory,".swarm","plan.json"),handle;try{handle=await fs64.promises.open(planPath,"r");let stat11=await handle.stat();if(!stat11.isFile()||stat11.size>MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES)return!1;let bytes=Buffer.alloc(stat11.size),offset=0;while(offset<bytes.length){let result=await handle.read(bytes,offset,bytes.length-offset,offset);if(result.bytesRead===0)return!1;offset+=result.bytesRead}let parsed=JSON.parse(bytes.toString("utf8"));if(!Array.isArray(parsed.phases))return!1;for(let phase of parsed.phases){if(!phase||typeof phase!=="object")continue;let tasks=phase.tasks;if(!Array.isArray(tasks))continue;for(let task of tasks){if(!task||typeof task!=="object")continue;let record3=task;if(record3.id===taskId&&Object.hasOwn(record3,"files_touched")&&Array.isArray(record3.files_touched)&&record3.files_touched.length===0)return!0}}}catch{return!1}finally{await handle?.close().catch(()=>{return})}return!1}async function settleRejectedEmptyPlanScope(directory,input,taskId,expectedGeneration){let baseline=await captureWorkspaceSnapshotAsync(directory);if(baseline.gitHead===null||!Array.isArray(baseline.changedFiles)||baseline.changedFiles.length!==0)return null;let transitionId=`coder-preflight:${input.callID}`;try{await beginCoderSettlement({directory,taskId,transitionId,actor:input.sessionID,expectedGeneration,context:{baseline,declaredFiles:[],workflowGeneration:expectedGeneration}});let observedFiles=await changedFilesSinceSnapshotAsync(directory,baseline);if(observedFiles===null)throw Error("CODER_SETTLEMENT_BASELINE_UNAVAILABLE: empty-scope preflight could not prove a clean post-baseline workspace.");return await settleCoderDispatch({directory,taskId,transitionId,accepted:!1,testEngineerExempt:!1,observedFiles})}catch(error93){try{await abortCoderSettlement({directory,taskId,transitionId,reason:`empty-scope preflight settlement failed: ${error93 instanceof Error?error93.message:String(error93)}`})}catch(abortError){criticalWarn(`[delegation-gate] failed to abort empty-scope preflight settlement for ${taskId}: ${abortError instanceof Error?abortError.message:String(abortError)}`)}throw error93}}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,errors5=[],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")errors5.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")errors5.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:errors5}}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(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error93}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error93}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 the user authorizes repair, the architect calls update_task_status on this task with status "in_progress", force true, expected_state set to the task's current workflow state, expected_generation ${input.generation}, target_state "idle", a reason, and a transition_id — the audited repair reopens the task and clears the retry circuit (issue #3389). The task's plan status must already be in_progress; a task still pending in the plan takes one ordinary in_progress status update first.`);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 isExplicitTaskEvidenceAgent(targetAgent){return EXPLICIT_TASK_EVIDENCE_AGENTS.has(stripKnownSwarmPrefix(targetAgent))}function evidenceTaskResolutionOptions(targetAgent,allowSessionFallback){if(isExplicitTaskEvidenceAgent(targetAgent))return{policy:"attribution",allowSessionFallback:!1};if(allowSessionFallback===!1)return{allowSessionFallback:!1};return}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&&fs64.existsSync(path105.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)try{if(isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0}catch{return!1}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(_internals97.isEpicOpenForProject(directory))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 currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan),fallbackReason=null;if(pendingTaskIds.length<2)fallbackReason="fewer than two pending tasks in the active phase — nothing to parallelize";else try{let verdict=computeParallelVerdict(directory,pendingTaskIds,{plan});if(verdict.verdict==="all_disjoint");else if(verdict.verdict==="unknown_scopes"){let shown=verdict.unknownScopeTasks.slice(0,6).join(", "),more=verdict.unknownScopeTasks.length>6?` (and ${verdict.unknownScopeTasks.length-6} more)`:"";fallbackReason=`no live declared scope for task${verdict.unknownScopeTasks.length===1?"":"s"}: ${shown}${more} — call declare_scope for each pending task, then retry`}else{let conflictPair=verdict.pairs.find((pair)=>pair.verdict==="conflict"),evidence=(conflictPair?.evidence??[]).slice(0,3).join("; ");fallbackReason=`declared scopes overlap: tasks ${conflictPair?.a??"?"} and ${conflictPair?.b??"?"} conflict (${evidence||"shared paths"})`}}catch{fallbackReason="verdict computation failed (fail-safe serial per v8 contract)"}if(fallbackReason!==null)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; SERIAL fallback active (v8 automatic safety) — exact reason: ${fallbackReason}. 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 state2=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state2))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 collectPendingTaskIdsForActivePhase(plan){let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);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,{plan}).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=path105.resolve(directory),planPath=path105.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path105.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path105.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs64.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((issue3)=>issue3.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 policy=options.policy??"plan",planContextOptions=policy==="attribution"&&planTaskIdContext?.status==="over_limit"?{}:planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{},resolutionOptions={policy,...planContextOptions,standaloneTaskMarkerOnly:policy==="attribution"},resolution=resolveTaskId(args2,resolutionOptions);if(resolution.status==="resolved"){let resolvedTaskId=resolution.taskId;if(policy==="attribution"&&!isStrictTaskId(resolvedTaskId)){let markerOnlyArgs={...args2};for(let field of EXPLICIT_TASK_ID_FIELDS)delete markerOnlyArgs[field];let markerResolution=resolveTaskId(markerOnlyArgs,resolutionOptions);if(markerResolution.status!=="resolved"||!isStrictTaskId(markerResolution.taskId))return null;resolvedTaskId=markerResolution.taskId}if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolvedTaskId)))return null;return resolvedTaskId}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 sanitizeDenialText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}function isRepairableStageBView(existingView,durableEligibleState){return existingView===void 0||existingView==="rework_required"||compareTaskWorkflowStateRank(durableEligibleState,existingView)>0}function warnStageBSettlementDropped(session,params){let{taskId,agent,reasonClass,drops}=params,restartNote=reasonClass==="unbound"?" The dispatch-generation binding is process-local and was lost — a plugin reload or host restart between dispatch and settlement is the usual cause; no durable binding was found for this dispatch, so it cannot be reconstructed.":"",dedupeToken=`[stageb-settlement-drop:${reasonClass}:${taskId}]`,safeCallID=sanitizeDenialText(params.callID),safeDetail=sanitizeDenialText(params.detail),message=reasonClass==="rejection_persist_failed"?`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}. The rejection verdict was not persisted (fail-closed); the task stays at its current state. Remedy: inspect .swarm/ evidence storage for this task and retry the rejection transition (the verdict need not be re-earned).`:`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}.${restartNote} The clean verdict was not recorded (fail-closed); the task stays at its current state. Remedy: re-dispatch the ${agent} gate for task ${taskId}.`;pushAdvisory(session,message,{dedupeKey:dedupeToken});let tasks=drops.get(reasonClass)??[];tasks.push(taskId),drops.set(reasonClass,tasks)}function flushStageBSettlementDropWarnings(drops){for(let[reasonClass,taskIds]of drops){if(taskIds.length===0)continue;let listed=taskIds.slice(0,10).join(", "),overflow=taskIds.length>10?` (+${taskIds.length-10} more)`:"";criticalWarn(`[delegation-gate] Stage B settlement dropped for task(s) ${listed}${overflow}: ${STAGE_B_SETTLEMENT_DROP_REASONS[reasonClass]}. See session advisories for per-task remedies.`)}drops.clear()}function createDelegationGateHook(config3,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config3.hooks?.delegation_gate!==!1,delegationMaxChars=config3.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config3.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,reviewRouteByTaskKey=new Map,stageBRouteSlotByCallID=new Map,reviewRouteTaskKey=(sessionId,taskId)=>`${sessionId}\x00${taskId}`,MAX_REVIEW_ROUTE_RECORDS=128,rememberReviewRoute=(key2,route)=>{reviewRouteByTaskKey.delete(key2),reviewRouteByTaskKey.set(key2,route);while(reviewRouteByTaskKey.size>MAX_REVIEW_ROUTE_RECORDS){let oldest=reviewRouteByTaskKey.keys().next().value;if(!oldest)break;reviewRouteByTaskKey.delete(oldest)}},clearReviewRouteStateForSession=(sessionId)=>{let prefix=`${sessionId}\x00`;for(let key2 of reviewRouteByTaskKey.keys())if(key2.startsWith(prefix))reviewRouteByTaskKey.delete(key2)},bindReviewRouteSlots=(callID,sessionId,role,taskIds)=>{let bindings=new Map,session=swarmState.agentSessions.get(sessionId);for(let taskId of taskIds){let route=reviewRouteByTaskKey.get(reviewRouteTaskKey(sessionId,taskId));if(!route||route.kind!=="review_route_receipt")continue;let identities=role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities;if(slots.length===0||identities.length!==slots.length)continue;let prior=stageBRouteSlotByCallID.get(callID)?.get(taskId),settled=session?getStageBRouteEvidence(session,taskId).find((entry)=>entry.role===role&&entry.sessionId===sessionId&&entry.taskId===taskId&&entry.callId===callID&&entry.generation===stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)):void 0,existing=prior??settled,occupiedSlots=new Set;for(let entry of session?getStageBRouteEvidence(session,taskId):[])if(entry.role===role&&entry.slotId)occupiedSlots.add(entry.slotId);for(let[otherCallId,otherBindings]of stageBRouteSlotByCallID){if(otherCallId===callID)continue;let other=otherBindings.get(taskId);if(other?.role===role&&other.sessionId===sessionId&&other.taskId===taskId&&other.slotId)occupiedSlots.add(other.slotId)}let slotIndex=existing?slots.indexOf(existing.slotId??""):slots.findIndex((slotId2)=>!occupiedSlots.has(slotId2));if(slotIndex<0||slotIndex>=slots.length)continue;let slotId=slots[slotIndex];bindings.set(taskId,{role,identity:identities[slotIndex],sessionId,taskId,slotId,callId:callID,...existing?.childSessionId?{childSessionId:existing.childSessionId}:{},generation:stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)})}if(bindings.size>0)stageBRouteSlotByCallID.set(callID,bindings)},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)=>{setDispatchParent(input.childSessionID,input.parentSessionID);let bindRouteChildSession=()=>{let routeBindings=stageBRouteSlotByCallID.get(input.callID);if(!routeBindings)return;for(let binding of routeBindings.values())binding.childSessionId=input.childSessionID},result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED"){bindRouteChildSession(),log("scope claim: no pending generation for dispatch",{parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});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],bindRouteChildSession()},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;clearReviewRouteStateForSession(sessionID);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,sessionID,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);let durableStart=Date.now(),persisted=_internals97.recordStageBDispatchBindings(directory,{sessionID:sessionID??"",callID,bindings:[...generations.entries()].map(([taskId,generation])=>({taskId,generation}))}),durableElapsed=Date.now()-durableStart;if(!persisted)criticalWarn(`[delegation-gate] Stage B durable binding write FAILED for call ${callID} — restart recovery for this dispatch is unavailable until re-dispatch (non-fatal; in-memory fencing remains active)`);else if(durableElapsed>50)log(`[delegation-gate] Stage B durable binding write for call ${callID}: persisted=true elapsedMs=${durableElapsed}`)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals97.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=(record3)=>{let callID=record3.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),deleteStageBDispatchBindings(directory,record3.parentSessionId,callID),stageBRouteSlotByCallID.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"){assertTaskIdNotForeignLaneSession(preflightArgs);let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent),registeredMode=registeredAgents?Object.entries(registeredAgents).find(([name])=>name.toLowerCase()===exactPreflightAgent.trim().toLowerCase())?.[1]:void 0,isCriticDispatch=preflightAgent.startsWith("critic"),isRegistryMatchedDispatch=registeredMode!==void 0,isPrimaryDispatch=registeredMode?.mode==="primary";if((isCriticDispatch||isRegistryMatchedDispatch)&&!isPrimaryDispatch){let denialError;if(isCriticDispatch){let legacyCriticModel=config3.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config3,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),denialError=`PLAN_CRITIC_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(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 "${sanitizeDenialText(exactPreflightAgent)}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error93}}}else{let overrideEntry=resolveEffectiveAgentOverride(config3,exactPreflightAgent),finalModel=overrideEntry&&typeof overrideEntry.model==="string"&&overrideEntry.model.trim()===""?"":(registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent):void 0)??resolveRegisteredAgentModel(config3,exactPreflightAgent);if(finalModel===void 0||finalModel.trim()==="")telemetry.modelUnresolved(preflightAgent,"(no final selection)","swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_MISSING_SELECTION: the ${sanitizeDenialText(exactPreflightAgent)} agent is registered but has no final model selection (blank model override or a stale swarm registry entry) — dispatching it cannot succeed. `+"Fix agents.<role>.model in opencode-swarm.json (the matching swarm override wins over the top-level entry) or correct the swarm configuration, then retry.";else try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(finalModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,finalModel,"swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(finalModel)}" does not resolve against the provider catalog — dispatching this role will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json (the matching swarm override wins over top-level agents.<role>.model). fallback_models entries only serve transient runtime failures; configure a resolvable primary model for this role."}catch{}}if(denialError!==void 0){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),Error(denialError)}}}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,void 0,directory),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,void 0,directory),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(error93){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),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"||targetAgent==="test_engineer"){let routedTaskId=null,routeDispatchStarted=!1;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):[],routeTaskId=reviewTaskId??`unresolved-${input.callID}`;routedTaskId=routeTaskId,markStageBRouteRequired(reviewSession,routeTaskId);let pendingRoute=buildReviewRoutePending({sessionId:input.sessionID,taskId:routeTaskId});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:pendingRoute}),routeDispatchStarted=!0,rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),pendingRoute),changedFiles.length===0){let routerError=buildReviewRouteRouterError({code:"NO_CHANGED_FILES",sessionId:input.sessionID,taskId:routeTaskId});await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routerError)}else{let routing=await routeReviewForChanges(directory,changedFiles),routeReceipt=buildReviewRouteReceipt({sessionId:input.sessionID,taskId:routeTaskId,complexity:routing.depth,semanticRisk:routing.reason,requiredReviewers:Array.from({length:routing.reviewerCount},(_,index)=>`${routeTaskId}:reviewer:${index+1}`),requiredTestEngineers:Array.from({length:routing.testEngineerCount},(_,index)=>`${routeTaskId}:test_engineer:${index+1}`)});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routeReceipt}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routeReceipt),shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);if(!routeDispatchStarted){warn(`[delegation-gate] review route dispatch could not establish its pending receipt: ${detail}`);return}let routerError=buildReviewRouteRouterError({code:/unavailable|timed out|timeout|not found/i.test(detail)?"ROUTER_UNAVAILABLE":"ROUTER_FAILED",sessionId:input.sessionID,taskId:routedTaskId??`unresolved-${input.callID}`,detail});try{if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),routedTaskId)rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routedTaskId),routerError)}catch(persistError){warn(`[delegation-gate] review route receipt was not recorded: ${detail}; router-error persistence failed: ${persistError instanceof Error?persistError.message:String(persistError)}`)}}}if(targetAgent==="coder"||targetAgent==="reviewer"){let joinAcceptancePromptText=()=>ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
|
|
1240
|
+
`).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;return approvedSnapshotCoversPlan(approved,plan)}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(!approvedSnapshotCoversPlan(approved,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(error93){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error93 instanceof Error?error93.message:String(error93)}`),{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((resolve55)=>setTimeout(resolve55,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,void 0,directory);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=path105.join(directory,".swarm","plan.json");if(fs64.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}}async function forceRecordRetrySoundingBoardApproval(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("APPROVE_RETRY_SOUNDING_BOARD_ARCHITECT_REQUIRED: approve_retry_sounding_board requires an active architect session. The coder retry circuit-breaker escape hatch is architect-only; a coder/reviewer cannot self-unblock.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('APPROVE_RETRY_UNKNOWN_TASK: approve_retry_sounding_board requires the exact plan task id (e.g. "2.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path105.join(directory,".swarm","plan.json");if(fs64.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 retry sounding-board approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a retry "+"sounding-board approval without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))).has(taskId))throw Error(`APPROVE_RETRY_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to record evidence for a foreign task id.`);let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence);if(!evidence||!workflow.authoritative)throw Error(`APPROVE_RETRY_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no retry state to recover.`);let prior;try{prior=readCoderRetryEscalations(directory,taskId,workflow.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("APPROVE_RETRY_AUDIT_INDEX_UNREADABLE: the retry audit authority index is unreadable, so the prior sounding_board_consultation cannot be verified. Repair the events store (see /swarm doctor) and retry.");throw error93}if(!prior.has("sounding_board_consultation"))throw Error(`APPROVE_RETRY_CONSULTATION_REQUIRED: task ${taskId} has no durable sounding_board_consultation escalation for retry epoch ${workflow.retryEpoch}. `+"Dispatch critic_sounding_board first — this tool records an obtained APPROVED verdict, it cannot substitute for the consultation.");let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,recordedAt=new Date().toISOString(),transitionId=`retry-sb-manual:${sessionID}:epoch${workflow.retryEpoch}`;await recordGateEvidence2(directory,taskId,"critic_sounding_board",sessionID,!1,{transitionId,expectedGeneration:workflow.generation});let auditEventRecorded=!0;try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:recordedAt,taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,rejectionCount:workflow.retryCount,rejectionHistory:[...workflow.retryHistory],phase:Number(taskId.split(".")[0])||0,action:"sounding_board_manual_approval",...sanitizedReason?{reason:sanitizedReason}:{}},{dedupeOnAuthorityKey:!0})}catch(err){auditEventRecorded=!1,warn(`[delegation-gate] sounding_board_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,recordedAt,auditEventRecorded}}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}async function hasExplicitEmptyPlanScope(directory,taskId){let planPath=path105.join(directory,".swarm","plan.json"),handle;try{handle=await fs64.promises.open(planPath,"r");let stat11=await handle.stat();if(!stat11.isFile()||stat11.size>MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES)return!1;let bytes=Buffer.alloc(stat11.size),offset=0;while(offset<bytes.length){let result=await handle.read(bytes,offset,bytes.length-offset,offset);if(result.bytesRead===0)return!1;offset+=result.bytesRead}let parsed=JSON.parse(bytes.toString("utf8"));if(!Array.isArray(parsed.phases))return!1;for(let phase of parsed.phases){if(!phase||typeof phase!=="object")continue;let tasks=phase.tasks;if(!Array.isArray(tasks))continue;for(let task of tasks){if(!task||typeof task!=="object")continue;let record3=task;if(record3.id===taskId&&Object.hasOwn(record3,"files_touched")&&Array.isArray(record3.files_touched)&&record3.files_touched.length===0)return!0}}}catch{return!1}finally{await handle?.close().catch(()=>{return})}return!1}async function settleRejectedEmptyPlanScope(directory,input,taskId,expectedGeneration){let baseline=await captureWorkspaceSnapshotAsync(directory);if(baseline.gitHead===null||!Array.isArray(baseline.changedFiles)||baseline.changedFiles.length!==0)return null;let transitionId=`coder-preflight:${input.callID}`;try{await beginCoderSettlement({directory,taskId,transitionId,actor:input.sessionID,expectedGeneration,context:{baseline,declaredFiles:[],workflowGeneration:expectedGeneration}});let observedFiles=await changedFilesSinceSnapshotAsync(directory,baseline);if(observedFiles===null)throw Error("CODER_SETTLEMENT_BASELINE_UNAVAILABLE: empty-scope preflight could not prove a clean post-baseline workspace.");return await settleCoderDispatch({directory,taskId,transitionId,accepted:!1,testEngineerExempt:!1,observedFiles})}catch(error93){try{await abortCoderSettlement({directory,taskId,transitionId,reason:`empty-scope preflight settlement failed: ${error93 instanceof Error?error93.message:String(error93)}`})}catch(abortError){criticalWarn(`[delegation-gate] failed to abort empty-scope preflight settlement for ${taskId}: ${abortError instanceof Error?abortError.message:String(abortError)}`)}throw error93}}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,errors5=[],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")errors5.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")errors5.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:errors5}}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(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error93}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error93}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 the user authorizes repair, the architect calls update_task_status on this task with status "in_progress", force true, expected_state set to the task's current workflow state, expected_generation ${input.generation}, target_state "idle", a reason, and a transition_id — the audited repair reopens the task and clears the retry circuit (issue #3389). The task's plan status must already be in_progress; a task still pending in the plan takes one ordinary in_progress status update first.`);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 isExplicitTaskEvidenceAgent(targetAgent){return EXPLICIT_TASK_EVIDENCE_AGENTS.has(stripKnownSwarmPrefix(targetAgent))}function evidenceTaskResolutionOptions(targetAgent,allowSessionFallback){if(isExplicitTaskEvidenceAgent(targetAgent))return{policy:"attribution",allowSessionFallback:!1};if(allowSessionFallback===!1)return{allowSessionFallback:!1};return}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&&fs64.existsSync(path105.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)try{if(isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0}catch{return!1}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(_internals97.isEpicOpenForProject(directory))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 currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan),fallbackReason=null;if(pendingTaskIds.length<2)fallbackReason="fewer than two pending tasks in the active phase — nothing to parallelize";else try{let verdict=computeParallelVerdict(directory,pendingTaskIds,{plan});if(verdict.verdict==="all_disjoint");else if(verdict.verdict==="unknown_scopes"){let shown=verdict.unknownScopeTasks.slice(0,6).join(", "),more=verdict.unknownScopeTasks.length>6?` (and ${verdict.unknownScopeTasks.length-6} more)`:"";fallbackReason=`no live declared scope for task${verdict.unknownScopeTasks.length===1?"":"s"}: ${shown}${more} — call declare_scope for each pending task, then retry`}else{let conflictPair=verdict.pairs.find((pair)=>pair.verdict==="conflict"),evidence=(conflictPair?.evidence??[]).slice(0,3).join("; ");fallbackReason=`declared scopes overlap: tasks ${conflictPair?.a??"?"} and ${conflictPair?.b??"?"} conflict (${evidence||"shared paths"})`}}catch{fallbackReason="verdict computation failed (fail-safe serial per v8 contract)"}if(fallbackReason!==null)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; SERIAL fallback active (v8 automatic safety) — exact reason: ${fallbackReason}. 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 state2=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state2))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 collectPendingTaskIdsForActivePhase(plan){let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);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,{plan}).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=path105.resolve(directory),planPath=path105.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path105.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path105.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs64.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((issue3)=>issue3.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 policy=options.policy??"plan",planContextOptions=policy==="attribution"&&planTaskIdContext?.status==="over_limit"?{}:planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{},resolutionOptions={policy,...planContextOptions,standaloneTaskMarkerOnly:policy==="attribution"},resolution=resolveTaskId(args2,resolutionOptions);if(resolution.status==="resolved"){let resolvedTaskId=resolution.taskId;if(policy==="attribution"&&!isStrictTaskId(resolvedTaskId)){let markerOnlyArgs={...args2};for(let field of EXPLICIT_TASK_ID_FIELDS)delete markerOnlyArgs[field];let markerResolution=resolveTaskId(markerOnlyArgs,resolutionOptions);if(markerResolution.status!=="resolved"||!isStrictTaskId(markerResolution.taskId))return null;resolvedTaskId=markerResolution.taskId}if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolvedTaskId)))return null;return resolvedTaskId}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 sanitizeDenialText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}function isRepairableStageBView(existingView,durableEligibleState){return existingView===void 0||existingView==="rework_required"||compareTaskWorkflowStateRank(durableEligibleState,existingView)>0}function warnStageBSettlementDropped(session,params){let{taskId,agent,reasonClass,drops}=params,restartNote=reasonClass==="unbound"?" The dispatch-generation binding is process-local and was lost — a plugin reload or host restart between dispatch and settlement is the usual cause; no durable binding was found for this dispatch, so it cannot be reconstructed.":"",dedupeToken=`[stageb-settlement-drop:${reasonClass}:${taskId}]`,safeCallID=sanitizeDenialText(params.callID),safeDetail=sanitizeDenialText(params.detail),message=reasonClass==="rejection_persist_failed"?`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}. The rejection verdict was not persisted (fail-closed); the task stays at its current state. Remedy: inspect .swarm/ evidence storage for this task and retry the rejection transition (the verdict need not be re-earned).`:`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}.${restartNote} The clean verdict was not recorded (fail-closed); the task stays at its current state. Remedy: re-dispatch the ${agent} gate for task ${taskId}.`;pushAdvisory(session,message,{dedupeKey:dedupeToken});let tasks=drops.get(reasonClass)??[];tasks.push(taskId),drops.set(reasonClass,tasks)}function flushStageBSettlementDropWarnings(drops){for(let[reasonClass,taskIds]of drops){if(taskIds.length===0)continue;let listed=taskIds.slice(0,10).join(", "),overflow=taskIds.length>10?` (+${taskIds.length-10} more)`:"";criticalWarn(`[delegation-gate] Stage B settlement dropped for task(s) ${listed}${overflow}: ${STAGE_B_SETTLEMENT_DROP_REASONS[reasonClass]}. See session advisories for per-task remedies.`)}drops.clear()}async function readPrReviewReentryBindingContextSafe(directory,sessionId){try{return await readPrReviewReentryBindingContext(directory,sessionId)}catch(error93){return warn(`[delegation-gate] PR-review re-entry binding context unreadable; routing-bookkeeping fault degrades locally, dispatch-time gates still run (#3380): ${error93 instanceof Error?error93.message:String(error93)}`),null}}function createDelegationGateHook(config3,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config3.hooks?.delegation_gate!==!1,delegationMaxChars=config3.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config3.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,reviewRouteByTaskKey=new Map,stageBRouteSlotByCallID=new Map,reviewRouteTaskKey=(sessionId,taskId)=>`${sessionId}\x00${taskId}`,MAX_REVIEW_ROUTE_RECORDS=128,rememberReviewRoute=(key2,route)=>{reviewRouteByTaskKey.delete(key2),reviewRouteByTaskKey.set(key2,route);while(reviewRouteByTaskKey.size>MAX_REVIEW_ROUTE_RECORDS){let oldest=reviewRouteByTaskKey.keys().next().value;if(!oldest)break;reviewRouteByTaskKey.delete(oldest)}},clearReviewRouteStateForSession=(sessionId)=>{let prefix=`${sessionId}\x00`;for(let key2 of reviewRouteByTaskKey.keys())if(key2.startsWith(prefix))reviewRouteByTaskKey.delete(key2)},forgetReviewRoute=(key2)=>{reviewRouteByTaskKey.delete(key2)},routeInvalidatedByCallID=new Map,MAX_ROUTE_INVALIDATION_RECORDS=128,invalidateRouteForCall=(callID,key2)=>{let keys=routeInvalidatedByCallID.get(callID);if(!keys){keys=new Set,routeInvalidatedByCallID.set(callID,keys);while(routeInvalidatedByCallID.size>MAX_ROUTE_INVALIDATION_RECORDS){let oldest=routeInvalidatedByCallID.keys().next().value;if(!oldest)break;routeInvalidatedByCallID.delete(oldest)}}keys.add(key2)},isRouteInvalidatedForCall=(callID,key2)=>routeInvalidatedByCallID.get(callID)?.has(key2)??!1,consumeRouteInvalidationsForCall=(callID)=>{routeInvalidatedByCallID.delete(callID)},isRouteBlockedForSettlement=(callID,sessionId,taskId)=>{let invalidated=isRouteInvalidatedForCall(callID,reviewRouteTaskKey(sessionId,taskId));if(invalidated)consumeRouteInvalidationsForCall(callID);return invalidated};_internals97.routeInvalidationProbe=isRouteBlockedForSettlement;let bindReviewRouteSlots=(callID,sessionId,role,taskIds)=>{let bindings=new Map,session=swarmState.agentSessions.get(sessionId);for(let taskId of taskIds){let route=reviewRouteByTaskKey.get(reviewRouteTaskKey(sessionId,taskId));if(!route||route.kind!=="review_route_receipt")continue;let identities=role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities;if(slots.length===0||identities.length!==slots.length)continue;let prior=stageBRouteSlotByCallID.get(callID)?.get(taskId),settled=session?getStageBRouteEvidence(session,taskId).find((entry)=>entry.role===role&&entry.sessionId===sessionId&&entry.taskId===taskId&&entry.callId===callID&&entry.generation===stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)):void 0,existing=prior??settled,occupiedSlots=new Set;for(let entry of session?getStageBRouteEvidence(session,taskId):[])if(entry.role===role&&entry.slotId)occupiedSlots.add(entry.slotId);for(let[otherCallId,otherBindings]of stageBRouteSlotByCallID){if(otherCallId===callID)continue;let other=otherBindings.get(taskId);if(other?.role===role&&other.sessionId===sessionId&&other.taskId===taskId&&other.slotId)occupiedSlots.add(other.slotId)}let slotIndex=existing?slots.indexOf(existing.slotId??""):slots.findIndex((slotId2)=>!occupiedSlots.has(slotId2));if(slotIndex<0||slotIndex>=slots.length)continue;let slotId=slots[slotIndex];bindings.set(taskId,{role,identity:identities[slotIndex],sessionId,taskId,slotId,callId:callID,...existing?.childSessionId?{childSessionId:existing.childSessionId}:{},generation:stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)})}if(bindings.size>0)stageBRouteSlotByCallID.set(callID,bindings)},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)=>{setDispatchParent(input.childSessionID,input.parentSessionID);let bindRouteChildSession=()=>{let routeBindings=stageBRouteSlotByCallID.get(input.callID);if(!routeBindings)return;for(let binding of routeBindings.values())binding.childSessionId=input.childSessionID},result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED"){bindRouteChildSession(),log("scope claim: no pending generation for dispatch",{parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});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],bindRouteChildSession()},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;clearReviewRouteStateForSession(sessionID);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,sessionID,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`);if(stageBDispatchGenerationsByCallID.set(callID,generations),generations.size===0)return;let durableStart=Date.now(),persisted=_internals97.recordStageBDispatchBindings(directory,{sessionID:sessionID??"",callID,bindings:[...generations.entries()].map(([taskId,generation])=>({taskId,generation}))}),durableElapsed=Date.now()-durableStart;if(!persisted)criticalWarn(`[delegation-gate] Stage B durable binding write FAILED for call ${callID} — restart recovery for this dispatch is unavailable until re-dispatch (non-fatal; in-memory fencing remains active)`);else if(durableElapsed>50)log(`[delegation-gate] Stage B durable binding write for call ${callID}: persisted=true elapsedMs=${durableElapsed}`)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals97.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=(record3)=>{let callID=record3.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),deleteStageBDispatchBindings(directory,record3.parentSessionId,callID),stageBRouteSlotByCallID.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"){assertTaskIdNotForeignLaneSession(preflightArgs);let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent),registeredMode=registeredAgents?Object.entries(registeredAgents).find(([name])=>name.toLowerCase()===exactPreflightAgent.trim().toLowerCase())?.[1]:void 0,isCriticDispatch=preflightAgent.startsWith("critic"),isRegistryMatchedDispatch=registeredMode!==void 0,isPrimaryDispatch=registeredMode?.mode==="primary";if((isCriticDispatch||isRegistryMatchedDispatch)&&!isPrimaryDispatch){let denialError;if(isCriticDispatch){let legacyCriticModel=config3.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config3,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),denialError=`PLAN_CRITIC_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(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 "${sanitizeDenialText(exactPreflightAgent)}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error93}}}else{let overrideEntry=resolveEffectiveAgentOverride(config3,exactPreflightAgent),finalModel=overrideEntry&&typeof overrideEntry.model==="string"&&overrideEntry.model.trim()===""?"":(registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent):void 0)??resolveRegisteredAgentModel(config3,exactPreflightAgent);if(finalModel===void 0||finalModel.trim()==="")telemetry.modelUnresolved(preflightAgent,"(no final selection)","swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_MISSING_SELECTION: the ${sanitizeDenialText(exactPreflightAgent)} agent is registered but has no final model selection (blank model override or a stale swarm registry entry) — dispatching it cannot succeed. `+"Fix agents.<role>.model in opencode-swarm.json (the matching swarm override wins over the top-level entry) or correct the swarm configuration, then retry.";else try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(finalModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,finalModel,"swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(finalModel)}" does not resolve against the provider catalog — dispatching this role will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json (the matching swarm override wins over top-level agents.<role>.model). fallback_models entries only serve transient runtime failures; configure a resolvable primary model for this role."}catch{}}if(denialError!==void 0){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),Error(denialError)}}}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,void 0,directory),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,void 0,directory),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(error93){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),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"||targetAgent==="test_engineer"){let routedTaskId=null,routeDispatchStarted=!1;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):[],routeTaskId=reviewTaskId??`unresolved-${input.callID}`;routedTaskId=routeTaskId,markStageBRouteRequired(reviewSession,routeTaskId);let pendingRoute=buildReviewRoutePending({sessionId:input.sessionID,taskId:routeTaskId});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:pendingRoute}),routeDispatchStarted=!0,rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),pendingRoute),changedFiles.length===0){let routerError=buildReviewRouteRouterError({code:"NO_CHANGED_FILES",sessionId:input.sessionID,taskId:routeTaskId});await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routerError)}else{let routing=await routeReviewForChanges(directory,changedFiles),routeReceipt=buildReviewRouteReceipt({sessionId:input.sessionID,taskId:routeTaskId,complexity:routing.depth,semanticRisk:routing.reason,requiredReviewers:Array.from({length:routing.reviewerCount},(_,index)=>`${routeTaskId}:reviewer:${index+1}`),requiredTestEngineers:Array.from({length:routing.testEngineerCount},(_,index)=>`${routeTaskId}:test_engineer:${index+1}`)});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routeReceipt}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routeReceipt),shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);if(!routeDispatchStarted){if(warn(`[delegation-gate] review route dispatch could not establish its pending receipt: ${detail}`),routedTaskId){let staleKey=reviewRouteTaskKey(input.sessionID,routedTaskId);forgetReviewRoute(staleKey),invalidateRouteForCall(input.callID,staleKey)}}else{let routerError=buildReviewRouteRouterError({code:/unavailable|timed out|timeout|not found/i.test(detail)?"ROUTER_UNAVAILABLE":"ROUTER_FAILED",sessionId:input.sessionID,taskId:routedTaskId??`unresolved-${input.callID}`,detail});try{if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),routedTaskId)rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routedTaskId),routerError)}catch(persistError){warn(`[delegation-gate] review route receipt was not recorded: ${detail}; router-error persistence failed: ${persistError instanceof Error?persistError.message:String(persistError)}`)}}}}if(targetAgent==="coder"||targetAgent==="reviewer"){let joinAcceptancePromptText=()=>ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
|
|
1241
1241
|
`),acceptanceCheck=validateCoderReviewerAcceptanceField(joinAcceptancePromptText());if(!acceptanceCheck.valid&&acceptanceCheck.reason&&config3.hooks?.auto_inject_acceptance){let injectionReason=acceptanceCheck.reason,originalFields={...args2},injectedField=injectDefaultAcceptance(args2,injectionReason);if(injectedField)if(acceptanceCheck=validateCoderReviewerAcceptanceField(joinAcceptancePromptText()),!acceptanceCheck.valid)args2[injectedField]=originalFields[injectedField];else{let notice=`ACCEPTANCE AUTO-INJECTED: the ${targetAgent} dispatch carried no usable ACCEPTANCE criteria (${injectionReason}), so hooks.auto_inject_acceptance wrote a generic default into ${injectedField}. State a task-specific ACCEPTANCE line in future dispatches (see ACCEPTANCE FIELD RESOLUTION).`;warn(`[delegation-gate] ${notice}`);let noticeSession=swarmState.agentSessions.get(input.sessionID);if(noticeSession)pushAdvisory(noticeSession,notice)}}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 _internals97.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 fs64.promises.readFile(path105.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(`
|
|
1242
|
-
`);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,void 0,directory),activePrReviewBinding=isPrReviewReentryAgent?await
|
|
1243
|
-
`);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,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,null),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED",standalonePrReviewReentry:!0}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());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,config3.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")){if(generations.set(taskId,workflow.generation),isRepairableStageBView(stageBSession.taskWorkflowStates.get(taskId),workflow.state))stageBSession.taskWorkflowStates.set(taskId,workflow.state),updateTaskWorkflowCache(stageBSession,taskId,workflow);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,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}let stageARemediation=workflow.state==="rework_required"?"Remediation: if the Stage B verdict did not require a code change, call recover_rework_task for task "+taskId+" (architect-only, audited; requires green secretscan AND sast_scan evidence newer than the verdict — normally from a fresh pre_check_batch run; unavailable when SAST is disabled), then re-dispatch. "+"Otherwise delegate the coder to repair the code, re-run pre_check_batch, and re-dispatch once stage_a_passed has fired.":`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.`;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. `+stageARemediation+(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,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID,void 0,directory);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)&&await turboMayBypassTask(directory,preflightTaskId)))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(error93){if(preflightTaskId){let transitionId=`coder-preflight:${input.callID}`,explicitEmptyPlanScope=error93 instanceof Error&&error93.message.includes("coder delegation has no complete, valid, non-empty scope.")&&!extractTaskFileDirectives(args2).present&&await hasExplicitEmptyPlanScope(directory,preflightTaskId),settled=null;if(explicitEmptyPlanScope&&preflightWorkflow.generation===0)try{settled=await settleRejectedEmptyPlanScope(directory,input,preflightTaskId,preflightWorkflow.generation)}catch(settlementError){criticalWarn(`[delegation-gate] empty-scope preflight settlement failed for ${preflightTaskId}: ${settlementError instanceof Error?settlementError.message:String(settlementError)}`)}let failedWorkflow=getTaskWorkflowSnapshot2(settled?.evidence??await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId}));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 error93}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 _internals97.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error93){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state2])=>state2==="coder_delegated").map(([taskId])=>taskId),claim=await _internals97.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"){if(_internals97.epicSentinelExists(directory)){let conflict=_internals97.resolveEpicPrFeedbackConflict(directory,preparedScope.declaredFiles);if(conflict)throw Error(`${conflict.code}: ${conflict.message}`)}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(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}return}let plan=preparedScope.plan,epicPolicy=_internals97.epicSentinelExists(directory)?_internals97.resolveEpicDispatchPolicy(directory,plan,incomingCoderTaskId,preparedScope.declaredFiles):null;if(epicPolicy?.kind==="reject")throw Error(`${epicPolicy.code}: ${epicPolicy.message}`);let epicWave=epicPolicy?.kind==="allow"?epicPolicy:null,profile=plan.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=epicWave?epicWave.maxConcurrent:session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=epicWave===null&&scopeVerdictAllowsParallel(directory,plan),parallelWorktreeIsolationActive=epicWave===null&¶llelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),epicIsolationRequired=epicWave?.isolate===!0,standardWorktreeIsolationActive=epicWave?epicWave.isolate:parallelWorktreeIsolationActive,parallelModeActive=epicWave?epicWave.parallel:parallelWorktreeIsolationActive&&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),state2=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state2),updateTaskWorkflowCache(session,taskId,durableWorkflow),state2!=="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)&&await turboMayBypassTask(directory,taskId))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(config3)),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,precreate=precreateStandardWorktreeSession({...epicIsolationRequired?{isolationRequired:!0}:{},config:config3,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});await(epicIsolationRequired?precreate.catch((error93)=>{throw Error(epicIsolationDegradedMessage(incomingCoderTaskId??"unknown",error93 instanceof Error?error93.message:String(error93)))}):precreate);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(error93){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config3).worktree_dir),error93}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(epicIsolationRequired)throw Error(epicIsolationDegradedMessage(incomingCoderTaskId??"unknown",getStandardWorktreeDegradationReason(input.sessionID)?.reason??'no isolated worktree was provisioned (worktree.policy is "disabled", or the session was released from serialized mode)'));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(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}},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;if(lastUserMessage.info?.agent==="")return;let agent=resolveMessageTransformContext(output).agent,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,void 0,directory).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(`
|
|
1242
|
+
`);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,void 0,directory),activePrReviewBinding=isPrReviewReentryAgent?await readPrReviewReentryBindingContextSafe(directory,input.sessionID):null,resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory,evidenceTaskResolutionOptions(targetAgent,activePrReviewBinding?!1:void 0)),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan&&!isExplicitTaskEvidenceAgent(targetAgent)){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(`
|
|
1243
|
+
`);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(!stageBDispatchGenerationsByCallID.has(input.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`);if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,null),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED",standalonePrReviewReentry:!0}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(await readPrReviewReentryBindingContextSafe(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,config3.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")){if(generations.set(taskId,workflow.generation),isRepairableStageBView(stageBSession.taskWorkflowStates.get(taskId),workflow.state))stageBSession.taskWorkflowStates.set(taskId,workflow.state),updateTaskWorkflowCache(stageBSession,taskId,workflow);continue}if(taskId===resolvedTaskId){let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(!stageBDispatchGenerationsByCallID.has(input.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`);if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}let stageARemediation=workflow.state==="rework_required"?"Remediation: if the Stage B verdict did not require a code change, call recover_rework_task for task "+taskId+" (architect-only, audited; requires green secretscan AND sast_scan evidence newer than the verdict — normally from a fresh pre_check_batch run; unavailable when SAST is disabled), then re-dispatch. "+"Otherwise delegate the coder to repair the code, re-run pre_check_batch, and re-dispatch once stage_a_passed has fired.":`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.`;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. `+stageARemediation+(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,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID,void 0,directory);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)&&await turboMayBypassTask(directory,preflightTaskId)))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(error93){if(preflightTaskId){let transitionId=`coder-preflight:${input.callID}`,explicitEmptyPlanScope=error93 instanceof Error&&error93.message.includes("coder delegation has no complete, valid, non-empty scope.")&&!extractTaskFileDirectives(args2).present&&await hasExplicitEmptyPlanScope(directory,preflightTaskId),settled=null;if(explicitEmptyPlanScope&&preflightWorkflow.generation===0)try{settled=await settleRejectedEmptyPlanScope(directory,input,preflightTaskId,preflightWorkflow.generation)}catch(settlementError){criticalWarn(`[delegation-gate] empty-scope preflight settlement failed for ${preflightTaskId}: ${settlementError instanceof Error?settlementError.message:String(settlementError)}`)}let failedWorkflow=getTaskWorkflowSnapshot2(settled?.evidence??await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId}));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 error93}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 _internals97.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error93){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state2])=>state2==="coder_delegated").map(([taskId])=>taskId),claim=await _internals97.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"){if(_internals97.epicSentinelExists(directory)){let conflict=_internals97.resolveEpicPrFeedbackConflict(directory,preparedScope.declaredFiles);if(conflict)throw Error(`${conflict.code}: ${conflict.message}`)}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(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}return}let plan=preparedScope.plan,epicPolicy=_internals97.epicSentinelExists(directory)?_internals97.resolveEpicDispatchPolicy(directory,plan,incomingCoderTaskId,preparedScope.declaredFiles):null;if(epicPolicy?.kind==="reject")throw Error(`${epicPolicy.code}: ${epicPolicy.message}`);let epicWave=epicPolicy?.kind==="allow"?epicPolicy:null,profile=plan.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=epicWave?epicWave.maxConcurrent:session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=epicWave===null&&scopeVerdictAllowsParallel(directory,plan),parallelWorktreeIsolationActive=epicWave===null&¶llelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),epicIsolationRequired=epicWave?.isolate===!0,standardWorktreeIsolationActive=epicWave?epicWave.isolate:parallelWorktreeIsolationActive,parallelModeActive=epicWave?epicWave.parallel:parallelWorktreeIsolationActive&&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),state2=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state2),updateTaskWorkflowCache(session,taskId,durableWorkflow),state2!=="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)&&await turboMayBypassTask(directory,taskId))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(config3)),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,precreate=precreateStandardWorktreeSession({...epicIsolationRequired?{isolationRequired:!0}:{},config:config3,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});await(epicIsolationRequired?precreate.catch((error93)=>{throw Error(epicIsolationDegradedMessage(incomingCoderTaskId??"unknown",error93 instanceof Error?error93.message:String(error93)))}):precreate);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(error93){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config3).worktree_dir),error93}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(epicIsolationRequired)throw Error(epicIsolationDegradedMessage(incomingCoderTaskId??"unknown",getStandardWorktreeDegradationReason(input.sessionID)?.reason??'no isolated worktree was provisioned (worktree.policy is "disabled", or the session was released from serialized mode)'));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(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}},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;if(lastUserMessage.info?.agent==="")return;let agent=resolveMessageTransformContext(output).agent,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,void 0,directory).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(`
|
|
1244
1244
|
`),trimComment=`[Task window: showing ${visibleCount} of ${totalTasks} tasks]`,trimmedMiddle=(hiddenBefore>0?`[...${hiddenBefore} tasks hidden...]
|
|
1245
1245
|
`:"")+visibleLines+(hiddenAfter>0?`
|
|
1246
1246
|
[...${hiddenAfter} tasks hidden...]`:"");textPart.text=`${before}${trimmedMiddle}
|
|
@@ -1249,7 +1249,7 @@ ${trimComment}${after}`}}}let sessionID=lastUserMessage.info?.sessionID,planTask
|
|
|
1249
1249
|
${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,void 0,directory),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.
|
|
1250
1250
|
Rule 3: ONE task per coder call. Split this into separate delegations.
|
|
1251
1251
|
${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
1252
|
-
`)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID,void 0,directory),councilActive=await isCouncilGateActive(directory,config3.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(isTaskTool2){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals96.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},normalizedSubagentType=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(normalizedSubagentType)),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(normalizedSubagentType)?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals97.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 _internals97.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 _internals97.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);_internals96.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config3,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge);coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged",observedFiles:observedForMerge,settlementFailed:unattributedEmptyScopeMutation})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals96.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals96.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals96.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);let stageBSettlementDrops=new Map;do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!attributionResult.verdicts.has(taskId))continue;let effectiveState=state2;if(!stageBEligibleStates.includes(state2)){if(stageBDispatchContextByCallID.get(input.callID)?.taskIds?.has(taskId)){let durableSnapshot=getTaskWorkflowSnapshot2(await readTaskEvidence2(directory,taskId));if(durableSnapshot.authoritative&&stageBEligibleStates.includes(durableSnapshot.state)&&isRepairableStageBView(state2,durableSnapshot.state))session.taskWorkflowStates.set(taskId,durableSnapshot.state),updateTaskWorkflowCache(session,taskId,durableSnapshot),effectiveState=durableSnapshot.state,log(`[delegation-gate] resynced Stage B settlement view for ${taskId} from durable evidence (in-memory said ${state2})`)}if(!stageBEligibleStates.includes(effectiveState))continue}let eligibleState=effectiveState,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){let reconstructed=_internals97.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===taskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)launchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B binding for ${taskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"unbound",detail:"ignoring unbound Stage B settlement",drops:stageBSettlementDrops});continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${effectiveState} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"rejection_persist_failed",detail:`rejection could not be persisted: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops})}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config3.review_routing?.enforce_receipts??!0,routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_blocked",detail:`route receipt blocked: ${routeDecision.reason??"unknown reason"}`,drops:stageBSettlementDrops});continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_capacity",detail:"route evidence capacity exceeded",drops:stageBSettlementDrops});continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"evidence_rejected",detail:`gate evidence recording rejected the settlement: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops});continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB))try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(routeComplete&&targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1);flushStageBSettlementDropWarnings(stageBSettlementDrops)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},targetAgentForEvidence=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(targetAgentForEvidence));if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID);if(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"].includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0){let reconstructed=_internals97.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===evidenceTaskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)gateLaunchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B gate binding for ${evidenceTaskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(taskChangeContext?.declaredFiles,rawObservedFiles),context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&(observedFiles.length>0||unattributedEmptyScopeMutation),updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure||unattributedEmptyScopeMutation,observedFiles:rawObservedFiles})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(typeof subagentType==="string"&&_internals97.epicSentinelExists(directory)){let routeBindings=stageBRouteSlotByCallID.get(input.callID);await _internals97.commitEpicResidueAfterDelegation({directory,agent:subagentType,sessionID:input.sessionID,resolveTaskIds:async()=>{let ids=[...routeBindings?.keys()??[]];if(ids.length>0)return ids;let resolved=await resolveEvidenceTaskId({...storedArgs??{},...directArgs??{}},session,directory,evidenceTaskResolutionOptions(stripKnownSwarmPrefix(subagentType)));return resolved?[resolved]:[]},childSessionIds:async()=>{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope));return[...[...routeBindings?.values()??[]].map((binding)=>binding.childSessionId),extractDispatchIds2(_output).subagentSessionId]}})}if(stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID,sessionID)=>{if(stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),sessionID)deleteStageBDispatchBindings(directory,sessionID,callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error93){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,AUTO_INJECTED_ACCEPTANCE_REQUIREMENT="- Complete verification of changes, tests, and documentation (auto-injected default: no task-specific acceptance criteria were supplied)",PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES=4194304,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,EXPLICIT_TASK_EVIDENCE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals97,STAGE_B_SETTLEMENT_DROP_REASONS;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_stage_b_dispatch_binding_store();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_gate_policy();init_lifecycle();init_residue_commit();init_task_landing();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state();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_tier3_classifier();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_host_boundary();init_normalize_tool_name();init_system_guidance_carrier();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]),EXPLICIT_TASK_EVIDENCE_AGENTS=new Set(["critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor"]);_internals97={isEpicOpenForProject,resolveEpicDispatchPolicy,resolveEpicPrFeedbackConflict,commitEpicResidueAfterDelegation,epicSentinelExists,recordStageBDispatchBindings,readStageBDispatchBindings,deleteStageBDispatchBindings,resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,turboMayBypassTask,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals96.provisionWorktree},set provisionWorktree(v){_internals96.provisionWorktree=v},get removeWorktree(){return _internals96.removeWorktree},set removeWorktree(v){_internals96.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals96.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals96.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals96.postMergeCleanup},set postMergeCleanup(v){_internals96.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals96.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals96.preserveBackgroundWorktreeOwnershipForCallId=v}};STAGE_B_SETTLEMENT_DROP_REASONS={unbound:"unbound launch generation (the dispatch-generation binding is process-local and was lost)",route_blocked:"review route receipt enforcement blocked the settlement",route_capacity:"route evidence capacity exceeded",evidence_rejected:"gate evidence recording rejected the settlement (generation fencing)",rejection_persist_failed:"the rejection verdict could not be persisted"}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
|
|
1252
|
+
`)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID,void 0,directory),councilActive=await isCouncilGateActive(directory,config3.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(isTaskTool2){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals96.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},normalizedSubagentType=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(normalizedSubagentType)),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(normalizedSubagentType)?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals97.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 _internals97.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 _internals97.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);_internals96.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config3,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge);coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged",observedFiles:observedForMerge,settlementFailed:unattributedEmptyScopeMutation})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals96.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals96.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals96.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID,void 0,directory);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);let stageBSettlementDrops=new Map;do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!attributionResult.verdicts.has(taskId))continue;let effectiveState=state2;if(!stageBEligibleStates.includes(state2)){if(stageBDispatchContextByCallID.get(input.callID)?.taskIds?.has(taskId)){let durableSnapshot=getTaskWorkflowSnapshot2(await readTaskEvidence2(directory,taskId));if(durableSnapshot.authoritative&&stageBEligibleStates.includes(durableSnapshot.state)&&isRepairableStageBView(state2,durableSnapshot.state))session.taskWorkflowStates.set(taskId,durableSnapshot.state),updateTaskWorkflowCache(session,taskId,durableSnapshot),effectiveState=durableSnapshot.state,log(`[delegation-gate] resynced Stage B settlement view for ${taskId} from durable evidence (in-memory said ${state2})`)}if(!stageBEligibleStates.includes(effectiveState))continue}let eligibleState=effectiveState,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){let reconstructed=_internals97.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===taskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)launchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B binding for ${taskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"unbound",detail:"ignoring unbound Stage B settlement",drops:stageBSettlementDrops});continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${effectiveState} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"rejection_persist_failed",detail:`rejection could not be persisted: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops})}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config3.review_routing?.enforce_receipts??!0;if(isRouteBlockedForSettlement(input.callID,input.sessionID,taskId)&&routeEnforcementEnabled){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ROUTE_RECEIPT_INVALIDATED (this dispatch's route persist failed; a prior receipt does not authorize it)`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_blocked",detail:"route receipt invalidated: this dispatch route persist failed",drops:stageBSettlementDrops});continue}let routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_blocked",detail:`route receipt blocked: ${routeDecision.reason??"unknown reason"}`,drops:stageBSettlementDrops});continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_capacity",detail:"route evidence capacity exceeded",drops:stageBSettlementDrops});continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"evidence_rejected",detail:`gate evidence recording rejected the settlement: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops});continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB))try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(routeComplete&&targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1);flushStageBSettlementDropWarnings(stageBSettlementDrops)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},targetAgentForEvidence=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(targetAgentForEvidence));if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID);if(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"].includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0){let reconstructed=_internals97.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===evidenceTaskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)gateLaunchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B gate binding for ${evidenceTaskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??await changedFilesSinceSnapshotAsync(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(taskChangeContext?.declaredFiles,rawObservedFiles),context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&(observedFiles.length>0||unattributedEmptyScopeMutation),updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure||unattributedEmptyScopeMutation,observedFiles:rawObservedFiles})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(typeof subagentType==="string"&&_internals97.epicSentinelExists(directory)){let routeBindings=stageBRouteSlotByCallID.get(input.callID);await _internals97.commitEpicResidueAfterDelegation({directory,agent:subagentType,sessionID:input.sessionID,resolveTaskIds:async()=>{let ids=[...routeBindings?.keys()??[]];if(ids.length>0)return ids;let resolved=await resolveEvidenceTaskId({...storedArgs??{},...directArgs??{}},session,directory,evidenceTaskResolutionOptions(stripKnownSwarmPrefix(subagentType)));return resolved?[resolved]:[]},childSessionIds:async()=>{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope));return[...[...routeBindings?.values()??[]].map((binding)=>binding.childSessionId),extractDispatchIds2(_output).subagentSessionId]}})}if(stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID,sessionID)=>{if(stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),sessionID)deleteStageBDispatchBindings(directory,sessionID,callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error93){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,AUTO_INJECTED_ACCEPTANCE_REQUIREMENT="- Complete verification of changes, tests, and documentation (auto-injected default: no task-specific acceptance criteria were supplied)",PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES=4194304,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,EXPLICIT_TASK_EVIDENCE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals97,STAGE_B_SETTLEMENT_DROP_REASONS;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_stage_b_dispatch_binding_store();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_gate_policy();init_lifecycle();init_residue_commit();init_task_landing();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state();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_tier3_classifier();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_host_boundary();init_normalize_tool_name();init_system_guidance_carrier();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]),EXPLICIT_TASK_EVIDENCE_AGENTS=new Set(["critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor"]);_internals97={isEpicOpenForProject,routeInvalidationProbe:null,resolveEpicDispatchPolicy,resolveEpicPrFeedbackConflict,commitEpicResidueAfterDelegation,epicSentinelExists,recordStageBDispatchBindings,readStageBDispatchBindings,deleteStageBDispatchBindings,resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,turboMayBypassTask,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals96.provisionWorktree},set provisionWorktree(v){_internals96.provisionWorktree=v},get removeWorktree(){return _internals96.removeWorktree},set removeWorktree(v){_internals96.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals96.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals96.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals96.postMergeCleanup},set postMergeCleanup(v){_internals96.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals96.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals96.preserveBackgroundWorktreeOwnershipForCallId=v}};STAGE_B_SETTLEMENT_DROP_REASONS={unbound:"unbound launch generation (the dispatch-generation binding is process-local and was lost)",route_blocked:"review route receipt enforcement blocked the settlement",route_capacity:"route evidence capacity exceeded",evidence_rejected:"gate evidence recording rejected the settlement (generation fencing)",rejection_persist_failed:"the rejection verdict could not be persisted"}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
|
|
1253
1253
|
`)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function trajectoryStepGeneration(){return stepCounterGeneration}function bumpStepCounterGeneration(){stepCounterGeneration+=1}function evictOldestStepSessionIfNeeded(key2){if(sessionStepCounters.has(key2))return;while(sessionStepCounters.size>=MAX_TRACKED_STEP_SESSIONS){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId,directory){let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let step=(sessionStepCounters.get(key2)??0)+1;return sessionStepCounters.set(key2,step),step}function seedTrajectoryStepCounter(sessionId,directory,step){if(!Number.isFinite(step)||step<=0)return;let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let current=sessionStepCounters.get(key2)??0;if(step>current)sessionStepCounters.set(key2,Math.floor(step))}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0){let suffix=sessionKeySuffix(sessionId),removed=!1;for(let key2 of sessionStepCounters.keys())if(key2.endsWith(suffix))sessionStepCounters.delete(key2),removed=!0;if(removed)bumpStepCounterGeneration()}else if(sessionStepCounters.size>0)sessionStepCounters.clear(),bumpStepCounterGeneration()}var MAX_TRACKED_STEP_SESSIONS=500,sessionStepCounters,stepCounterGeneration=0;var init_trajectory_step_state=__esm(()=>{init_canonical_root();sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key2,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key2);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature){let next={key:key2,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current)return!1;if(expectedGeneration!==void 0&¤t.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function peekScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return;return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function clearScopedModelSelectionsForSession(sessionID,opts){let normalizedSessionID=normalizeText2(sessionID),primaryScopes=opts?.primaryScopes??!0;for(let[key2,entry]of scopedModelOverrides){if(!key2.startsWith(`${normalizedSessionID}␟`))continue;if(!primaryScopes){if((key2.split("␟")[1]??"")==="")continue}scopedModelOverrides.delete(entry.key)}}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key2=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key2);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key2),routesByParentCall.set(key2,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key2)}function pruneRoutes(now){for(let[key2,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key2=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key2);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function sessionFallbackScope(input){return{sessionID:normalizeText3(input.sessionID),invocationID:PRIMARY_SESSION_INVOCATION_ID,swarmID:normalizeText3(input.swarmID)||void 0,role:normalizeText3(input.role)}}function advanceSessionFallbackSelection(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(scope,chain,now),advanced=advanceScopedModelSelection(scope,chain,selection.generation,now);return{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,scope}}function resolveSessionChatModelOverride(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]);if(chain.fallbacks.length===0)return{status:"missing"};let selection=peekScopedModelSelection(scope,chain,now);if(selection===void 0)return{status:"missing"};if(selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex}}function recordSessionChatAgent(sessionID,agentName){let session=normalizeText3(sessionID),agent=normalizeText3(agentName);if(!session||!agent)return;while(sessionChatAgentBySession.size>=MAX_SESSION_CHAT_AGENTS){let oldest=sessionChatAgentBySession.keys().next().value;if(typeof oldest!=="string")break;sessionChatAgentBySession.delete(oldest)}sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent)}function resolveSessionChatAgent(sessionID){let session=normalizeText3(sessionID);if(!session)return;let agent=sessionChatAgentBySession.get(session);if(agent===void 0)return;return sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent),agent}function clearPendingTaskModelRoutesForSession(sessionID,mode="session"){let normalizedSessionID=normalizeText3(sessionID);for(let[key2,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}if(clearScopedModelSelectionsForSession(normalizedSessionID,{primaryScopes:mode==="session"}),mode==="session")sessionChatAgentBySession.delete(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),sessionChatAgentBySession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,MAX_SESSION_CHAT_AGENTS=256,sessionChatAgentBySession,routesByParentCall,routeKeyByChildSession,PRIMARY_SESSION_INVOCATION_ID="";var init_task_model_routing=__esm(()=>{init_model_override_state();sessionChatAgentBySession=new Map,routesByParentCall=new Map,routeKeyByChildSession=new Map});import{existsSync as existsSync52,mkdirSync as mkdirSync33,readFileSync as readFileSync40,writeFileSync as writeFileSync21}from"node:fs";import*as path106 from"node:path";function sessionStartPath(directory){if(typeof directory!=="string"||directory.trim()===""||!path106.isAbsolute(directory))return null;return path106.join(directory,".swarm","session",SESSION_START_FILE)}function recordSessionStart(directory,startMs){try{let filePath=sessionStartPath(directory);if(filePath===null)return;let line=JSON.stringify({startMs,ts:Date.now()});mkdirSync33(path106.dirname(filePath),{recursive:!0}),writeFileSync21(filePath,`${line}
|
|
1254
1254
|
`,{flag:"a"})}catch{}}function readEarliestSessionStart(directory){try{let filePath=sessionStartPath(directory);if(filePath===null||!existsSync52(filePath))return null;let lines=readFileSync40(filePath,"utf-8").split(`
|
|
1255
1255
|
`),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 randomUUID13}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=randomUUID13();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((resolve55)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS3,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve55(0);return}let count2=0;for(let line of stdout.split(`
|
|
@@ -4364,7 +4364,7 @@ Writes a retrospective evidence bundle for a completed phase.
|
|
|
4364
4364
|
|
|
4365
4365
|
Phase **${result.phase??"unknown"}** retrospective saved to \`.swarm/evidence/${result.task_id??"unknown"}/evidence.json\`.
|
|
4366
4366
|
|
|
4367
|
-
Run \`/swarm evidence ${result.task_id??"unknown"}\` to view it, or \`/swarm status\` to check phase_complete readiness.`;return`Error: ${result.message}`}var init_write_retro2=__esm(()=>{init_write_retro()});var COMMAND_NAMES,COMMAND_NAME_SET;var init_command_names=__esm(()=>{init_registry2();COMMAND_NAMES=Object.freeze(Object.keys(COMMAND_REGISTRY)),COMMAND_NAME_SET=new Set(COMMAND_NAMES)});import path292 from"node:path";function parseGuardrailExplainArgs(args2){let agent="coder",scope=null,writeTargets=[],positional=[],i=0;while(i<args2.length){let token=args2[i];if(token==="--agent"&&i+1<args2.length)agent=args2[i+1],i+=2;else if(token==="--scope"&&i+1<args2.length)scope=args2[i+1],i+=2;else if(token==="--write"&&i+1<args2.length)writeTargets.push(args2[i+1]),i+=2;else positional.push(token),i++}return{agent,scope,writeTargets,shellCommand:positional.join(" ")}}function resolveShellType(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|cmd\.exe|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";return"posix"}function evaluateDestructiveDecision(rawCommand,cwd,declaredScope){if(!rawCommand)return{decision:"allow",firingRule:"allow: no rule matched"};let shared=classifyCommand(rawCommand),sharedFiringRule=`shared_classifier: ${shared.aggregate}`;if(getSharedClassifierGuardrailBlock(shared))return{decision:"block",firingRule:sharedFiringRule};let command=dcNormalizeCommand(rawCommand),unwrapped=dcUnwrapWrappers(command),outerSegments=dcSplitSegments(command),innerSegments=dcSplitSegments(unwrapped),perSegmentUnwrapped=outerSegments.map((s)=>dcUnwrapWrappers(s)),allSegments=[...new Set([...outerSegments,...innerSegments,...perSegmentUnwrapped])];for(let segment of allSegments){let seg=segment.trim();if(!seg)continue;if(dcCheckJunctionCreation(seg,cwd))return{decision:"block",firingRule:"destructive_block: junction creation"};let targets=dcExtractRecursiveRmTargets(seg);if(targets){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}if(/^(?:rmdir|rd)(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets2=dcExtractWindowsCmdTargets(seg);if(targets2.length===0)return{decision:"block",firingRule:"destructive_block: Windows recursive directory delete (rmdir /s)"};let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}if(/^del(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets2=dcExtractWindowsCmdTargets(seg);if(targets2.length>0){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.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 targets2=dcExtractPowerShellTargets(seg);if(targets2.length>0){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}else return{decision:"block",firingRule:"destructive_block: PowerShell Remove-Item -Recurse (target unverifiable)"}}if(/Get-ChildItem\b.*\|\s*Remove-Item\b.*-[Rr]ecurse/i.test(seg)||/gci\b.*\|\s*ri\b.*-[Rr]ecurse/i.test(seg))return{decision:"block",firingRule:"destructive_block: PowerShell pipeline Get-ChildItem | Remove-Item -Recurse"};if(/^git\s+worktree\s+remove\s+.*--force\b/i.test(seg)){let worktreeRemoveMatch=/^git\s+worktree\s+remove\s+(.+)$/i.exec(seg);if(worktreeRemoveMatch){let pathArgs=worktreeRemoveMatch[1].trim().split(/\s+/).filter(Boolean).map((token)=>token.replace(/^["']|["']$/g,"")).filter((token)=>!token.startsWith("-")),target=pathArgs.length===1?pathArgs[0]?.trim():null;if(!(target!=null&&target.length>0&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(target,declaredScope,cwd)))return{decision:"block",firingRule:"destructive_block: git worktree remove --force"}}}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)))return{decision:"block",firingRule:`destructive_block: rsync --delete (target: ${redactPath(rsyncTarget??"unknown")})`}}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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:"destructive_block: 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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "7z" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed'};{let 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 swarmCliMatches=[probe2.match(/^\\?(?: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),probe2.match(/^\\?opencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i),probe2.match(/\bcli[/\\]+index\.[mc]?(?:js|ts)\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)];for(let m of swarmCliMatches){if(!m)continue;let normalized=m[1].trim().split(/\s+/).join(" "),firstToken=normalized.includes(" ")?normalized.split(" ")[0]:normalized;if(HUMAN_ONLY_SWARM_COMMANDS.has(normalized)||HUMAN_ONLY_SWARM_COMMANDS.has(firstToken))return{decision:"block",firingRule:`human_only_command: "${HUMAN_ONLY_SWARM_COMMANDS.has(normalized)?normalized:firstToken}" is a human-only swarm command (not invocable from shell by an agent)`}}}{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)return{decision:"block",firingRule:"system_file_tampering: shell command targeting .swarm/spec-staleness.json (system-managed file)"}}}}return{decision:"allow",firingRule:"allow: no destructive/scope rule matched"}}async function handleGuardrailExplain(directory,args2){let{agent,scope,writeTargets,shellCommand}=parseGuardrailExplainArgs(args2),resolvedScope=scope??directory,scopeEntries=scope!=null&&scope.length>0?[scope]:[resolvedScope];if(writeTargets.length>0){let results=[];for(let rawPath of writeTargets){let absolutePath2=path292.resolve(directory,rawPath),decision2=checkFileAuthority(agent,absolutePath2,directory,void 0,{declaredScope:scope!=null?[scope]:null}),zoneResult=classifyFile(absolutePath2),allowed=decision2.allowed===!0,zone=allowed?zoneResult.zone:decision2.zone??zoneResult.zone;results.push({path:rawPath,decision:allowed?"allow":"block",firingRule:allowed?"allow: no rule matched":decision2.reason,resolvedScope,zone})}let redactedResolvedScope=redactPath(resolvedScope);return["## Guardrail Explain (dry-run)","",`**Mode**: write-target | **Agent**: ${agent} | **Resolved scope**: ${redactedResolvedScope}`,"","| Path | Decision | Firing Rule | Resolved Scope | Zone |","| --- | --- | --- | --- | --- |",...results.map((r)=>`| ${redactPath(r.path)} | ${r.decision} | ${r.firingRule} | ${redactPath(r.resolvedScope)} | ${r.zone} |`),""].join(`
|
|
4367
|
+
Run \`/swarm evidence ${result.task_id??"unknown"}\` to view it, or \`/swarm status\` to check phase_complete readiness.`;return`Error: ${result.message}`}var init_write_retro2=__esm(()=>{init_write_retro()});var COMMAND_NAMES,COMMAND_NAME_SET;var init_command_names=__esm(()=>{init_registry2();COMMAND_NAMES=Object.freeze(Object.keys(COMMAND_REGISTRY)),COMMAND_NAME_SET=new Set(COMMAND_NAMES)});import path292 from"node:path";function parseGuardrailExplainArgs(args2){let agent="coder",scope=null,writeTargets=[],positional=[],i=0;while(i<args2.length){let token=args2[i];if(token==="--agent"&&i+1<args2.length)agent=args2[i+1],i+=2;else if(token==="--scope"&&i+1<args2.length)scope=args2[i+1],i+=2;else if(token==="--write"&&i+1<args2.length)writeTargets.push(args2[i+1]),i+=2;else positional.push(token),i++}return{agent,scope,writeTargets,shellCommand:positional.join(" ")}}function resolveShellType(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|cmd\.exe|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";return"posix"}function evaluateDestructiveDecision(rawCommand,cwd,declaredScope){if(!rawCommand)return{decision:"allow",firingRule:"allow: no rule matched"};let shared=classifyCommand(rawCommand),sharedFiringRule=`shared_classifier: ${shared.aggregate}`;if(getSharedClassifierGuardrailBlock(shared))return{decision:"block",firingRule:sharedFiringRule};let command=dcNormalizeCommand(rawCommand),unwrapped=dcUnwrapWrappers(command),outerSegments=dcSplitSegments(command),innerSegments=dcSplitSegments(unwrapped),perSegmentUnwrapped=outerSegments.map((s)=>dcUnwrapWrappers(s)),allSegments=[...new Set([...outerSegments,...innerSegments,...perSegmentUnwrapped])];for(let segment of allSegments){let seg=segment.trim();if(!seg)continue;if(dcCheckJunctionCreation(seg,cwd))return{decision:"block",firingRule:"destructive_block: junction creation"};let targets=dcExtractRecursiveRmTargets(seg);if(targets){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}let explainRmdirVerb=/^(?:rmdir|rd)(?:\.exe)?\s*/i.exec(seg);if(explainRmdirVerb){let parsed=dcParseWindowsRecursiveDelete(seg.slice(explainRmdirVerb[0].length));if(parsed.fires){if(parsed.targets.length===0)return{decision:"block",firingRule:"destructive_block: Windows recursive directory delete (rmdir /s)"};let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:parsed.targets,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}}let explainDelVerb=/^del(?:\.exe)?\s*/i.exec(seg);if(explainDelVerb){let parsed=dcParseWindowsRecursiveDelete(seg.slice(explainDelVerb[0].length));if(parsed.fires){if(parsed.targets.length===0)return{decision:"block",firingRule:"destructive_block: Windows recursive file delete (del /s)"};let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:parsed.targets,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}}if(/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*\s-[Rr]ecurse\b/i.test(seg)||/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*\s-[Rr]\b/i.test(seg)){let targets2=dcExtractPowerShellTargets(seg);if(targets2.length>0){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}else return{decision:"block",firingRule:"destructive_block: PowerShell Remove-Item -Recurse (target unverifiable)"}}if(/Get-ChildItem\b.*\|\s*Remove-Item\b.*-[Rr]ecurse/i.test(seg)||/gci\b.*\|\s*ri\b.*-[Rr]ecurse/i.test(seg))return{decision:"block",firingRule:"destructive_block: PowerShell pipeline Get-ChildItem | Remove-Item -Recurse"};if(/^git\s+worktree\s+remove\s+.*--force\b/i.test(seg)){let worktreeRemoveMatch=/^git\s+worktree\s+remove\s+(.+)$/i.exec(seg);if(worktreeRemoveMatch){let pathArgs=worktreeRemoveMatch[1].trim().split(/\s+/).filter(Boolean).map((token)=>token.replace(/^["']|["']$/g,"")).filter((token)=>!token.startsWith("-")),target=pathArgs.length===1?pathArgs[0]?.trim():null;if(!(target!=null&&target.length>0&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(target,declaredScope,cwd)))return{decision:"block",firingRule:"destructive_block: git worktree remove --force"}}}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)))return{decision:"block",firingRule:`destructive_block: rsync --delete (target: ${redactPath(rsyncTarget??"unknown")})`}}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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:"destructive_block: 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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "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))return{decision:"block",firingRule:'destructive_block: "7z" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed'};{let 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 swarmCliMatches=[probe2.match(/^\\?(?: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),probe2.match(/^\\?opencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i),probe2.match(/\bcli[/\\]+index\.[mc]?(?:js|ts)\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)];for(let m of swarmCliMatches){if(!m)continue;let normalized=m[1].trim().split(/\s+/).join(" "),firstToken=normalized.includes(" ")?normalized.split(" ")[0]:normalized;if(HUMAN_ONLY_SWARM_COMMANDS.has(normalized)||HUMAN_ONLY_SWARM_COMMANDS.has(firstToken))return{decision:"block",firingRule:`human_only_command: "${HUMAN_ONLY_SWARM_COMMANDS.has(normalized)?normalized:firstToken}" is a human-only swarm command (not invocable from shell by an agent)`}}}{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)return{decision:"block",firingRule:"system_file_tampering: shell command targeting .swarm/spec-staleness.json (system-managed file)"}}}}return{decision:"allow",firingRule:"allow: no destructive/scope rule matched"}}async function handleGuardrailExplain(directory,args2){let{agent,scope,writeTargets,shellCommand}=parseGuardrailExplainArgs(args2),resolvedScope=scope??directory,scopeEntries=scope!=null&&scope.length>0?[scope]:[resolvedScope];if(writeTargets.length>0){let results=[];for(let rawPath of writeTargets){let absolutePath2=path292.resolve(directory,rawPath),decision2=checkFileAuthority(agent,absolutePath2,directory,void 0,{declaredScope:scope!=null?[scope]:null}),zoneResult=classifyFile(absolutePath2),allowed=decision2.allowed===!0,zone=allowed?zoneResult.zone:decision2.zone??zoneResult.zone;results.push({path:rawPath,decision:allowed?"allow":"block",firingRule:allowed?"allow: no rule matched":decision2.reason,resolvedScope,zone})}let redactedResolvedScope=redactPath(resolvedScope);return["## Guardrail Explain (dry-run)","",`**Mode**: write-target | **Agent**: ${agent} | **Resolved scope**: ${redactedResolvedScope}`,"","| Path | Decision | Firing Rule | Resolved Scope | Zone |","| --- | --- | --- | --- | --- |",...results.map((r)=>`| ${redactPath(r.path)} | ${r.decision} | ${r.firingRule} | ${redactPath(r.resolvedScope)} | ${r.zone} |`),""].join(`
|
|
4368
4368
|
`)}if(!shellCommand)return["## Guardrail Explain (dry-run)","","Provide a shell command to analyze, or use `--write <path>` for write-target mode.","","```","/swarm guardrail explain <command>","/swarm guardrail explain --agent <role> --scope <path> <command>","/swarm guardrail explain --write <path> [--write <path2> ...]","```",""].join(`
|
|
4369
4369
|
`);let decision="allow",firingRule="allow: no rule matched",writeCategories=new Set,destructiveEval=evaluateDestructiveDecision(shellCommand,directory,scopeEntries);if(destructiveEval.decision==="block")decision="block",firingRule=destructiveEval.firingRule;let commandSegments=dcSplitSegments(shellCommand),unwrappedSegments=commandSegments.map((s)=>dcUnwrapWrappers(s)),detectionCommand=commandSegments.some((s,i)=>unwrappedSegments[i]!==s)?unwrappedSegments.join(`
|
|
4370
4370
|
`):shellCommand;if(decision==="allow"){let detected=resolveShellType(shellCommand),authority=resolveWindowsWriteAuthority("shell",shellCommand,detected,isPowerShellShaped(shellCommand),process.platform,getObservedHostShell()),wrapperDeclaredHere=declaresWindowsWrapperLoose(shellCommand),posix24=detectPosixWrites(detectionCommand),analysis=authority===null?posix24:mergeWriteAnalyses(posix24,detectWindowsWrites(detectionCommand,authority),!0,wrapperDeclaredHere),rawPosix=detectPosixWrites(shellCommand);if((authority===null?rawPosix:mergeWriteAnalyses(rawPosix,detectWindowsWrites(shellCommand,authority),!0,wrapperDeclaredHere)).parseError&&!isPowerShellReadOnlyPipeline(shellCommand))decision="block",firingRule="parse_error: write detection failed to parse command — rejecting for safety";else if(analysis.parseError&&!isPowerShellReadOnlyPipeline(detectionCommand))decision="block",firingRule="parse_error: write detection failed to parse command — rejecting for safety";else if(analysis.hasWrites){let resolvedWrites=resolveWriteTargets(detectionCommand,analysis.writes,directory);for(let write of resolvedWrites)if(write.resolvedPath){if(agent!=="architect"){if(!(isInDeclaredScope(write.resolvedPath,scopeEntries,directory)||write.original.emptyDirectoryRemoval===!0&&isPosixRmdirExecutor("shell",authority,detectionCommand)&&isEmptyDirectoryRemovalWithinWorkspace(write.resolvedPath,directory))){decision="block",firingRule=`scope_violation: write outside declared scope: ${redactPath(write.resolvedPath)}`;break}}writeCategories.add(write.original.category)}else writeCategories.add(write.original.category)}}else{let detected=resolveShellType(shellCommand),authority=resolveWindowsWriteAuthority("shell",shellCommand,detected,isPowerShellShaped(shellCommand),process.platform,getObservedHostShell()),wrapperDeclaredElse=declaresWindowsWrapperLoose(shellCommand),posix24=detectPosixWrites(detectionCommand),analysis=authority===null?posix24:mergeWriteAnalyses(posix24,detectWindowsWrites(detectionCommand,authority),!0,wrapperDeclaredElse);if(!analysis.parseError&&analysis.hasWrites)for(let write of analysis.writes)writeCategories.add(write.category)}let redactedCommand=redactShellCommand(shellCommand),redactedResolvedScopeShell=redactPath(resolvedScope),shellResult={decision,firingRule,resolvedScope:redactedResolvedScopeShell,writeCategories:writeCategories.size>0?[...writeCategories]:[],command:redactedCommand};return["## Guardrail Explain (dry-run)","",`**Mode**: shell | **Agent**: ${agent} | **Resolved scope**: ${redactedResolvedScopeShell}`,"","| Field | Value |","| --- | --- |",`| Command | \`${shellResult.command}\` |`,`| Decision | ${shellResult.decision} |`,`| Firing Rule | ${shellResult.firingRule} |`,`| Resolved Scope | ${shellResult.resolvedScope} |`,`| Write Categories | ${shellResult.writeCategories.length>0?shellResult.writeCategories.join(", "):"(none)"} |`,""].join(`
|