opencode-swarm 7.200.5 → 7.200.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{attest-task-0k72fh70.js → attest-task-10qxnfg0.js} +25 -25
  4. package/dist/cli/{auto-checkpoint-8g004dar.js → auto-checkpoint-n4wjv3c3.js} +4 -4
  5. package/dist/cli/{checkpoint-18wx2473.js → checkpoint-hce4bjpa.js} +8 -8
  6. package/dist/cli/{coder-settlement-r2q6pkxc.js → coder-settlement-wzccs5q0.js} +3 -3
  7. package/dist/cli/{config-doctor-h071vxsj.js → config-doctor-zmrk4e62.js} +7 -7
  8. package/dist/cli/{core-6767154r.js → core-91vc3hm8.js} +1 -1
  9. package/dist/cli/{curator-drift-gd7tckag.js → curator-drift-jnnfryzt.js} +5 -5
  10. package/dist/cli/{curator-llm-factory-mf701qb7.js → curator-llm-factory-mj9nwpqy.js} +25 -25
  11. package/dist/cli/{curator-pf0edk2z.js → curator-mx34qmvj.js} +25 -25
  12. package/dist/cli/{doctor-knowledge-receipt-phase-id-zz0tz3pt.js → doctor-knowledge-receipt-phase-id-wsv9av6b.js} +4 -4
  13. package/dist/cli/{evidence-summary-service-awjxt2am.js → evidence-summary-service-t8jxvzse.js} +9 -9
  14. package/dist/cli/{gate-evidence-tvkhkqwy.js → gate-evidence-13evayfx.js} +2 -2
  15. package/dist/cli/{guardrail-explain-m70anx1g.js → guardrail-explain-w69nx4h3.js} +26 -26
  16. package/dist/cli/{guardrail-log-3sf6n33b.js → guardrail-log-em42cpeg.js} +3 -3
  17. package/dist/cli/{guardrail-reset-t94jbv1q.js → guardrail-reset-1z11c474.js} +25 -25
  18. package/dist/cli/{hive-promoter-60h9tqgs.js → hive-promoter-et6yf4e4.js} +25 -25
  19. package/dist/cli/{index-dsqavehz.js → index-1j9g90y9.js} +1 -1
  20. package/dist/cli/{index-8c51asrp.js → index-50h4hrhe.js} +232 -97
  21. package/dist/cli/{index-b4amh1n3.js → index-6cgh59z6.js} +3 -3
  22. package/dist/cli/{index-vz1fh1v3.js → index-9ww8f1e9.js} +3 -3
  23. package/dist/cli/{index-74n7sz4s.js → index-bkdkkxxe.js} +1 -1
  24. package/dist/cli/{index-vxbj42j0.js → index-cbhkyfmm.js} +2 -2
  25. package/dist/cli/{index-687c2ze1.js → index-e5b0ayxw.js} +3 -3
  26. package/dist/cli/{index-se501ytb.js → index-ehcp9r1f.js} +1 -1
  27. package/dist/cli/{index-ryrg48c7.js → index-fjh70sfg.js} +5 -5
  28. package/dist/cli/{index-1akazdbj.js → index-gjzfy7zw.js} +1 -1
  29. package/dist/cli/{index-phz90w3t.js → index-h21p9f69.js} +1 -1
  30. package/dist/cli/{index-pvj101jx.js → index-he1xpa9h.js} +3 -3
  31. package/dist/cli/{index-xdk3cxs9.js → index-hfzyp68b.js} +27 -27
  32. package/dist/cli/{index-4mjfdpte.js → index-j2736j97.js} +6 -6
  33. package/dist/cli/{index-826kptfe.js → index-k3nhzhkz.js} +3 -3
  34. package/dist/cli/{index-yamz6830.js → index-kdp4rk4p.js} +1 -1
  35. package/dist/cli/{index-5qajesjq.js → index-n2vx9eb0.js} +3 -3
  36. package/dist/cli/{index-wyfag7r7.js → index-n61daqkj.js} +2 -2
  37. package/dist/cli/{index-cy2gbs5b.js → index-qxse4xm5.js} +1 -1
  38. package/dist/cli/{index-ee59rzwk.js → index-r9x74612.js} +2 -2
  39. package/dist/cli/{index-1asbb0r4.js → index-tw0bn65v.js} +1 -1
  40. package/dist/cli/{index-1by2qd8n.js → index-w747vv23.js} +1 -1
  41. package/dist/cli/{index-10myvh2k.js → index-wxh0624z.js} +1 -1
  42. package/dist/cli/{index-hfnj4s6r.js → index-yd8k2081.js} +25 -25
  43. package/dist/cli/{index-xh861gf3.js → index-ykwya5ff.js} +2 -2
  44. package/dist/cli/{index-g1b5xxzc.js → index-yy7hq6c5.js} +5 -4
  45. package/dist/cli/{index-k01n01sc.js → index-z4qhqws0.js} +3 -3
  46. package/dist/cli/{index-h8419k5d.js → index-zfzgt2hj.js} +4 -4
  47. package/dist/cli/{index-3x8mz39c.js → index-zq1gna9j.js} +1 -1
  48. package/dist/cli/{index-twwdx79t.js → index-zv45anwx.js} +1 -1
  49. package/dist/cli/index.js +26 -26
  50. package/dist/cli/{knowledge-escalator-3096yt7j.js → knowledge-escalator-6h3bwf6q.js} +7 -7
  51. package/dist/cli/{knowledge-events-st3j22za.js → knowledge-events-wp1j51h6.js} +5 -5
  52. package/dist/cli/{knowledge-store-9q8jvd0p.js → knowledge-store-98jhzs3k.js} +1 -1
  53. package/dist/cli/{knowledge-validator-fak1fvdm.js → knowledge-validator-jttph6bb.js} +2 -2
  54. package/dist/cli/{mcp-shvt5c9b.js → mcp-3fbk6v7e.js} +1 -1
  55. package/dist/cli/{model-preflight-cxhdzc9c.js → model-preflight-vps41qvj.js} +25 -25
  56. package/dist/cli/{pending-delegations-tjj8nhmm.js → pending-delegations-f3yj2qxg.js} +2 -2
  57. package/dist/cli/{pr-subscriptions-xtnbfg8m.js → pr-subscriptions-ash398n1.js} +1 -1
  58. package/dist/cli/{pr-workflow-gate-24ytg64p.js → pr-workflow-gate-6za22msz.js} +25 -25
  59. package/dist/cli/{scan-cursor-drax4dt3.js → scan-cursor-15x71ymh.js} +2 -2
  60. package/dist/cli/{schema-epr5xxb0.js → schema-69za4986.js} +1 -1
  61. package/dist/cli/{scope-persistence-pyn9vb4r.js → scope-persistence-6qnvpm85.js} +5 -5
  62. package/dist/cli/{server-c5b651kg.js → server-cdpsjzsp.js} +25 -25
  63. package/dist/cli/{skill-generator-r8kvvbh2.js → skill-generator-q77jzyw0.js} +8 -8
  64. package/dist/cli/{snapshot-coordination-init-wnt85258.js → snapshot-coordination-init-gz9ak1be.js} +25 -25
  65. package/dist/cli/{speckit-checkoff-64p4d5hf.js → speckit-checkoff-59xs6f5t.js} +3 -3
  66. package/dist/cli/{worktree-collision-ownership-eej2phhm.js → worktree-collision-ownership-8zm5z35p.js} +2 -2
  67. package/dist/cli/{worktree-isolation-xsc0k2n3.js → worktree-isolation-f7khy039.js} +25 -25
  68. package/dist/hooks/guardrails/tool-before.d.ts +1 -1
  69. package/dist/hooks/shell-executor-context.d.ts +17 -0
  70. package/dist/hooks/shell-write-detect.d.ts +26 -0
  71. package/dist/host/v2/hooks.d.ts +20 -0
  72. package/dist/host/v2/types.d.ts +27 -0
  73. package/dist/index.js +13 -13
  74. 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.5",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run; 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.6",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run; 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
 
@@ -703,7 +703,7 @@ ${formatSwarmPlanTrailer(planKey)}`}function cacheRootTimestamp(key,value){if(ro
703
703
  `)}function summarizeClosedWave(wave,outcomes){let resolutions={};for(let outcome of outcomes)resolutions[outcome.taskId]=outcome.resolution;return{seq:wave.seq,phase:wave.phase,taskIds:[...wave.taskIds],resolutions,closeHead:wave.closeHead??null,divergence:outcomes.filter((o)=>o.undeclared.length>0).map((o)=>({taskId:o.taskId,undeclared:o.undeclared})),waveUndeclared:wave.undeclared??[]}}function predecessorMessage(problems,planKey){let lines=problems.slice(0,10).map((p)=>`${p.taskId} depends on ${p.dependency}, which ${PREDECESSOR_WHY[p.why]}`),more=problems.length>10?` (+${problems.length-10} more)`:"",committedHint=problems.some((p)=>p.why==="not-committed")?` For a task whose work IS on the epic branch, ask the user to run \`/swarm epic status --repair-refs\` (it re-adopts the task's commit: its \`swarm(task <id>): …\` commit with the trailer \`Swarm-Plan: ${planKey}\`, else the newest commit touching its declared files); if its work is missing, re-run the task.`:"";return`These tasks can never run as planned: ${lines.join("; ")}${more}. Tell the user and fix the plan — drop or correct the dependency (save_plan), or close the dependent task (update_task_status closed).${committedHint} Then call epic_next_wave.`}function syncPhaseRecords(phases,currentPhase,currentStatus){let key=String(currentPhase),prior=phases[key];if(prior?.status===currentStatus||prior?.status==="complete")return phases;return{...phases,[key]:{status:currentStatus,reviewRuns:prior?.reviewRuns??0,verdicts:prior?.verdicts??[]}}}var PREDECESSOR_WHY;var init_next_wave_format=__esm(()=>{PREDECESSOR_WHY={removed:"is no longer in the plan",closed:"was closed (its work will never exist)","later-phase":"belongs to a later phase","not-committed":"is completed but its commit is not on the epic branch (no epic task ref, or the ref is no longer reachable from HEAD — e.g. it was completed outside a wave, or a rebase/amend rewrote its commit)",cycle:"forms a dependency cycle"}});import*as path54 from"node:path";function toCoChangeEntry(pair){return{fileA:pair.fileA,fileB:pair.fileB,npmi:pair.npmi,coChangeCount:pair.coChangeCount,lift:0,hasStaticEdge:!1,totalCommits:0,commitsA:0,commitsB:0}}function epicWaveVerdictOptions(plan,wave){return{plan,scopes:wave.files,useCochange:!!wave.cochange,...wave.cochange?{cochangePairs:wave.cochange.pairs.map(toCoChangeEntry),cochangeThreshold:wave.cochange.threshold}:{}}}function computeEpicWaveVerdict(directory,plan,wave,taskIds){return _internals53.computeParallelVerdict(directory,taskIds,epicWaveVerdictOptions(plan,wave))}function reject(code,message){return{kind:"reject",code,message}}function errorText2(error49){return error49 instanceof Error?error49.message:String(error49)}function findPlanTask(plan,taskId){for(let phase of plan.phases){let task=(phase.tasks??[]).find((t)=>t.id===taskId);if(task)return task}return null}function isResolved(status){return status==="completed"||status==="closed"}function list(items,max=8){let shown=items.slice(0,max).join(", ");return items.length>max?`${shown}, …`:shown}function resolveEpicDispatchPolicy(directory,plan,incomingTaskId,liveBindingFiles){if(!_internals53.epicSentinelExists(directory))return null;if(!_internals53.isEpicModeConfigEnabledForDirectory(directory))return null;let epic;try{epic=_internals53.getOpenEpic(directory,plan)}catch(error49){return reject("EPIC_STATE_UNREADABLE",`Epic Mode is enabled and an epic sentinel exists, but the epic's lifecycle state is unreadable (${errorText2(error49)}). Coder dispatch is refused (fail closed) until it is repaired, because it cannot be told whether the coder belongs to an epic wave. Remedy: ask the user to run \`/swarm epic status\` (diagnose) and \`/swarm epic close --abandon\` (repair).`)}if(!epic){let closingKey=null;try{let record2=_internals53.inspectEpic(directory,null).record;if(record2?.status==="closing")closingKey=record2.epicKey}catch(error49){return reject("EPIC_STATE_UNREADABLE",`Epic Mode is enabled and an epic sentinel exists, but the epic's lifecycle state could not be read to determine whether a close is in progress (${errorText2(error49)}). Coder dispatch is refused (fail closed). Remedy: ask the user to run \`/swarm epic status\` (diagnose) and \`/swarm epic close --abandon\` (repair).`)}if(closingKey!==null)return reject("EPIC_CLOSING",`Epic \`${closingKey}\` is closing (an interrupted \`/swarm epic close\`), so a coder dispatched now would settle with no Epic context and merge back onto the branch the close is stepping off. Remedy: ask the user to rerun \`/swarm epic close\`.`);return null}let branch=_internals53.checkEpicBranch(directory,epic);if(!branch.ok)return reject("EPIC_BRANCH_MISMATCH",branch.message.replace(/^EPIC_BRANCH_MISMATCH:\s*/,""));let taskId=typeof incomingTaskId==="string"?incomingTaskId.trim():"";if(taskId.length===0||!findPlanTask(plan,taskId))return reject("EPIC_TASK_UNKNOWN",`${taskId?`task ${taskId} is`:"the coder dispatch names no task that is"} not a task of the plan epic \`${epic.epicKey}\` runs, so it cannot be dispatched while the epic is open. Remedy: call epic_next_wave and dispatch only the task ids of the wave it returns.`);let wave=epic.activeWaveSeq===null?void 0:epic.waves.find((w)=>w.seq===epic.activeWaveSeq&&w.status==="issued");if(!wave){let inReview=Object.entries(epic.phases).filter(([,record2])=>record2.status==="review").map(([phase])=>Number(phase)).filter((phase)=>Number.isFinite(phase)),reviewNote=inReview.length>0?` Phase ${inReview[0]} is in review: to fix review findings, ${epicPhaseFixSteps(inReview[0])}`:"";return reject("EPIC_NO_ACTIVE_WAVE",`no wave of epic \`${epic.epicKey}\` is active, so the coder for task ${taskId} is refused. Remedy: call epic_next_wave — it closes the finished wave and issues the next one — and dispatch only the tasks it returns.${reviewNote}`)}if(!wave.taskIds.includes(taskId))return reject("EPIC_TASK_NOT_IN_ACTIVE_WAVE",`task ${taskId} is not in the active wave ${wave.seq} (tasks: ${list(wave.taskIds)}). While an epic is open, coders run only for the active wave's tasks. Remedy: dispatch the wave's tasks, finish each (Stage A → Stage B → update_task_status(completed)), then call epic_next_wave for the next wave.`);let frozen=wave.files[taskId]??[],extra=(liveBindingFiles??[]).filter((file2)=>!scopeContains(frozen,file2));if(extra.length>0)return reject("EPIC_WAVE_SCOPE_DRIFT",`task ${taskId}'s declared scope has path(s) outside the scope frozen when wave ${wave.seq} was issued (outside: ${list(extra)}; frozen: ${list(frozen)}). The wave's parallel safety was proven on the frozen scope, and a frozen scope never grows. Remedy, one of: (1) re-declare the task within the frozen scope (declare_scope replace_existing: true, no FILE: line outside it) and dispatch again; (2) if the task genuinely needs the extra paths, finish it within the frozen scope or close it (update_task_status closed), and add the extra work as a NEW pending task of the current phase (save_plan) — epic_next_wave plans it into a later wave with its own scope; (3) ask the user to end the epic (\`/swarm epic close --abandon\`).`);let isolate=epic.git.isRepo&&epic.config.isolation==="worktree",unresolved=wave.taskIds.filter((id)=>{let task=findPlanTask(plan,id);return task!==null&&!isResolved(task.status)}),parallel=!1;if(isolate&&unresolved.includes(taskId)&&unresolved.length>=2)try{parallel=computeEpicWaveVerdict(directory,plan,wave,unresolved).verdict==="all_disjoint"}catch{parallel=!1}return{kind:"allow",parallel,isolate,maxConcurrent:Math.max(1,epic.config.maxParallel)}}function resolveEpicGateTaskAttribution(directory,files){if(!_internals53.epicSentinelExists(directory))return{kind:"none"};let epic;try{epic=_internals53.getOpenEpic(directory)}catch(error49){return{kind:"unattributable",message:`EPIC STAGE A ATTRIBUTION: the epic's lifecycle state is unreadable (${errorText2(error49)}), so this gate run cannot be credited to a wave task. Ask the user to run \`/swarm epic status\` (diagnose) or \`/swarm epic close --abandon\` (repair).`}}if(!epic||epic.activeWaveSeq===null)return{kind:"none"};let wave=epic.waves.find((w)=>w.seq===epic.activeWaveSeq&&w.status==="issued");if(!wave||wave.taskIds.length<2)return{kind:"none"};let scopes=wave.taskIds.map((id)=>`${id}: ${list(wave.files[id]??[])}`).join("; "),checked=(files??[]).filter((file2)=>file2.trim()!=="");if(checked.length===0)return{kind:"unattributable",message:`EPIC STAGE A ATTRIBUTION: wave ${wave.seq} runs ${wave.taskIds.length} tasks at once, and this gate run names no files, so it cannot be credited to one task. Re-run it with \`files\` set to ONE task's changed files (frozen scopes — ${scopes}).`};let relative12=checked.map((file2)=>path54.isAbsolute(file2)?path54.relative(directory,file2):file2),owners=wave.taskIds.filter((id)=>relative12.every((file2)=>scopeContains(wave.files[id]??[],file2)));if(owners.length===1)return{kind:"task",taskId:owners[0]};return{kind:"unattributable",message:owners.length===0?`EPIC STAGE A ATTRIBUTION: no task of wave ${wave.seq} owns every checked file (${list(relative12)}), so this gate run is credited to no task. Run the gate once per task, with \`files\` limited to that task's frozen scope (${scopes}).`:`EPIC STAGE A ATTRIBUTION: the checked files (${list(relative12)}) fall inside the frozen scope of several wave-${wave.seq} tasks (${list(owners)}), so this gate run is credited to no task. Run it with files only one task owns (${scopes}).`}}function resolveEpicPrFeedbackConflict(directory,declaredFiles){if(!_internals53.epicSentinelExists(directory))return null;let epic;try{epic=_internals53.getOpenEpic(directory)}catch(error49){return{code:"EPIC_STATE_UNREADABLE",message:`the open epic's lifecycle state is unreadable (${errorText2(error49)}), so this PR-feedback coder cannot be checked against the running wave (fail closed). Ask the user to run \`/swarm epic status\`.`}}if(!epic||epic.activeWaveSeq===null)return null;let wave=epic.waves.find((w)=>w.seq===epic.activeWaveSeq&&w.status==="issued");if(!wave)return null;let declared=(declaredFiles??[]).filter((file2)=>file2.trim()!=="").map((file2)=>path54.isAbsolute(file2)?path54.relative(directory,file2):file2),owners=[];for(let taskId of wave.taskIds){let frozen=wave.files[taskId]??[];if(declared.some((file2)=>scopeContains(frozen,file2)||frozen.some((entry)=>scopeContains([file2],entry))))owners.push(taskId)}if(owners.length===0)return null;return{code:"EPIC_PR_FEEDBACK_SCOPE_OVERLAP",message:`this PR-feedback coder's declared files (${list(declared)}) overlap the frozen scope of wave-${wave.seq} task(s) ${list(owners)}, which may be writing them right now. Let the wave finish (epic_next_wave closes it), then dispatch the PR-feedback coder.`}}var _internals53;var init_gate_policy=__esm(()=>{init_parallel_verdict();init_scope_binding();init_config_gate();init_epic_branch();init_lifecycle();init_next_wave_format();_internals53={epicSentinelExists,isEpicModeConfigEnabledForDirectory,getOpenEpic,inspectEpic,checkEpicBranch,computeParallelVerdict}});function canonicalProjectKey(directory){return canonicalRootKeyFresh(directory)}var defaultCanonicalRootRealpath,defaultCanonicalRootNativeRealpath;var init_canonical_project=__esm(()=>{init_canonical_root();defaultCanonicalRootRealpath=_internals8.realpathSync,defaultCanonicalRootNativeRealpath=_internals8.realpathSyncNative});function evictOldest(map2,cap){while(map2.size>=cap){let oldest=map2.keys().next().value;if(oldest===void 0)break;map2.delete(oldest)}}function hydrationProjectKey(directory){let memoKey=canonicalRootKeyLexical(directory),memoized=directoryKeyMemo.get(memoKey);if(memoized!==void 0)return memoized;let key=canonicalProjectKey(directory);if(!directoryKeyMemo.has(memoKey))evictOldest(directoryKeyMemo,MAX_DIRECTORY_KEY_MEMO);return directoryKeyMemo.set(memoKey,key),key}function beginHydrationScope(directory){let projectKey=hydrationProjectKey(directory),current=projectHydrationAuthorities.get(projectKey),generation=(current?.generation??0)+1;if(!current)evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let authorityEpoch=current?.authorityEpoch??nextHydrationAuthorityEpoch();return projectHydrationAuthorities.set(projectKey,{generation,authorityEpoch}),{projectKey,generation,authorityEpoch}}function currentHydrationGeneration(projectKey){return projectHydrationAuthorities.get(projectKey)?.generation??0}function captureCurrentHydrationAuthority(projectKey){let current=projectHydrationAuthorities.get(projectKey);if(current)return{projectKey,...current};let authorityEpoch=nextHydrationAuthorityEpoch();evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let record2={generation:0,authorityEpoch};return projectHydrationAuthorities.set(projectKey,record2),{projectKey,...record2}}function nextHydrationAuthorityEpoch(){if(hydrationAuthorityEpoch>=Number.MAX_SAFE_INTEGER)throw Error("hydration authority epoch exhausted");return hydrationAuthorityEpoch+=1,hydrationAuthorityEpoch}function isHydrationAuthorityCurrent(authority){let current=projectHydrationAuthorities.get(authority.projectKey);return current?.generation===authority.generation&&current.authorityEpoch===authority.authorityEpoch}function isHydrationScopeCurrent(scope){return isHydrationAuthorityCurrent(scope)}function nextSessionHydrationStamp(projectKey){return currentHydrationGeneration(projectKey)+1}function getRehydrationCache(projectKey){let entry=rehydrationCaches.get(projectKey),authority=projectHydrationAuthorities.get(projectKey);if(!entry||!authority||entry.authorityEpoch!==authority.authorityEpoch)return;return entry.cache}function setRehydrationCache(projectKey,cache2,authority){let cacheAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(cacheAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(cacheAuthority))return!1;if(!rehydrationCaches.has(projectKey))evictOldest(rehydrationCaches,MAX_TRACKED_PROJECTS);return rehydrationCaches.set(projectKey,{cache:cache2,authorityEpoch:cacheAuthority.authorityEpoch}),!0}function recordHydratedAggregateKeys(projectKey,keys,authority){let aggregateAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(aggregateAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(aggregateAuthority))return!1;if(!hydratedAggregateKeys.has(projectKey))evictOldest(hydratedAggregateKeys,MAX_TRACKED_PROJECTS);return hydratedAggregateKeys.set(projectKey,{keys:new Set(keys),authorityEpoch:aggregateAuthority.authorityEpoch}),!0}function hydratedAggregateKeysFor(projectKey,authority){let entry=hydratedAggregateKeys.get(projectKey),current=authority??projectHydrationAuthorities.get(projectKey);if(!entry||!current||entry.authorityEpoch!==current.authorityEpoch)return new Set;return entry.keys}function clearHydrationOwnershipState(){projectHydrationAuthorities.clear(),rehydrationCaches.clear(),hydratedAggregateKeys.clear(),directoryKeyMemo.clear()}var MAX_TRACKED_PROJECTS=32,MAX_DIRECTORY_KEY_MEMO=64,projectHydrationAuthorities,hydrationAuthorityEpoch=0,rehydrationCaches,hydratedAggregateKeys,directoryKeyMemo;var init_hydration_ownership=__esm(()=>{init_canonical_project();init_canonical_root();projectHydrationAuthorities=new Map,rehydrationCaches=new Map,hydratedAggregateKeys=new Map,directoryKeyMemo=new Map});function resolveEpicLearningSettings(config2){let learning=resolveEpicConfig(config2)?.learning,d=DEFAULT_EPIC_LEARNING_SETTINGS;return{enabled:learning?.enabled??d.enabled,decayPerEpic:learning?.decay_per_epic??d.decayPerEpic,halfLifeDays:learning?.half_life_days??d.halfLifeDays,hotExcess:learning?.hot_excess??d.hotExcess}}function emptyEpicLearning(){return{files:new Map,edges:new Map}}function isEpicLearningEmpty(stats2){return stats2.files.size===0&&stats2.edges.size===0}function cloneEpicLearning(stats2){let edges=new Map;for(let[from,targets]of stats2.edges)edges.set(from,new Map(targets));let files=new Map;for(let[file2,s]of stats2.files)files.set(file2,{...s});return{files,edges}}function isLearnablePath(file2){return file2.length>0&&file2!=="."&&file2!==".swarm"&&!file2.startsWith(".swarm/")&&!file2.startsWith("../")&&file2!==".."&&!file2.startsWith("/")}function learnablePaths(files){let out=new Set;for(let file2 of files){let normalized=normalizePath(file2);if(isLearnablePath(normalized))out.add(normalized)}return[...out]}function addFile(stats2,file2,alpha,beta){if(alpha===0&&beta===0)return;let current=stats2.files.get(file2)??{alpha:0,beta:0};current.alpha+=alpha,current.beta+=beta,stats2.files.set(file2,current)}function addEdge(stats2,from,to,weight){if(from===to||weight===0)return;let targets=stats2.edges.get(from)??new Map;targets.set(to,(targets.get(to)??0)+weight),stats2.edges.set(from,targets)}function undeclaredFiles(declaredScope,actualFiles){let declared=[...new Set(declaredScope.map(normalizePath))],actual=[...new Set(actualFiles.map(normalizePath))].sort(),covers=(d,f)=>d.length<=f.length&&pathsConflict(d,f);return actual.filter((f)=>!declared.some((d)=>covers(d,f)))}function reworkCharge(generation){let w=EPIC_LEARNING_INCIDENT_WEIGHTS,g=Number.isFinite(generation)?generation:0;return w.reworkPerGeneration*Math.min(Math.max(g-1,0),w.reworkMaxGenerations)}function count(value){return Number.isFinite(value)?Math.max(0,value):0}function epicLearningFromOutcomes(outcomes,options={}){let w=EPIC_LEARNING_INCIDENT_WEIGHTS,stats2=emptyEpicLearning();for(let outcome of outcomes){if(outcome.resolution==="removed")continue;let declared=learnablePaths(outcome.declared),undeclared=learnablePaths(outcome.undeclared).filter((file2)=>!declared.includes(file2)),all=[...declared,...undeclared],fileEntries=declared.filter((entry)=>!all.some((other)=>other!==entry&&other.length>entry.length&&pathsConflict(entry,other))&&!(options.isDirectory?.(entry)??!1));for(let file2 of fileEntries)addFile(stats2,file2,0,1);for(let file2 of undeclared){addFile(stats2,file2,w.undeclared,0);for(let from of declared)addEdge(stats2,from,file2,1)}let previous=outcome.previous&&options.learnedThroughWaveSeq!==void 0&&outcome.previous.waveSeq<=options.learnedThroughWaveSeq?outcome.previous:null,perDeclared=outcome.mergeFailure?w.mergeFailurePerDeclared:0;if(perDeclared+=w.stageBFailure*Math.max(0,count(outcome.stageBFailures)-count(previous?.stageBFailures)),perDeclared+=Math.max(0,reworkCharge(outcome.generation)-(previous?reworkCharge(previous.generation):0)),perDeclared+=w.reopen*Math.max(0,count(outcome.reopened)-count(previous?.reopened)),perDeclared>0)for(let file2 of fileEntries)addFile(stats2,file2,perDeclared,0)}return stats2}function mergeEpicLearning(a,b){let out=cloneEpicLearning(a);for(let[file2,s]of b.files)addFile(out,file2,s.alpha,s.beta);for(let[from,targets]of b.edges)for(let[to,weight]of targets)addEdge(out,from,to,weight);return out}function scaleEpicLearning(stats2,factor){let f=Number.isFinite(factor)?Math.min(Math.max(factor,0),1):1,out=emptyEpicLearning();for(let[file2,s]of stats2.files)out.files.set(file2,{alpha:s.alpha*f,beta:s.beta*f});for(let[from,targets]of stats2.edges){let scaled=new Map;for(let[to,weight]of targets)scaled.set(to,weight*f);out.edges.set(from,scaled)}return out}function epicTimeDecayFactor(updatedAtIso,nowMs,halfLifeDays){let updated=updatedAtIso?Date.parse(updatedAtIso):Number.NaN;if(!Number.isFinite(updated)||!Number.isFinite(nowMs))return 1;if(!(halfLifeDays>0))return 1;let days=Math.max(0,nowMs-updated)/DAY_MS;return 0.5**Math.floor(days/halfLifeDays)}function boundEpicLearning(stats2){let maxFiles=resolveRetentionCap("MAX_EPIC_LEARNING_FILES",MAX_EPIC_LEARNING_FILES),maxEdges=resolveRetentionCap("MAX_EPIC_LEARNING_EDGES",MAX_EPIC_LEARNING_EDGES),files=[...stats2.files].filter(([file2,s])=>isLearnablePath(file2)&&Number.isFinite(s.alpha)&&Number.isFinite(s.beta)&&s.alpha>=0&&s.beta>=0&&s.alpha+s.beta>=EPIC_LEARNING_DROP_BELOW).sort(([fa,a],[fb,b])=>b.alpha+b.beta-(a.alpha+a.beta)||fa.localeCompare(fb)).slice(0,maxFiles),edges=[];for(let[from,targets]of stats2.edges)for(let[to,weight]of targets)if(isLearnablePath(from)&&isLearnablePath(to)&&from!==to&&Number.isFinite(weight)&&weight>=EPIC_LEARNING_DROP_BELOW)edges.push([from,to,weight]);edges.sort((a,b)=>b[2]-a[2]||a[0].localeCompare(b[0])||a[1].localeCompare(b[1]));let out=emptyEpicLearning();for(let[file2,s]of files)out.files.set(file2,{...s});for(let[from,to,weight]of edges.slice(0,maxEdges))addEdge(out,from,to,weight);return out}function epicIncidentRate(stats2){return(PRIOR_A0+stats2.alpha)/(PRIOR_A0+PRIOR_B0+stats2.alpha+stats2.beta)}function isEpicHotFile(stats2,hotExcess){return stats2.alpha>=EPIC_HOT_MIN_ALPHA&&epicIncidentRate(stats2)-EPIC_LEARNING_PRIOR_MEAN>hotExcess}function strongestCoWriteInto(stats2){let strongest=new Map;for(let targets of stats2.edges.values())for(let[to,weight]of targets)if(weight>(strongest.get(to)??0))strongest.set(to,weight);return strongest}function epicHotIncidentMass(stats2,strongestCoWriter){return strongestCoWriter>=EPIC_EXPANSION_MIN_WEIGHT?Math.max(0,stats2.alpha-strongestCoWriter):stats2.alpha}function epicHotEvidence(stats2,file2){let s=stats2.files.get(file2)??{alpha:0,beta:0},countedAlpha=epicHotIncidentMass(s,strongestCoWriteInto(stats2).get(file2)??0);return{alpha:s.alpha,countedAlpha,beta:s.beta,rate:epicIncidentRate({alpha:countedAlpha,beta:s.beta})}}function epicHotFiles(stats2,hotExcess){let strongest=strongestCoWriteInto(stats2);return[...stats2.files].map(([file2,s])=>[file2,{alpha:epicHotIncidentMass(s,strongest.get(file2)??0),beta:s.beta}]).filter(([,s])=>isEpicHotFile(s,hotExcess)).sort(([fa,a],[fb,b])=>epicIncidentRate(b)-epicIncidentRate(a)||fa.localeCompare(fb)).map(([file2])=>file2)}function expandEpicScope(scope,coWrites){let declared=[...new Set(scope.map(normalizePath))];if(!coWrites||coWrites.size===0)return declared;let sums=new Map;for(let from of declared)for(let[to,weight]of coWrites.get(from)??[])sums.set(to,(sums.get(to)??0)+weight);let learned=[...sums].filter(([file2,weight])=>weight>=EPIC_EXPANSION_MIN_WEIGHT&&!declared.includes(file2)).map(([file2])=>file2).sort((a,b)=>a.localeCompare(b));return[...declared,...learned]}function summarizeEpicLearning(stats2,hotExcess,limit=10){let edges=[];for(let[from,targets]of stats2.edges)for(let[to,weight]of targets)edges.push({from,to,weight});return edges.sort((a,b)=>b.weight-a.weight||a.from.localeCompare(b.from)||a.to.localeCompare(b.to)),{files:stats2.files.size,edges:edges.length,hotFiles:epicHotFiles(stats2,hotExcess),topCoWrites:edges.slice(0,limit)}}var MAX_EPIC_LEARNING_FILES=2000,MAX_EPIC_LEARNING_EDGES=2000,EPIC_LEARNING_DROP_BELOW=0.05,EPIC_LEARNING_PRIOR_MEAN=0.1,EPIC_LEARNING_PRIOR_STRENGTH=2,EPIC_HOT_MIN_ALPHA=1,EPIC_EXPANSION_MIN_WEIGHT=1,PRIOR_A0,PRIOR_B0,DAY_MS=86400000,EPIC_LEARNING_INCIDENT_WEIGHTS,DEFAULT_EPIC_LEARNING_SETTINGS;var init_learning=__esm(()=>{init_caps();init_conflicts();init_config();PRIOR_A0=EPIC_LEARNING_PRIOR_MEAN*EPIC_LEARNING_PRIOR_STRENGTH,PRIOR_B0=(1-EPIC_LEARNING_PRIOR_MEAN)*EPIC_LEARNING_PRIOR_STRENGTH,EPIC_LEARNING_INCIDENT_WEIGHTS=Object.freeze({undeclared:1,mergeFailurePerDeclared:0.5,stageBFailure:0.25,reworkPerGeneration:0.25,reworkMaxGenerations:4,reopen:0.5}),DEFAULT_EPIC_LEARNING_SETTINGS=Object.freeze({enabled:!0,decayPerEpic:0.7,halfLifeDays:60,hotExcess:0.25})});import{createHash as createHash29}from"node:crypto";import*as fs31 from"node:fs";import*as path55 from"node:path";function errorText3(error49){return error49 instanceof Error?error49.message:String(error49)}function priorPath(directory){return path55.join(directory,EPIC_PRIOR_LEARNING_RELATIVE_PATH)}function posteriorPath(directory){return path55.join(directory,EPIC_POSTERIOR_RELATIVE_PATH)}function encodeStats(stats2){let files=[...stats2.files].map(([file2,s])=>({path:file2,alpha:s.alpha,beta:s.beta})).sort((a,b)=>a.path.localeCompare(b.path)),edges=[];for(let[from,targets]of stats2.edges)for(let[to,weight]of targets)edges.push({from,to,weight});return edges.sort((a,b)=>a.from.localeCompare(b.from)||a.to.localeCompare(b.to)),{files,edges}}function decodeStats(raw){let stats2=emptyEpicLearning();for(let entry of raw.files){let current=stats2.files.get(entry.path)??{alpha:0,beta:0};stats2.files.set(entry.path,{alpha:current.alpha+entry.alpha,beta:current.beta+entry.beta})}for(let edge of raw.edges){let targets=stats2.edges.get(edge.from)??new Map;targets.set(edge.to,(targets.get(edge.to)??0)+edge.weight),stats2.edges.set(edge.from,targets)}return boundEpicLearning(stats2)}function readBounded(filePath){let size;try{size=fs31.statSync(filePath).size}catch(error49){if(error49?.code==="ENOENT")return null;throw error49}if(size>MAX_LEARNING_FILE_BYTES)throw Error(`${filePath} exceeds ${MAX_LEARNING_FILE_BYTES} bytes`);return fs31.readFileSync(filePath,"utf-8")}function sha2563(text){return createHash29("sha256").update(text).digest("hex")}function directoryProbe(directory){return(entry)=>{try{return fs31.statSync(path55.join(directory,entry)).isDirectory()}catch{return!1}}}function readEpicPrior(directory){let raw;try{raw=readBounded(priorPath(directory))}catch(error49){return{status:"unreadable",reason:errorText3(error49),digest:null}}if(raw===null)return{status:"absent",digest:null};try{let parsed=priorSchema.safeParse(JSON.parse(raw));if(!parsed.success)return{status:"unreadable",reason:`invalid ${EPIC_PRIOR_LEARNING_RELATIVE_PATH}: ${parsed.error.issues[0]?.message??"schema mismatch"}`,digest:null};return{status:"ok",digest:sha2563(raw),prior:{updatedAt:parsed.data.updatedAt,importedFrom:parsed.data.importedFrom,mergedEpics:parsed.data.mergedEpics.slice(-EPIC_PRIOR_MERGED_EPICS_KEEP),stats:decodeStats(parsed.data)}}}catch(error49){return{status:"unreadable",reason:errorText3(error49),digest:null}}}function writeEpicPrior(directory,prior){let target=priorPath(directory);fs31.mkdirSync(path55.dirname(target),{recursive:!0});let payload={schema:"epic-learning-v1",updatedAt:prior.updatedAt,importedFrom:prior.importedFrom,mergedEpics:prior.mergedEpics.slice(-EPIC_PRIOR_MERGED_EPICS_KEEP),...encodeStats(boundEpicLearning(prior.stats))};atomicWriteSwarmFileSync(target,`${JSON.stringify(payload,null,2)}
704
704
  `)}function readEpicPosterior(directory){try{let raw=readBounded(posteriorPath(directory));if(raw===null)return null;let parsed=posteriorSchema.safeParse(JSON.parse(raw));if(!parsed.success)return null;return{epicKey:parsed.data.epicKey,token:parsed.data.token,priorDigest:parsed.data.priorDigest,createdAt:parsed.data.createdAt,lastAppliedWaveSeq:parsed.data.lastAppliedWaveSeq,base:{updatedAt:parsed.data.base.updatedAt,stats:decodeStats(parsed.data.base)},increments:decodeStats(parsed.data.increments)}}catch{return null}}function writeEpicPosterior(directory,posterior){let target=posteriorPath(directory);fs31.mkdirSync(path55.dirname(target),{recursive:!0});let payload={schema:"epic-posterior-v1",epicKey:posterior.epicKey,token:posterior.token,priorDigest:posterior.priorDigest,createdAt:posterior.createdAt,lastAppliedWaveSeq:posterior.lastAppliedWaveSeq,base:{updatedAt:posterior.base.updatedAt,...encodeStats(boundEpicLearning(posterior.base.stats))},increments:encodeStats(boundEpicLearning(posterior.increments))};atomicWriteSwarmFileSync(target,`${JSON.stringify(payload,null,2)}
705
705
  `)}function warnOnce(key,message){if(warnedKeys.has(key))return;if(warnedKeys.size>=MAX_WARNED_KEYS){let oldest=warnedKeys.values().next().value;if(oldest!==void 0)warnedKeys.delete(oldest)}warnedKeys.add(key),criticalWarn(message)}function decayedPriorStats(prior,settings,nowMs){return scaleEpicLearning(prior.stats,epicTimeDecayFactor(prior.updatedAt,nowMs,settings.halfLifeDays))}function loadEpicLearningView(directory,epic,settings,nowMs){if(!settings.enabled)return{source:"none",stats:emptyEpicLearning()};if(epic!==null){let posterior=readEpicPosterior(directory);if(posterior&&posterior.epicKey===epic.epicKey&&posterior.token===epic.token){let base=scaleEpicLearning(posterior.base.stats,epicTimeDecayFactor(posterior.base.updatedAt,nowMs,settings.halfLifeDays));return{source:"posterior",stats:boundEpicLearning(mergeEpicLearning(base,posterior.increments))}}}let read=readEpicPrior(directory);if(read.status==="unreadable")return warnOnce(`prior\x00${directory}`,`[epic/learning] the project prior is unreadable (${read.reason}); epics plan without learned signals until \`/swarm epic prior reset\` clears it.`),{source:"prior-unreadable",stats:emptyEpicLearning()};if(read.status==="absent")return{source:"none",stats:emptyEpicLearning()};return{source:"prior",stats:decayedPriorStats(read.prior,settings,nowMs)}}function initEpicPosterior(directory,record2,snapshot){writeEpicPosterior(directory,{epicKey:record2.epicKey,token:record2.token,priorDigest:record2.priorDigest,createdAt:record2.startedAt,lastAppliedWaveSeq:0,base:snapshot.status==="ok"?{updatedAt:snapshot.prior.updatedAt,stats:snapshot.prior.stats}:{updatedAt:record2.startedAt,stats:emptyEpicLearning()},increments:emptyEpicLearning()})}function posteriorFor(directory,record2){let existing=readEpicPosterior(directory);if(existing&&existing.epicKey===record2.epicKey&&existing.token===record2.token)return existing;let prior=readEpicPrior(directory);return{epicKey:record2.epicKey,token:record2.token,priorDigest:prior.digest,createdAt:record2.startedAt,lastAppliedWaveSeq:0,base:prior.status==="ok"?{updatedAt:prior.prior.updatedAt,stats:prior.prior.stats}:{updatedAt:record2.startedAt,stats:emptyEpicLearning()},increments:emptyEpicLearning()}}function applyClosedWavesToPosterior(directory,record2,settings){if(!settings.enabled)return{appliedWaves:[]};let posterior=posteriorFor(directory,record2),pending=record2.waves.filter((wave)=>wave.status==="closed"&&wave.seq>posterior.lastAppliedWaveSeq).map((wave)=>wave.seq).sort((a,b)=>a-b);if(pending.length===0)return{appliedWaves:[]};let applied=new Set(pending),outcomes=Object.values(record2.tasks??{}).filter((outcome)=>applied.has(outcome.waveSeq));return writeEpicPosterior(directory,{...posterior,lastAppliedWaveSeq:pending[pending.length-1],increments:boundEpicLearning(mergeEpicLearning(posterior.increments,epicLearningFromOutcomes(outcomes,{isDirectory:directoryProbe(directory),learnedThroughWaveSeq:posterior.lastAppliedWaveSeq})))}),{appliedWaves:pending}}function mergeEpicPosteriorIntoPrior(directory,record2,reportKey,settings,nowMs){let none={learnedFiles:0,learnedEdges:0,hotFiles:[]};if(!settings.enabled)return{status:"disabled",...none,detail:"learning is disabled (epic.learning.enabled: false)"};try{try{applyClosedWavesToPosterior(directory,record2,settings)}catch(error49){warn(`[epic/learning] posterior catch-up failed; merging from the epic record: ${errorText3(error49)}`)}let posterior=readEpicPosterior(directory),increments=posterior&&posterior.epicKey===record2.epicKey&&posterior.token===record2.token?posterior.increments:boundEpicLearning(epicLearningFromOutcomes(Object.values(record2.tasks??{}),{isDirectory:directoryProbe(directory)})),learnedEdges=0;for(let targets of increments.edges.values())learnedEdges+=targets.size;let learned={learnedFiles:increments.files.size,learnedEdges},read=readEpicPrior(directory);if(read.status==="unreadable")return{status:"prior-unreadable",...learned,hotFiles:[],detail:`the project prior is unreadable (${read.reason}); this epic's observations were not merged — clear it with \`/swarm epic prior reset\``};let prior=read.status==="ok"?read.prior:null;if(prior?.mergedEpics.includes(reportKey))return removePosterior(directory,record2),{status:"already-merged",...learned,hotFiles:epicHotFiles(prior.stats,settings.hotExcess).slice(0,10),detail:"already merged into the project prior"};if(isEpicLearningEmpty(increments)){if(prior)writeEpicPrior(directory,{...prior,mergedEpics:[...prior.mergedEpics,reportKey]});return removePosterior(directory,record2),{status:"nothing-to-learn",...learned,hotFiles:prior?epicHotFiles(prior.stats,settings.hotExcess).slice(0,10):[],detail:"no outcomes to learn from"}}let decayed=prior?scaleEpicLearning(decayedPriorStats(prior,settings,nowMs),settings.decayPerEpic):emptyEpicLearning(),stats2=boundEpicLearning(mergeEpicLearning(decayed,increments));return writeEpicPrior(directory,{updatedAt:new Date(nowMs).toISOString(),importedFrom:prior?.importedFrom??null,mergedEpics:[...prior?.mergedEpics??[],reportKey],stats:stats2}),removePosterior(directory,record2),{status:"merged",...learned,hotFiles:epicHotFiles(stats2,settings.hotExcess).slice(0,10),detail:"merged into the project prior"}}catch(error49){return{status:"failed",...none,detail:`merging into the project prior failed: ${errorText3(error49)}`}}}function removePosterior(directory,record2){let existing=readEpicPosterior(directory);if(existing&&existing.epicKey!==record2.epicKey)return;try{fs31.rmSync(posteriorPath(directory),{force:!0})}catch{}}function resetEpicPrior(directory,nowMs){let read=readEpicPrior(directory),nowIso2=new Date(nowMs).toISOString();try{return writeEpicPrior(directory,{updatedAt:nowIso2,importedFrom:read.status==="ok"&&read.prior.importedFrom?read.prior.importedFrom:{source:"reset",at:nowIso2,calibrationHotModules:0,divergenceRecords:0},mergedEpics:read.status==="ok"?read.prior.mergedEpics:[],stats:emptyEpicLearning()}),{status:"reset",hadPrior:read.status!=="absent"}}catch(error49){return{status:"failed",detail:errorText3(error49)}}}function readLegacyHotModules(directory){let raw=readBounded(path55.join(directory,LEGACY_CALIBRATION_RELATIVE_PATH));if(raw===null)return null;let parsed=JSON.parse(raw);if(!Array.isArray(parsed?.hotModuleAdditions))return[];return parsed.hotModuleAdditions.filter((entry)=>typeof entry==="string").slice(0,MAX_LEGACY_HOT_MODULES)}function readLegacyDivergence(directory){let filePath=path55.join(directory,LEGACY_DIVERGENCE_RELATIVE_PATH),size;try{size=fs31.statSync(filePath).size}catch(error49){if(error49?.code==="ENOENT")return null;throw error49}let text,truncated=!1;if(size>MAX_LEGACY_DIVERGENCE_BYTES){let fd=fs31.openSync(filePath,"r");try{let buffer=Buffer.alloc(MAX_LEGACY_DIVERGENCE_BYTES);fs31.readSync(fd,buffer,0,MAX_LEGACY_DIVERGENCE_BYTES,size-MAX_LEGACY_DIVERGENCE_BYTES),text=buffer.toString("utf-8"),truncated=!0}finally{fs31.closeSync(fd)}}else text=fs31.readFileSync(filePath,"utf-8");let tail=text.split(`
706
- `).filter((line)=>line.trim().length>0).slice(truncated?1:0).slice(-MAX_LEGACY_DIVERGENCE_RECORDS),records=[];for(let line of tail)try{let parsed=JSON.parse(line);if(parsed&&typeof parsed==="object")records.push(parsed)}catch{}let last=new Map;records.forEach((record2,index)=>{if(typeof record2.planId==="string"&&typeof record2.taskId==="string")last.set(`${record2.planId}\x00${record2.taskId}`,index)});let strings=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):[];return records.filter((record2,index)=>typeof record2.planId!=="string"||typeof record2.taskId!=="string"||last.get(`${record2.planId}\x00${record2.taskId}`)===index).map((record2)=>({declared:strings(record2.declaredScope),undeclared:strings(record2.undeclared)}))}function importLegacyEpicCalibrationOnce(directory,nowMs){try{let read=readEpicPrior(directory);if(read.status==="unreadable")return{status:"prior-unreadable"};if(read.status==="ok"&&read.prior.importedFrom!==null)return{status:"already-imported"};let hotModules=null;try{hotModules=readLegacyHotModules(directory)}catch(error49){warn(`[epic/learning] Epic v1 calibration.json unreadable; not imported: ${errorText3(error49)}`)}let divergence=null;try{divergence=readLegacyDivergence(directory)}catch(error49){warn(`[epic/learning] Epic v1 divergence.jsonl unreadable; not imported: ${errorText3(error49)}`)}if(hotModules===null&&divergence===null)return{status:"nothing-to-import"};let increments=epicLearningFromOutcomes((divergence??[]).map((record2,index)=>({taskId:`legacy-${index}`,phase:0,waveSeq:0,resolution:"completed",resolvedAt:"",generation:0,stageAFailures:0,stageBFailures:0,mergeFailure:null,declared:record2.declared,undeclared:record2.undeclared,attribution:"session",reopened:0,marker:null})),{isDirectory:directoryProbe(directory)}),base=read.status==="ok"?read.prior.stats:emptyEpicLearning(),stats2=mergeEpicLearning(base,increments);for(let file2 of learnablePaths(hotModules??[])){let current=stats2.files.get(file2)??{alpha:0,beta:0};stats2.files.set(file2,{alpha:Math.max(current.alpha,EPIC_LEGACY_HOT_MODULE_ALPHA),beta:current.beta})}let nowIso2=new Date(nowMs).toISOString(),importedFrom={source:"epic-v1-import",at:nowIso2,calibrationHotModules:hotModules?.length??0,divergenceRecords:divergence?.length??0};return writeEpicPrior(directory,{updatedAt:nowIso2,importedFrom,mergedEpics:read.status==="ok"?read.prior.mergedEpics:[],stats:boundEpicLearning(stats2)}),{status:"imported",calibrationHotModules:importedFrom.calibrationHotModules,divergenceRecords:importedFrom.divergenceRecords}}catch(error49){return{status:"failed",detail:errorText3(error49)}}}function describeEpicPriorMerge(result){switch(result.status){case"merged":return`Learning: merged ${result.learnedFiles} file statistic(s) and ${result.learnedEdges} learned co-write(s) into the project prior (\`${EPIC_PRIOR_LEARNING_DISPLAY_PATH}\`)${result.hotFiles.length>0?`; hot files: ${result.hotFiles.slice(0,5).join(", ")}${result.hotFiles.length>5?", …":""}`:"; no hot files"}. Project prior kept (it survives /swarm close; \`/swarm epic prior reset\` clears it).`;case"already-merged":return"Learning: already merged into the project prior. Project prior kept.";case"nothing-to-learn":return"Learning: this epic recorded no outcomes to learn from. Project prior kept.";case"disabled":return"Learning: disabled (`epic.learning.enabled: false`). Project prior kept unchanged.";default:return`Learning: ⚠️ ${result.detail}. Project prior kept unchanged.`}}var EPIC_PRIOR_LEARNING_RELATIVE_PATH,EPIC_PRIOR_LEARNING_DISPLAY_PATH=".swarm/epic-prior/learning.json",EPIC_POSTERIOR_RELATIVE_PATH,LEGACY_CALIBRATION_RELATIVE_PATH,LEGACY_DIVERGENCE_RELATIVE_PATH,EPIC_PRIOR_MERGED_EPICS_KEEP=50,MAX_LEARNING_FILE_BYTES=4194304,MAX_LEGACY_DIVERGENCE_BYTES=16777216,MAX_LEGACY_DIVERGENCE_RECORDS=1e4,MAX_LEGACY_HOT_MODULES=2000,EPIC_LEGACY_HOT_MODULE_ALPHA=2,MAX_WARNED_KEYS=64,fileEntrySchema,edgeEntrySchema,statsSchema,importedFromSchema,priorSchema,posteriorSchema,warnedKeys;var init_learning_store=__esm(()=>{init_zod();init_atomic_write();init_logger();init_learning();EPIC_PRIOR_LEARNING_RELATIVE_PATH=path55.join(".swarm","epic-prior","learning.json"),EPIC_POSTERIOR_RELATIVE_PATH=path55.join(".swarm","epic","posterior.json"),LEGACY_CALIBRATION_RELATIVE_PATH=path55.join(".swarm","epic","calibration.json"),LEGACY_DIVERGENCE_RELATIVE_PATH=path55.join(".swarm","epic","divergence.jsonl"),fileEntrySchema=exports_external.object({path:exports_external.string().min(1),alpha:exports_external.number().finite().min(0),beta:exports_external.number().finite().min(0)}).strict(),edgeEntrySchema=exports_external.object({from:exports_external.string().min(1),to:exports_external.string().min(1),weight:exports_external.number().finite().min(0)}).strict(),statsSchema=exports_external.object({files:exports_external.array(fileEntrySchema),edges:exports_external.array(edgeEntrySchema)}).strict(),importedFromSchema=exports_external.object({at:exports_external.string(),source:exports_external.enum(["epic-v1-import","reset"]),calibrationHotModules:exports_external.number().int().min(0),divergenceRecords:exports_external.number().int().min(0)}).strict(),priorSchema=statsSchema.extend({schema:exports_external.literal("epic-learning-v1"),updatedAt:exports_external.string(),importedFrom:importedFromSchema.nullable(),mergedEpics:exports_external.array(exports_external.string())}).strict(),posteriorSchema=exports_external.object({schema:exports_external.literal("epic-posterior-v1"),epicKey:exports_external.string().min(1),token:exports_external.string().min(1),priorDigest:exports_external.string().nullable(),createdAt:exports_external.string(),lastAppliedWaveSeq:exports_external.number().int().min(0),base:statsSchema.extend({updatedAt:exports_external.string()}).strict(),increments:statsSchema}).strict();warnedKeys=new Set});function isFullSha(value){return typeof value==="string"&&SHA_RE2.test(value)}function taskRefComponent(taskId){if(SAFE_COMPONENT_RE.test(taskId)&&!taskId.endsWith(".lock"))return taskId;return`_x${Buffer.from(taskId,"utf8").toString("hex")}`}function epicRefPrefix(epicKey){return assertSafeGitRefArg(`${EPIC_REFS_ROOT}/${epicKey}`,"epic ref prefix")}function epicBaseRef(epicKey){return`${epicRefPrefix(epicKey)}/base`}function epicWaveRef(epicKey,seq){return`${epicRefPrefix(epicKey)}/waves/${Math.trunc(seq)}`}function epicTaskRef(epicKey,taskId){return assertSafeGitRefArg(`${epicRefPrefix(epicKey)}/tasks/${taskRefComponent(taskId)}`,"epic task ref")}function readEpicRefs(directory,epicKey){let output=_internals54.gitExec(["for-each-ref",`--count=${MAX_EPIC_REFS}`,"--format=%(objectname) %(refname)",epicRefPrefix(epicKey)],directory),refs=new Map;for(let line of output.split(/\r?\n/)){let space=line.indexOf(" ");if(space<=0)continue;let sha=line.slice(0,space),name=line.slice(space+1).trim();if(isFullSha(sha)&&name.length>0)refs.set(name,sha)}return refs}function readOneRef(directory,ref){let sha=_internals54.gitExec(["for-each-ref","--count=1","--format=%(objectname)",ref],directory).trim().split(/\r?\n/)[0]??"";return isFullSha(sha)?sha:null}function writeEpicRef(directory,ref,sha,existing){if(!isFullSha(sha))throw Error(`not a full commit id: ${sha}`);if(assertSafeGitRefArg(ref,"epic ref write"),existing===sha)return"unchanged";try{return _internals54.gitExecOnce(["update-ref",ref,sha,existing??""],directory),existing===null?"created":"updated"}catch(error49){if(readOneRef(directory,ref)===sha)return existing===null?"created":"updated";throw error49}}function desiredEpicRefs(record2){let desired=new Map;if(!record2.git.isRepo)return desired;if(isFullSha(record2.git.baseCommit))desired.set(epicBaseRef(record2.epicKey),record2.git.baseCommit);for(let wave of record2.waves)if(wave.status==="closed"&&isFullSha(wave.closeHead))desired.set(epicWaveRef(record2.epicKey,wave.seq),wave.closeHead);for(let outcome of Object.values(record2.tasks)){let sha=outcome.marker?.sha;if(outcome.resolution==="completed"&&isFullSha(sha))desired.set(epicTaskRef(record2.epicKey,outcome.taskId),sha)}return desired}function syncEpicRefs(directory,record2){let existing=readEpicRefs(directory,record2.epicKey);for(let[ref,sha]of desiredEpicRefs(record2))writeEpicRef(directory,ref,sha,existing.get(ref)??null),existing.set(ref,sha);return existing}function isCommitAncestorOfHead(directory,sha){if(!isFullSha(sha))return!1;return _internals54.gitProbeExitCode(["merge-base","--is-ancestor",sha,"HEAD"],directory)===0}function deleteEpicRefs(directory,epicKey){let deleted=[],failed=[],refs;try{refs=readEpicRefs(directory,epicKey)}catch(error49){return{deleted,failed:[`${epicRefPrefix(epicKey)}/* (${error49 instanceof Error?error49.message:String(error49)})`]}}for(let[ref,sha]of refs)try{_internals54.gitExecOnce(["update-ref","-d",ref,sha],directory),deleted.push(ref)}catch{failed.push(ref)}return{deleted,failed}}function findTaskCommits(directory,range,planKey,taskIds){let wanted=new Map;for(let id of taskIds)wanted.set(scrubTaskIdForGitSubject(id),id);let found=new Map;if(wanted.size===0)return found;let output=_internals54.gitExec(["log","-z","--extended-regexp","--grep=^swarm\\(task [^)]+\\):",`--max-count=${MARKER_LOOKUP_MAX_COMMITS}`,MARKER_LOG_FORMAT,range,"--"],directory);for(let marker of parseTaskMarkerLog(output)){if(marker.planKey!==planKey)continue;let taskId=wanted.get(marker.taskId);if(taskId!==void 0&&!found.has(taskId))found.set(taskId,marker.sha)}return found}function epicCommitRange(record2){return isFullSha(record2.git.baseCommit)?`${record2.git.baseCommit}..HEAD`:"HEAD"}function planEpicTaskRefRepair(directory,record2,unrecorded){let repairs=[],recorded=new Map,adoptedUnrecorded=new Map,refs=readEpicRefs(directory,record2.epicKey),broken=[],reachable=(sha)=>isFullSha(sha)&&isCommitAncestorOfHead(directory,sha);for(let outcome of Object.values(record2.tasks)){if(outcome.resolution!=="completed")continue;let sha=outcome.marker?.sha??null;if(reachable(sha))repairs.push({taskId:outcome.taskId,status:"ok",sha,detail:"reachable from HEAD"});else broken.push(outcome.taskId)}let brokenUnrecorded=[];for(let taskId of unrecorded){if(record2.tasks[taskId])continue;let sha=refs.get(epicTaskRef(record2.epicKey,taskId));if(reachable(sha))repairs.push({taskId,status:"ok",sha,detail:"reachable from HEAD"});else brokenUnrecorded.push(taskId)}if(broken.length===0&&brokenUnrecorded.length===0)return{repairs,recorded,unrecorded:adoptedUnrecorded};let range=epicCommitRange(record2),markers=findTaskCommits(directory,range,record2.planKey,[...broken,...brokenUnrecorded]),needsAttention=(taskId)=>{repairs.push({taskId,status:"needs-attention",sha:null,detail:"no commit reachable from HEAD carries its work — commit it on the epic branch with the subject `swarm(task <id>): …` and the plan trailer, then rerun --repair-refs"})};for(let taskId of broken){let sha=markers.get(taskId)??null,how="its `swarm(task …)` commit for this plan",declared=(record2.tasks[taskId]?.declared??[]).filter((file2)=>file2.length>0&&!file2.startsWith(":"));if(!sha&&declared.length>0){let out=_internals54.gitExec(["log","--max-count=1","--format=%H",range,"--",...declared.slice(0,200).map((file2)=>`:(literal)${file2}`)],directory).trim();if(isFullSha(out))sha=out,how="the newest commit touching its declared files"}if(!sha){needsAttention(taskId);continue}recorded.set(taskId,sha),repairs.push({taskId,status:"repaired",sha,detail:`re-pointed to ${sha.slice(0,12)} (${how})`})}for(let taskId of brokenUnrecorded){let sha=markers.get(taskId);if(!sha){needsAttention(taskId);continue}adoptedUnrecorded.set(taskId,sha),repairs.push({taskId,status:"repaired",sha,detail:`adopted ${sha.slice(0,12)} (its \`swarm(task …)\` commit for this plan; completed outside a wave)`})}return{repairs,recorded,unrecorded:adoptedUnrecorded}}var EPIC_REFS_ROOT="refs/swarm/epics",MARKER_LOOKUP_MAX_COMMITS=2000,MAX_EPIC_REFS=20000,SHA_RE2,SAFE_COMPONENT_RE,_internals54;var init_markers=__esm(()=>{init_branch();init_safe_ref();init_git_once();init_plan_key();SHA_RE2=/^[0-9a-f]{40,64}$/,SAFE_COMPONENT_RE=/^[A-Za-z0-9][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)*$/,_internals54={gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),gitExecOnce,gitProbeExitCode}});function errorText4(error49){return error49 instanceof Error?error49.message:String(error49)}function readHead(directory){try{let head=_internals55.gitExec(["rev-parse","HEAD"],directory).trim();return SHA_RE3.test(head)?head:null}catch{return null}}function isSwarmPath(file2){return file2===".swarm"||file2.startsWith(".swarm/")}function changedFilesSinceBase(directory,baseHead){if(!baseHead||!SHA_RE3.test(baseHead))return null;try{let files=new Set,committed=_internals55.gitExec(["diff","--name-only","-z",baseHead,"HEAD"],directory);for(let file2 of committed.split("\x00"))if(file2.length>0)files.add(file2.replace(/\\/g,"/"));let records=_internals55.gitExec(["status","--porcelain=v1","-z","--untracked-files=all"],directory).split("\x00");for(let i=0;i<records.length;i+=1){let record2=records[i];if(record2.length<4)continue;let code=record2.slice(0,2);if(files.add(record2.slice(3).replace(/\\/g,"/")),code.includes("R")||code.includes("C"))i+=1}return[...files].filter((file2)=>!isSwarmPath(file2)).sort().slice(0,MAX_FALLBACK_FILES)}catch(error49){return warn(`[epic/wave-close] git fallback for divergence unavailable: ${errorText4(error49)}`),null}}function collectTaskAttribution(directory,callerSessionID,taskId){let collected=[],add=(session)=>{if(!session)return;try{collected.push(..._internals55.getModifiedFilesForTask(session,taskId))}catch{}},caller=callerSessionID?_internals55.getAgentSession(callerSessionID):void 0;add(caller);let projectKey=null;try{projectKey=_internals55.hydrationProjectKey(directory)}catch{projectKey=null}if(projectKey!==null)try{for(let[,session]of _internals55.listAgentSessions()){if(session===caller)continue;if(!session||!(session.modifiedFilesByTask instanceof Map))continue;if(session.owningProjectKey!==projectKey)continue;add(session)}}catch{}let canonical=new Set;for(let file2 of collected){let normalized=canonicalAttributionPath(file2,directory);if(normalized!==null)canonical.add(normalized)}return[...canonical].sort()}function lastTransitionAt(events,taskId,resolution){let at=null;for(let event of events){if(event.task_id!==taskId)continue;if(resolution==="removed"&&event.event_type==="task_removed"||event.event_type==="task_status_changed"&&event.to_status===resolution)at=event.timestamp}return at}function countReopens(events,taskId,sinceIso){let since=Date.parse(sinceIso);return events.filter((event)=>event.task_id===taskId&&event.event_type==="task_status_changed"&&event.from_status==="completed"&&event.to_status!=="completed"&&(!Number.isFinite(since)||Date.parse(event.timestamp)>=since)).length}async function readWorkflowCounts(directory,taskId){try{let workflow=(await _internals55.readTaskEvidence(directory,taskId))?.workflow;if(!workflow)return{generation:0,stageA:0,stageB:0};let history=Array.isArray(workflow.retryHistory)?workflow.retryHistory:[];return{generation:Number.isFinite(workflow.generation)?workflow.generation:0,stageA:history.filter((o)=>o==="stage_a_failed").length,stageB:history.filter((o)=>o==="stage_b_failed").length}}catch{return{generation:0,stageA:0,stageB:0}}}function resolutionOf(plan,taskId){for(let phase of plan.phases){let task=(phase.tasks??[]).find((t)=>t.id===taskId);if(!task)continue;if(task.status==="completed")return"completed";if(task.status==="closed")return"closed";return null}return"removed"}function markerFor(epic,taskId,resolution,closeHead,taskCommits){if(resolution!=="completed")return null;if(!epic.git.isRepo)return{ref:null,sha:null,provenance:"no-git"};let landed=taskCommits.get(taskId),sha=landed??closeHead;return{ref:isFullSha(sha)?epicTaskRef(epic.epicKey,taskId):null,sha,provenance:landed?"landing-commit":"wave-close-head"}}async function computeWaveClose(args2){let{directory,epic,wave,plan,sessionID,nowIso:nowIso2}=args2,isRepo=epic.git.isRepo,closeHead=isRepo?readHead(directory):null,events=[];try{events=await _internals55.readLedgerEvents(directory)}catch(error49){warn(`[epic/wave-close] plan ledger unreadable; outcome times fall back to now: ${errorText4(error49)}`)}let changed=isRepo?changedFilesSinceBase(directory,wave.baseHead):null,completedIds=wave.taskIds.filter((taskId)=>resolutionOf(plan,taskId)==="completed"),taskCommits=new Map;if(isRepo&&closeHead&&completedIds.length>0)try{taskCommits=_internals55.findTaskCommits(directory,isFullSha(wave.baseHead)?`${wave.baseHead}..HEAD`:epicCommitRange(epic),epic.planKey,completedIds)}catch(error49){warn(`[epic/wave-close] task commit lookup failed; markers fall back to the close HEAD: ${errorText4(error49)}`)}let outcomes=[],attributedAll=new Set;for(let taskId of wave.taskIds){let resolution=resolutionOf(plan,taskId)??"removed",declared=[...wave.files[taskId]??[]],counts=resolution==="removed"?{generation:0,stageA:0,stageB:0}:await readWorkflowCounts(directory,taskId),undeclared=[],attribution=isRepo?"unavailable":"no-git";if(resolution==="completed"){let attributed=collectTaskAttribution(directory,sessionID,taskId);for(let file2 of attributed)attributedAll.add(file2);let actual=null;if(attributed.length>0)actual=attributed,attribution="session";else if(changed!==null&&wave.taskIds.length===1)actual=changed,attribution="git-single-task";if(actual!==null)undeclared=undeclaredFiles(declared,actual)}let snapshot=wave.mergeFailures?.[taskId];outcomes.push({taskId,phase:wave.phase,waveSeq:wave.seq,resolution,resolvedAt:lastTransitionAt(events,taskId,resolution)??nowIso2,generation:counts.generation,stageAFailures:counts.stageA,stageBFailures:counts.stageB,mergeFailure:snapshot?{outcome:snapshot.outcome,stage:snapshot.stage}:null,declared,undeclared,attribution,reopened:countReopens(events,taskId,epic.startedAt),marker:markerFor(epic,taskId,resolution,closeHead,taskCommits)})}let waveUndeclared=[];if(changed!==null){let declaredAll=Object.values(wave.files).flat();waveUndeclared=undeclaredFiles(declaredAll,changed).filter((file2)=>!attributedAll.has(file2))}return{closeHead,outcomes,waveUndeclared}}function applyWaveClose(record2,seq,computation,nowIso2){let wave=record2.waves.find((w)=>w.seq===seq);if(!wave||wave.status!=="issued"||record2.activeWaveSeq!==seq)return record2;let tasks={...record2.tasks};for(let outcome of computation.outcomes){let before=Object.hasOwn(record2.tasks,outcome.taskId)?record2.tasks[outcome.taskId]:void 0;tasks[outcome.taskId]=before&&before.waveSeq!==outcome.waveSeq?{...outcome,previous:{waveSeq:before.waveSeq,generation:before.generation,stageBFailures:before.stageBFailures,reopened:before.reopened}}:outcome}return{...record2,activeWaveSeq:null,tasks,waves:record2.waves.map((w)=>w.seq===seq?{...w,status:"closed",closedAt:nowIso2,closeHead:computation.closeHead,undeclared:computation.waveUndeclared}:w)}}function recordEpicWaveLearning(args2){let settings=resolveEpicLearningSettings(args2.config);if(!settings.enabled)return[];try{return _internals55.applyClosedWavesToPosterior(args2.directory,args2.record,settings).appliedWaves}catch(error49){return criticalWarn(`[epic/wave-close] learning update failed (the wave flow continues; the next wave close catches it up): ${errorText4(error49)}`),[]}}function releaseWaveAttribution(directory,sessionID,taskIds){let sessions=new Set,caller=sessionID?_internals55.getAgentSession(sessionID):void 0;if(caller)sessions.add(caller);try{let projectKey=_internals55.hydrationProjectKey(directory);for(let[,session]of _internals55.listAgentSessions())if(session&&session.owningProjectKey===projectKey)sessions.add(session)}catch{}for(let session of sessions)for(let taskId of taskIds)try{_internals55.resetModifiedFilesForTask(session,taskId,{remove:!0})}catch{}}var MAX_FALLBACK_FILES=2000,SHA_RE3,_internals55;var init_wave_close=__esm(()=>{init_gate_evidence();init_branch();init_ledger();init_hydration_ownership();init_state();init_logger();init_path();init_learning();init_learning_store();init_markers();SHA_RE3=/^[0-9a-f]{7,64}$/,_internals55={gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),readTaskEvidence,readLedgerEvents,listAgentSessions:()=>swarmState.agentSessions.entries(),getAgentSession,getModifiedFilesForTask,resetModifiedFilesForTask,hydrationProjectKey,applyClosedWavesToPosterior,findTaskCommits}});import*as fs32 from"node:fs";import*as path56 from"node:path";function errorText5(error49){return error49 instanceof Error?error49.message:String(error49)}function isSwarmStatePath(file2){let normalized=file2.replace(/\\/g,"/");return normalized===".swarm"||normalized.startsWith(".swarm/")||normalized.includes("/.swarm/")||normalized.endsWith("/.swarm")}function caseKey(file2){return process.platform==="win32"?file2.toLowerCase():file2}function listDirtyEntries(directory){let output=_internals56.gitExec(["status","--porcelain=v1","-z","--untracked-files=all"],directory),entries=[],records=output.split("\x00");for(let i=0;i<records.length;i+=1){let record2=records[i];if(record2.length<4)continue;let code=record2.slice(0,2),file2=record2.slice(3).replace(/\\/g,"/"),origin;if(code.includes("R")||code.includes("C"))i+=1,origin=records[i]?.replace(/\\/g,"/");if(isSwarmStatePath(file2))continue;if(entries.push({path:file2,untracked:code==="??",needsAdd:code[1]!==" ",...origin?{origin}:{}}),entries.length>=MAX_DIRTY_ENTRIES)break}return entries}function coveredBy(file2,declared){let key=caseKey(file2);return declared.some((entry)=>{let d=caseKey(entry.replace(/\\/g,"/").replace(/\/+$/,""));return d.length>0&&(key===d||key.startsWith(`${d}/`))})}function literal2(file2){return`:(literal)${file2}`}function readIndexEntries(directory,files){let entries=new Map;for(let i=0;i<files.length;i+=PATHSPEC_CHUNK){let out=_internals56.gitExec(["ls-files","-s","-z","--",...files.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);for(let record2 of out.split("\x00")){let tab=record2.indexOf("\t");if(tab<0)continue;let[mode,sha,stage]=record2.slice(0,tab).split(" ");if(stage!=="0")continue;entries.set(record2.slice(tab+1),`${mode} ${sha}`)}}return entries}function restoreIndexEntries(directory,files,before){for(let i=0;i<files.length;i+=PATHSPEC_CHUNK)_internals56.gitExecOnce(["reset","-q","--",...files.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);let after=readIndexEntries(directory,files);for(let file2 of files){let wanted=before.get(file2),actual=after.get(file2);if(wanted===actual)continue;if(wanted){let[mode,sha]=wanted.split(" ");_internals56.gitExecOnce(["update-index","--cacheinfo",`${mode},${sha},${file2}`],directory)}else _internals56.gitExecOnce(["update-index","--force-remove","--",file2],directory)}}function commitPaths(directory,message,files,toAdd){let base=["-c","commit.gpgsign=false","commit","--only","--no-verify","-m",message],pathspecs=files.map(literal2),inlineBytes=pathspecs.reduce((sum,p)=>sum+Buffer.byteLength(p,"utf-8")+1,0),before=readIndexEntries(directory,files);try{for(let i=0;i<toAdd.length;i+=PATHSPEC_CHUNK)_internals56.gitExecOnce(["add","-A","--",...toAdd.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);if(inlineBytes<=COMMIT_ARGV_PATHSPEC_BUDGET_BYTES)_internals56.gitExecOnce([...base,"--",...pathspecs],directory);else{let gitPath=_internals56.gitExec(["rev-parse","--git-path",`swarm-epic-residue-${process.pid}-${_internals56.now()}`],directory).trim(),specFile=path56.resolve(directory,gitPath);try{fs32.writeFileSync(specFile,`${pathspecs.join("\x00")}\x00`,"utf-8"),_internals56.gitExecOnce([...base,`--pathspec-from-file=${specFile}`,"--pathspec-file-nul"],directory)}finally{try{fs32.rmSync(specFile,{force:!0})}catch{}}}}catch(error49){try{restoreIndexEntries(directory,files,before)}catch(restoreError){criticalWarn(`[epic] could not restore the index after a failed residue commit (${errorText5(restoreError)}); check \`git status\` for: ${files.slice(0,10).join(", ")}`)}throw error49}try{let head=_internals56.gitExec(["rev-parse","HEAD"],directory).trim();return/^[0-9a-f]{40,64}$/.test(head)?head:null}catch{return null}}function commitTaskResidue(args2){let wanted=new Set;for(let candidate of args2.candidates)if(typeof candidate==="string"&&candidate.length>0&&!candidate.startsWith(":")&&!isSwarmStatePath(candidate))wanted.add(caseKey(candidate.replace(/\\/g,"/")));let files=new Set,toAdd=new Set,scopes=(args2.scopes??[]).filter((entry)=>entry.length>0&&!entry.startsWith(":")),globLike=scopes.filter((entry)=>/[*?]/.test(entry));if(globLike.length>0)warn(`[epic] task ${args2.taskId}: declared scope entries are literal files or directories, never globs; ${globLike.slice(0,5).join(", ")} only match a path spelled exactly like that.`);for(let entry of args2.dirty){if(!wanted.has(caseKey(entry.path))&&!(scopes.length>0&&coveredBy(entry.path,scopes)))continue;if(files.add(entry.path),entry.needsAdd!==!1)toAdd.add(entry.path);if(entry.origin&&!isSwarmStatePath(entry.origin))files.add(entry.origin)}if(files.size===0)return{status:"nothing"};let list2=[...files].sort();try{return{status:"committed",sha:commitPaths(args2.directory,formatEpicTaskCommitMessage(args2.taskId,args2.epic.planKey,args2.label),list2,[...toAdd].sort()),files:list2}}catch(error49){return{status:"failed",error:errorText5(error49),files:list2}}}function inFlightWriterFiles(directory,exclude){let files=new Set;for(let[id,session]of _internals56.listAgentSessions()){if(exclude.has(id)||!session?.delegationActive)continue;if(!(session.modifiedFilesByTask instanceof Map))continue;for(let entries of session.modifiedFilesByTask.values())for(let file2 of entries){let canonical=canonicalAttributionPath(file2,directory);if(canonical!==null)files.add(caseKey(canonical))}}return files}function childSessionFiles(directory,ids){let files=[];for(let id of new Set(ids)){if(typeof id!=="string"||id.length===0)continue;let session=_internals56.getAgentSession(id);if(!session||!(session.modifiedFilesByTask instanceof Map))continue;for(let entries of session.modifiedFilesByTask.values())for(let file2 of entries){let canonical=canonicalAttributionPath(file2,directory);if(canonical!==null)files.push(canonical)}}return files}function declaredScopeOf(epic,taskId){return[...epic.waves.find((w)=>w.seq===epic.activeWaveSeq&&w.status==="issued")?.files[taskId]??[]]}async function commitEpicResidueAfterDelegation(request){try{if(!_internals56.epicSentinelExists(request.directory))return;let agent=stripKnownSwarmPrefix(request.agent);if(agent==="coder"||agent==="architect")return;let epic=_internals56.getOpenEpic(request.directory);if(!epic||!epic.git.isRepo)return;let taskIds=(await request.resolveTaskIds()).filter((id)=>_internals56.readPlanTaskRef(request.directory,id)!==null);if(taskIds.length===0)return;let branch=_internals56.checkEpicBranch(request.directory,epic);if(!branch.ok){criticalWarn(`[epic] ${agent} residue for task ${taskIds.join(", ")} NOT committed: ${branch.message}`);return}let childIds=await request.childSessionIds(),childFiles=childSessionFiles(request.directory,childIds),exclude=new Set([...childIds,request.sessionID].filter((id)=>typeof id==="string"&&id.length>0)),inFlight=inFlightWriterFiles(request.directory,exclude);await _internals56.serializeWithMergeBacks(()=>commitResidueForTasks(request,epic,agent,taskIds,childFiles,inFlight))}catch(error49){criticalWarn(`[epic] residue commit after a ${request.agent} delegation failed (non-fatal; epic_next_wave retries): ${errorText5(error49)}`)}}function commitResidueForTasks(request,epic,agent,taskIds,childFiles,inFlight=new Set){try{let dirty=listDirtyEntries(request.directory).filter((entry)=>!inFlight.has(caseKey(entry.path)));if(dirty.length===0)return;let remaining=dirty,commitStep=(taskId,label,candidates,scopes)=>{let result=commitTaskResidue({directory:request.directory,epic,taskId,label,candidates,scopes,dirty:remaining});if(result.status==="failed")return criticalWarn(`[epic] ${label} for task ${taskId} could not be committed (${result.error}); epic_next_wave retries before the next wave. Files: ${result.files.slice(0,10).join(", ")}`),!1;if(result.status==="committed"){let done=new Set(result.files.map(caseKey));remaining=remaining.filter((entry)=>!done.has(caseKey(entry.path)))}return!0};for(let[index,taskId]of taskIds.entries()){if(index===0&&childFiles.length>0&&!commitStep(taskId,`${agent} residue`,childFiles,[]))return;if(!commitStep(taskId,"residue",_internals56.collectTaskAttribution(request.directory,request.sessionID,taskId),declaredScopeOf(epic,taskId)))return}}catch(error49){criticalWarn(`[epic] residue commit after a ${request.agent} delegation failed (non-fatal; epic_next_wave retries): ${errorText5(error49)}`)}}function classifyDirtyBaseline(dirty){let unattributedTracked=[],unattributedUntracked=[];for(let entry of dirty)(entry.untracked?unattributedUntracked:unattributedTracked).push(entry.path);return{unattributedTracked,unattributedUntracked}}var COMMIT_ARGV_PATHSPEC_BUDGET_BYTES=24576,PATHSPEC_CHUNK=200,MAX_DIRTY_ENTRIES=5000,_internals56;var init_residue_commit=__esm(()=>{init_schema();init_branch();init_worktree_isolation();init_state();init_logger();init_path();init_epic_branch();init_git_once();init_lifecycle();init_plan_key();init_wave_close();_internals56={epicSentinelExists,getOpenEpic,readPlanTaskRef,checkEpicBranch,collectTaskAttribution,getAgentSession,listAgentSessions:()=>swarmState.agentSessions.entries(),gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),gitExecOnce,serializeWithMergeBacks:(task)=>runSerializedWithMergeBacks(task),now:()=>Date.now()}});function normalizeToolName(toolName){if(!toolName)return;return toolName.replace(NAMESPACE_PREFIX_PATTERN,"")}function normalizeToolNameLowerCase(toolName){return toolName.replace(NAMESPACE_PREFIX_PATTERN,"").toLowerCase()}function isTaskToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.task$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="task"}var NAMESPACE_PREFIX_PATTERN;var init_normalize_tool_name=__esm(()=>{NAMESPACE_PREFIX_PATTERN=/^[^:]+[:.]/});function declaresWindowsWrapper(command){return CMD_WRAPPER_DECLARATION.test(command)||PS_WRAPPER_DECLARATION.test(command)}function declaresWindowsWrapperLoose(command){return declaresWindowsWrapper(command)||PS_WRAPPER_LOOSE.test(command)}var CMD_SWITCH,CMD_WRAPPER_DECLARATION,PS_WRAPPER_DECLARATION,PS_WRAPPER_LOOSE,CMD_BUILTIN_PREFIX,CMD_STRIP_PREFIX,PS_STRIP_PREFIX;var init_shell_executor_context=__esm(()=>{CMD_SWITCH=String.raw`\/[a-z](?::(?:on|off))?`,CMD_WRAPPER_DECLARATION=new RegExp(String.raw`(?:^|[;|&\n])\s*cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/c(?:\s|$)`,"i"),PS_WRAPPER_DECLARATION=/(?:^|[;|&\n])\s*(?:powershell|pwsh)(?:\.exe)?\s+(?:-[A-Za-z]+\s+)*-command(?:\s|$)/i,PS_WRAPPER_LOOSE=/(?:^|\|)\s*(?:powershell|pwsh)(?:\.exe)?\s+-/i;CMD_BUILTIN_PREFIX=new RegExp(String.raw`(?:(?:^|\s)(?:if\s+(?:not\s+)?exist\s+(?:"[^"]*"|\S+)\s+)|(?:^|[;|&\n])\s*cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/c\s+|(?:^|\s)(?:call|start)\s+)*`,"i"),CMD_STRIP_PREFIX=new RegExp(String.raw`^cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/[ck]\s+`,"i"),PS_STRIP_PREFIX=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-[A-Za-z]+\s+)*-(?:command|c)\s+/i});import*as fsSync6 from"node:fs";import*as path57 from"node:path";function dcNormalizeCommand(cmd){let s=cmd.normalize("NFKC");return s=s.replace(/`(.)/g,"$1"),s=s.replace(/\^([a-zA-Z0-9 ])/g,"$1"),s=s.replace(/""/g,""),s=s.replace(/''/g,""),s}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=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].trim();let evalMatch=/^eval\s+(.+)$/is.exec(t);if(evalMatch)return evalMatch[1].replace(/^["']|["']$/g,"").trim();let prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??/^env(?:\s+[A-Za-z_][A-Za-z0-9_]*=[^\s]*)*\s+(.+)$/is.exec(t)??/^nice\s+(?:-n\s+\d+\s+)?(.+)$/is.exec(t);if(prefixMatch)return prefixMatch[1].trim();let wslMatch=/^wsl(?:\.exe)?\s+(?:-e|--)\s+(.+)$/is.exec(t);if(wslMatch)return wslMatch[1].trim();let scriptBlockMatch=/^&\s*\{(.+)\}$/s.exec(t);if(scriptBlockMatch)return scriptBlockMatch[1].trim();let iexMatch=/^(?:Invoke-Expression|iex)\s+(.+)$/is.exec(t);if(iexMatch)return iexMatch[1].replace(/^["'`]|["'`]$/g,"").trim();let invokeCommandMatch=/^Invoke-Command\s+.*-ScriptBlock\s*\{(.+)\}$/is.exec(t);if(invokeCommandMatch)return invokeCommandMatch[1].trim();let callMatch=/^call\s+(.+)$/is.exec(t);if(callMatch)return callMatch[1].trim();return null}function dcUnwrapWrappers(cmd){let current=cmd.trim();for(let depth=0;depth<DC_MAX_UNWRAP_DEPTH;depth++){let inner=dcStripOneWrapper(current);if(inner===null||inner===current)break;current=inner.trim()}return current}function dcSplitSegments(cmd){let segments=[],current="",inDoubleQuote=!1,inSingleQuote=!1;for(let i=0;i<cmd.length;i++){let ch=cmd[i],next=cmd[i+1];if(ch==='"'&&!inSingleQuote){inDoubleQuote=!inDoubleQuote,current+=ch;continue}if(ch==="'"&&!inDoubleQuote){inSingleQuote=!inSingleQuote,current+=ch;continue}if(!inDoubleQuote&&!inSingleQuote){if(ch==="&"&&next==="&"||ch==="|"&&next==="|"){segments.push(current.trim()),current="",i++;continue}if(ch==="|"||ch===";"||ch===`
706
+ `).filter((line)=>line.trim().length>0).slice(truncated?1:0).slice(-MAX_LEGACY_DIVERGENCE_RECORDS),records=[];for(let line of tail)try{let parsed=JSON.parse(line);if(parsed&&typeof parsed==="object")records.push(parsed)}catch{}let last=new Map;records.forEach((record2,index)=>{if(typeof record2.planId==="string"&&typeof record2.taskId==="string")last.set(`${record2.planId}\x00${record2.taskId}`,index)});let strings=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):[];return records.filter((record2,index)=>typeof record2.planId!=="string"||typeof record2.taskId!=="string"||last.get(`${record2.planId}\x00${record2.taskId}`)===index).map((record2)=>({declared:strings(record2.declaredScope),undeclared:strings(record2.undeclared)}))}function importLegacyEpicCalibrationOnce(directory,nowMs){try{let read=readEpicPrior(directory);if(read.status==="unreadable")return{status:"prior-unreadable"};if(read.status==="ok"&&read.prior.importedFrom!==null)return{status:"already-imported"};let hotModules=null;try{hotModules=readLegacyHotModules(directory)}catch(error49){warn(`[epic/learning] Epic v1 calibration.json unreadable; not imported: ${errorText3(error49)}`)}let divergence=null;try{divergence=readLegacyDivergence(directory)}catch(error49){warn(`[epic/learning] Epic v1 divergence.jsonl unreadable; not imported: ${errorText3(error49)}`)}if(hotModules===null&&divergence===null)return{status:"nothing-to-import"};let increments=epicLearningFromOutcomes((divergence??[]).map((record2,index)=>({taskId:`legacy-${index}`,phase:0,waveSeq:0,resolution:"completed",resolvedAt:"",generation:0,stageAFailures:0,stageBFailures:0,mergeFailure:null,declared:record2.declared,undeclared:record2.undeclared,attribution:"session",reopened:0,marker:null})),{isDirectory:directoryProbe(directory)}),base=read.status==="ok"?read.prior.stats:emptyEpicLearning(),stats2=mergeEpicLearning(base,increments);for(let file2 of learnablePaths(hotModules??[])){let current=stats2.files.get(file2)??{alpha:0,beta:0};stats2.files.set(file2,{alpha:Math.max(current.alpha,EPIC_LEGACY_HOT_MODULE_ALPHA),beta:current.beta})}let nowIso2=new Date(nowMs).toISOString(),importedFrom={source:"epic-v1-import",at:nowIso2,calibrationHotModules:hotModules?.length??0,divergenceRecords:divergence?.length??0};return writeEpicPrior(directory,{updatedAt:nowIso2,importedFrom,mergedEpics:read.status==="ok"?read.prior.mergedEpics:[],stats:boundEpicLearning(stats2)}),{status:"imported",calibrationHotModules:importedFrom.calibrationHotModules,divergenceRecords:importedFrom.divergenceRecords}}catch(error49){return{status:"failed",detail:errorText3(error49)}}}function describeEpicPriorMerge(result){switch(result.status){case"merged":return`Learning: merged ${result.learnedFiles} file statistic(s) and ${result.learnedEdges} learned co-write(s) into the project prior (\`${EPIC_PRIOR_LEARNING_DISPLAY_PATH}\`)${result.hotFiles.length>0?`; hot files: ${result.hotFiles.slice(0,5).join(", ")}${result.hotFiles.length>5?", …":""}`:"; no hot files"}. Project prior kept (it survives /swarm close; \`/swarm epic prior reset\` clears it).`;case"already-merged":return"Learning: already merged into the project prior. Project prior kept.";case"nothing-to-learn":return"Learning: this epic recorded no outcomes to learn from. Project prior kept.";case"disabled":return"Learning: disabled (`epic.learning.enabled: false`). Project prior kept unchanged.";default:return`Learning: ⚠️ ${result.detail}. Project prior kept unchanged.`}}var EPIC_PRIOR_LEARNING_RELATIVE_PATH,EPIC_PRIOR_LEARNING_DISPLAY_PATH=".swarm/epic-prior/learning.json",EPIC_POSTERIOR_RELATIVE_PATH,LEGACY_CALIBRATION_RELATIVE_PATH,LEGACY_DIVERGENCE_RELATIVE_PATH,EPIC_PRIOR_MERGED_EPICS_KEEP=50,MAX_LEARNING_FILE_BYTES=4194304,MAX_LEGACY_DIVERGENCE_BYTES=16777216,MAX_LEGACY_DIVERGENCE_RECORDS=1e4,MAX_LEGACY_HOT_MODULES=2000,EPIC_LEGACY_HOT_MODULE_ALPHA=2,MAX_WARNED_KEYS=64,fileEntrySchema,edgeEntrySchema,statsSchema,importedFromSchema,priorSchema,posteriorSchema,warnedKeys;var init_learning_store=__esm(()=>{init_zod();init_atomic_write();init_logger();init_learning();EPIC_PRIOR_LEARNING_RELATIVE_PATH=path55.join(".swarm","epic-prior","learning.json"),EPIC_POSTERIOR_RELATIVE_PATH=path55.join(".swarm","epic","posterior.json"),LEGACY_CALIBRATION_RELATIVE_PATH=path55.join(".swarm","epic","calibration.json"),LEGACY_DIVERGENCE_RELATIVE_PATH=path55.join(".swarm","epic","divergence.jsonl"),fileEntrySchema=exports_external.object({path:exports_external.string().min(1),alpha:exports_external.number().finite().min(0),beta:exports_external.number().finite().min(0)}).strict(),edgeEntrySchema=exports_external.object({from:exports_external.string().min(1),to:exports_external.string().min(1),weight:exports_external.number().finite().min(0)}).strict(),statsSchema=exports_external.object({files:exports_external.array(fileEntrySchema),edges:exports_external.array(edgeEntrySchema)}).strict(),importedFromSchema=exports_external.object({at:exports_external.string(),source:exports_external.enum(["epic-v1-import","reset"]),calibrationHotModules:exports_external.number().int().min(0),divergenceRecords:exports_external.number().int().min(0)}).strict(),priorSchema=statsSchema.extend({schema:exports_external.literal("epic-learning-v1"),updatedAt:exports_external.string(),importedFrom:importedFromSchema.nullable(),mergedEpics:exports_external.array(exports_external.string())}).strict(),posteriorSchema=exports_external.object({schema:exports_external.literal("epic-posterior-v1"),epicKey:exports_external.string().min(1),token:exports_external.string().min(1),priorDigest:exports_external.string().nullable(),createdAt:exports_external.string(),lastAppliedWaveSeq:exports_external.number().int().min(0),base:statsSchema.extend({updatedAt:exports_external.string()}).strict(),increments:statsSchema}).strict();warnedKeys=new Set});function isFullSha(value){return typeof value==="string"&&SHA_RE2.test(value)}function taskRefComponent(taskId){if(SAFE_COMPONENT_RE.test(taskId)&&!taskId.endsWith(".lock"))return taskId;return`_x${Buffer.from(taskId,"utf8").toString("hex")}`}function epicRefPrefix(epicKey){return assertSafeGitRefArg(`${EPIC_REFS_ROOT}/${epicKey}`,"epic ref prefix")}function epicBaseRef(epicKey){return`${epicRefPrefix(epicKey)}/base`}function epicWaveRef(epicKey,seq){return`${epicRefPrefix(epicKey)}/waves/${Math.trunc(seq)}`}function epicTaskRef(epicKey,taskId){return assertSafeGitRefArg(`${epicRefPrefix(epicKey)}/tasks/${taskRefComponent(taskId)}`,"epic task ref")}function readEpicRefs(directory,epicKey){let output=_internals54.gitExec(["for-each-ref",`--count=${MAX_EPIC_REFS}`,"--format=%(objectname) %(refname)",epicRefPrefix(epicKey)],directory),refs=new Map;for(let line of output.split(/\r?\n/)){let space=line.indexOf(" ");if(space<=0)continue;let sha=line.slice(0,space),name=line.slice(space+1).trim();if(isFullSha(sha)&&name.length>0)refs.set(name,sha)}return refs}function readOneRef(directory,ref){let sha=_internals54.gitExec(["for-each-ref","--count=1","--format=%(objectname)",ref],directory).trim().split(/\r?\n/)[0]??"";return isFullSha(sha)?sha:null}function writeEpicRef(directory,ref,sha,existing){if(!isFullSha(sha))throw Error(`not a full commit id: ${sha}`);if(assertSafeGitRefArg(ref,"epic ref write"),existing===sha)return"unchanged";try{return _internals54.gitExecOnce(["update-ref",ref,sha,existing??""],directory),existing===null?"created":"updated"}catch(error49){if(readOneRef(directory,ref)===sha)return existing===null?"created":"updated";throw error49}}function desiredEpicRefs(record2){let desired=new Map;if(!record2.git.isRepo)return desired;if(isFullSha(record2.git.baseCommit))desired.set(epicBaseRef(record2.epicKey),record2.git.baseCommit);for(let wave of record2.waves)if(wave.status==="closed"&&isFullSha(wave.closeHead))desired.set(epicWaveRef(record2.epicKey,wave.seq),wave.closeHead);for(let outcome of Object.values(record2.tasks)){let sha=outcome.marker?.sha;if(outcome.resolution==="completed"&&isFullSha(sha))desired.set(epicTaskRef(record2.epicKey,outcome.taskId),sha)}return desired}function syncEpicRefs(directory,record2){let existing=readEpicRefs(directory,record2.epicKey);for(let[ref,sha]of desiredEpicRefs(record2))writeEpicRef(directory,ref,sha,existing.get(ref)??null),existing.set(ref,sha);return existing}function isCommitAncestorOfHead(directory,sha){if(!isFullSha(sha))return!1;return _internals54.gitProbeExitCode(["merge-base","--is-ancestor",sha,"HEAD"],directory)===0}function deleteEpicRefs(directory,epicKey){let deleted=[],failed=[],refs;try{refs=readEpicRefs(directory,epicKey)}catch(error49){return{deleted,failed:[`${epicRefPrefix(epicKey)}/* (${error49 instanceof Error?error49.message:String(error49)})`]}}for(let[ref,sha]of refs)try{_internals54.gitExecOnce(["update-ref","-d",ref,sha],directory),deleted.push(ref)}catch{failed.push(ref)}return{deleted,failed}}function findTaskCommits(directory,range,planKey,taskIds){let wanted=new Map;for(let id of taskIds)wanted.set(scrubTaskIdForGitSubject(id),id);let found=new Map;if(wanted.size===0)return found;let output=_internals54.gitExec(["log","-z","--extended-regexp","--grep=^swarm\\(task [^)]+\\):",`--max-count=${MARKER_LOOKUP_MAX_COMMITS}`,MARKER_LOG_FORMAT,range,"--"],directory);for(let marker of parseTaskMarkerLog(output)){if(marker.planKey!==planKey)continue;let taskId=wanted.get(marker.taskId);if(taskId!==void 0&&!found.has(taskId))found.set(taskId,marker.sha)}return found}function epicCommitRange(record2){return isFullSha(record2.git.baseCommit)?`${record2.git.baseCommit}..HEAD`:"HEAD"}function planEpicTaskRefRepair(directory,record2,unrecorded){let repairs=[],recorded=new Map,adoptedUnrecorded=new Map,refs=readEpicRefs(directory,record2.epicKey),broken=[],reachable=(sha)=>isFullSha(sha)&&isCommitAncestorOfHead(directory,sha);for(let outcome of Object.values(record2.tasks)){if(outcome.resolution!=="completed")continue;let sha=outcome.marker?.sha??null;if(reachable(sha))repairs.push({taskId:outcome.taskId,status:"ok",sha,detail:"reachable from HEAD"});else broken.push(outcome.taskId)}let brokenUnrecorded=[];for(let taskId of unrecorded){if(record2.tasks[taskId])continue;let sha=refs.get(epicTaskRef(record2.epicKey,taskId));if(reachable(sha))repairs.push({taskId,status:"ok",sha,detail:"reachable from HEAD"});else brokenUnrecorded.push(taskId)}if(broken.length===0&&brokenUnrecorded.length===0)return{repairs,recorded,unrecorded:adoptedUnrecorded};let range=epicCommitRange(record2),markers=findTaskCommits(directory,range,record2.planKey,[...broken,...brokenUnrecorded]),needsAttention=(taskId)=>{repairs.push({taskId,status:"needs-attention",sha:null,detail:"no commit reachable from HEAD carries its work — commit it on the epic branch with the subject `swarm(task <id>): …` and the plan trailer, then rerun --repair-refs"})};for(let taskId of broken){let sha=markers.get(taskId)??null,how="its `swarm(task …)` commit for this plan",declared=(record2.tasks[taskId]?.declared??[]).filter((file2)=>file2.length>0&&!file2.startsWith(":"));if(!sha&&declared.length>0){let out=_internals54.gitExec(["log","--max-count=1","--format=%H",range,"--",...declared.slice(0,200).map((file2)=>`:(literal)${file2}`)],directory).trim();if(isFullSha(out))sha=out,how="the newest commit touching its declared files"}if(!sha){needsAttention(taskId);continue}recorded.set(taskId,sha),repairs.push({taskId,status:"repaired",sha,detail:`re-pointed to ${sha.slice(0,12)} (${how})`})}for(let taskId of brokenUnrecorded){let sha=markers.get(taskId);if(!sha){needsAttention(taskId);continue}adoptedUnrecorded.set(taskId,sha),repairs.push({taskId,status:"repaired",sha,detail:`adopted ${sha.slice(0,12)} (its \`swarm(task …)\` commit for this plan; completed outside a wave)`})}return{repairs,recorded,unrecorded:adoptedUnrecorded}}var EPIC_REFS_ROOT="refs/swarm/epics",MARKER_LOOKUP_MAX_COMMITS=2000,MAX_EPIC_REFS=20000,SHA_RE2,SAFE_COMPONENT_RE,_internals54;var init_markers=__esm(()=>{init_branch();init_safe_ref();init_git_once();init_plan_key();SHA_RE2=/^[0-9a-f]{40,64}$/,SAFE_COMPONENT_RE=/^[A-Za-z0-9][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)*$/,_internals54={gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),gitExecOnce,gitProbeExitCode}});function errorText4(error49){return error49 instanceof Error?error49.message:String(error49)}function readHead(directory){try{let head=_internals55.gitExec(["rev-parse","HEAD"],directory).trim();return SHA_RE3.test(head)?head:null}catch{return null}}function isSwarmPath(file2){return file2===".swarm"||file2.startsWith(".swarm/")}function changedFilesSinceBase(directory,baseHead){if(!baseHead||!SHA_RE3.test(baseHead))return null;try{let files=new Set,committed=_internals55.gitExec(["diff","--name-only","-z",baseHead,"HEAD"],directory);for(let file2 of committed.split("\x00"))if(file2.length>0)files.add(file2.replace(/\\/g,"/"));let records=_internals55.gitExec(["status","--porcelain=v1","-z","--untracked-files=all"],directory).split("\x00");for(let i=0;i<records.length;i+=1){let record2=records[i];if(record2.length<4)continue;let code=record2.slice(0,2);if(files.add(record2.slice(3).replace(/\\/g,"/")),code.includes("R")||code.includes("C"))i+=1}return[...files].filter((file2)=>!isSwarmPath(file2)).sort().slice(0,MAX_FALLBACK_FILES)}catch(error49){return warn(`[epic/wave-close] git fallback for divergence unavailable: ${errorText4(error49)}`),null}}function collectTaskAttribution(directory,callerSessionID,taskId){let collected=[],add=(session)=>{if(!session)return;try{collected.push(..._internals55.getModifiedFilesForTask(session,taskId))}catch{}},caller=callerSessionID?_internals55.getAgentSession(callerSessionID):void 0;add(caller);let projectKey=null;try{projectKey=_internals55.hydrationProjectKey(directory)}catch{projectKey=null}if(projectKey!==null)try{for(let[,session]of _internals55.listAgentSessions()){if(session===caller)continue;if(!session||!(session.modifiedFilesByTask instanceof Map))continue;if(session.owningProjectKey!==projectKey)continue;add(session)}}catch{}let canonical=new Set;for(let file2 of collected){let normalized=canonicalAttributionPath(file2,directory);if(normalized!==null)canonical.add(normalized)}return[...canonical].sort()}function lastTransitionAt(events,taskId,resolution){let at=null;for(let event of events){if(event.task_id!==taskId)continue;if(resolution==="removed"&&event.event_type==="task_removed"||event.event_type==="task_status_changed"&&event.to_status===resolution)at=event.timestamp}return at}function countReopens(events,taskId,sinceIso){let since=Date.parse(sinceIso);return events.filter((event)=>event.task_id===taskId&&event.event_type==="task_status_changed"&&event.from_status==="completed"&&event.to_status!=="completed"&&(!Number.isFinite(since)||Date.parse(event.timestamp)>=since)).length}async function readWorkflowCounts(directory,taskId){try{let workflow=(await _internals55.readTaskEvidence(directory,taskId))?.workflow;if(!workflow)return{generation:0,stageA:0,stageB:0};let history=Array.isArray(workflow.retryHistory)?workflow.retryHistory:[];return{generation:Number.isFinite(workflow.generation)?workflow.generation:0,stageA:history.filter((o)=>o==="stage_a_failed").length,stageB:history.filter((o)=>o==="stage_b_failed").length}}catch{return{generation:0,stageA:0,stageB:0}}}function resolutionOf(plan,taskId){for(let phase of plan.phases){let task=(phase.tasks??[]).find((t)=>t.id===taskId);if(!task)continue;if(task.status==="completed")return"completed";if(task.status==="closed")return"closed";return null}return"removed"}function markerFor(epic,taskId,resolution,closeHead,taskCommits){if(resolution!=="completed")return null;if(!epic.git.isRepo)return{ref:null,sha:null,provenance:"no-git"};let landed=taskCommits.get(taskId),sha=landed??closeHead;return{ref:isFullSha(sha)?epicTaskRef(epic.epicKey,taskId):null,sha,provenance:landed?"landing-commit":"wave-close-head"}}async function computeWaveClose(args2){let{directory,epic,wave,plan,sessionID,nowIso:nowIso2}=args2,isRepo=epic.git.isRepo,closeHead=isRepo?readHead(directory):null,events=[];try{events=await _internals55.readLedgerEvents(directory)}catch(error49){warn(`[epic/wave-close] plan ledger unreadable; outcome times fall back to now: ${errorText4(error49)}`)}let changed=isRepo?changedFilesSinceBase(directory,wave.baseHead):null,completedIds=wave.taskIds.filter((taskId)=>resolutionOf(plan,taskId)==="completed"),taskCommits=new Map;if(isRepo&&closeHead&&completedIds.length>0)try{taskCommits=_internals55.findTaskCommits(directory,isFullSha(wave.baseHead)?`${wave.baseHead}..HEAD`:epicCommitRange(epic),epic.planKey,completedIds)}catch(error49){warn(`[epic/wave-close] task commit lookup failed; markers fall back to the close HEAD: ${errorText4(error49)}`)}let outcomes=[],attributedAll=new Set;for(let taskId of wave.taskIds){let resolution=resolutionOf(plan,taskId)??"removed",declared=[...wave.files[taskId]??[]],counts=resolution==="removed"?{generation:0,stageA:0,stageB:0}:await readWorkflowCounts(directory,taskId),undeclared=[],attribution=isRepo?"unavailable":"no-git";if(resolution==="completed"){let attributed=collectTaskAttribution(directory,sessionID,taskId);for(let file2 of attributed)attributedAll.add(file2);let actual=null;if(attributed.length>0)actual=attributed,attribution="session";else if(changed!==null&&wave.taskIds.length===1)actual=changed,attribution="git-single-task";if(actual!==null)undeclared=undeclaredFiles(declared,actual)}let snapshot=wave.mergeFailures?.[taskId];outcomes.push({taskId,phase:wave.phase,waveSeq:wave.seq,resolution,resolvedAt:lastTransitionAt(events,taskId,resolution)??nowIso2,generation:counts.generation,stageAFailures:counts.stageA,stageBFailures:counts.stageB,mergeFailure:snapshot?{outcome:snapshot.outcome,stage:snapshot.stage}:null,declared,undeclared,attribution,reopened:countReopens(events,taskId,epic.startedAt),marker:markerFor(epic,taskId,resolution,closeHead,taskCommits)})}let waveUndeclared=[];if(changed!==null){let declaredAll=Object.values(wave.files).flat();waveUndeclared=undeclaredFiles(declaredAll,changed).filter((file2)=>!attributedAll.has(file2))}return{closeHead,outcomes,waveUndeclared}}function applyWaveClose(record2,seq,computation,nowIso2){let wave=record2.waves.find((w)=>w.seq===seq);if(!wave||wave.status!=="issued"||record2.activeWaveSeq!==seq)return record2;let tasks={...record2.tasks};for(let outcome of computation.outcomes){let before=Object.hasOwn(record2.tasks,outcome.taskId)?record2.tasks[outcome.taskId]:void 0;tasks[outcome.taskId]=before&&before.waveSeq!==outcome.waveSeq?{...outcome,previous:{waveSeq:before.waveSeq,generation:before.generation,stageBFailures:before.stageBFailures,reopened:before.reopened}}:outcome}return{...record2,activeWaveSeq:null,tasks,waves:record2.waves.map((w)=>w.seq===seq?{...w,status:"closed",closedAt:nowIso2,closeHead:computation.closeHead,undeclared:computation.waveUndeclared}:w)}}function recordEpicWaveLearning(args2){let settings=resolveEpicLearningSettings(args2.config);if(!settings.enabled)return[];try{return _internals55.applyClosedWavesToPosterior(args2.directory,args2.record,settings).appliedWaves}catch(error49){return criticalWarn(`[epic/wave-close] learning update failed (the wave flow continues; the next wave close catches it up): ${errorText4(error49)}`),[]}}function releaseWaveAttribution(directory,sessionID,taskIds){let sessions=new Set,caller=sessionID?_internals55.getAgentSession(sessionID):void 0;if(caller)sessions.add(caller);try{let projectKey=_internals55.hydrationProjectKey(directory);for(let[,session]of _internals55.listAgentSessions())if(session&&session.owningProjectKey===projectKey)sessions.add(session)}catch{}for(let session of sessions)for(let taskId of taskIds)try{_internals55.resetModifiedFilesForTask(session,taskId,{remove:!0})}catch{}}var MAX_FALLBACK_FILES=2000,SHA_RE3,_internals55;var init_wave_close=__esm(()=>{init_gate_evidence();init_branch();init_ledger();init_hydration_ownership();init_state();init_logger();init_path();init_learning();init_learning_store();init_markers();SHA_RE3=/^[0-9a-f]{7,64}$/,_internals55={gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),readTaskEvidence,readLedgerEvents,listAgentSessions:()=>swarmState.agentSessions.entries(),getAgentSession,getModifiedFilesForTask,resetModifiedFilesForTask,hydrationProjectKey,applyClosedWavesToPosterior,findTaskCommits}});import*as fs32 from"node:fs";import*as path56 from"node:path";function errorText5(error49){return error49 instanceof Error?error49.message:String(error49)}function isSwarmStatePath(file2){let normalized=file2.replace(/\\/g,"/");return normalized===".swarm"||normalized.startsWith(".swarm/")||normalized.includes("/.swarm/")||normalized.endsWith("/.swarm")}function caseKey(file2){return process.platform==="win32"?file2.toLowerCase():file2}function listDirtyEntries(directory){let output=_internals56.gitExec(["status","--porcelain=v1","-z","--untracked-files=all"],directory),entries=[],records=output.split("\x00");for(let i=0;i<records.length;i+=1){let record2=records[i];if(record2.length<4)continue;let code=record2.slice(0,2),file2=record2.slice(3).replace(/\\/g,"/"),origin;if(code.includes("R")||code.includes("C"))i+=1,origin=records[i]?.replace(/\\/g,"/");if(isSwarmStatePath(file2))continue;if(entries.push({path:file2,untracked:code==="??",needsAdd:code[1]!==" ",...origin?{origin}:{}}),entries.length>=MAX_DIRTY_ENTRIES)break}return entries}function coveredBy(file2,declared){let key=caseKey(file2);return declared.some((entry)=>{let d=caseKey(entry.replace(/\\/g,"/").replace(/\/+$/,""));return d.length>0&&(key===d||key.startsWith(`${d}/`))})}function literal2(file2){return`:(literal)${file2}`}function readIndexEntries(directory,files){let entries=new Map;for(let i=0;i<files.length;i+=PATHSPEC_CHUNK){let out=_internals56.gitExec(["ls-files","-s","-z","--",...files.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);for(let record2 of out.split("\x00")){let tab=record2.indexOf("\t");if(tab<0)continue;let[mode,sha,stage]=record2.slice(0,tab).split(" ");if(stage!=="0")continue;entries.set(record2.slice(tab+1),`${mode} ${sha}`)}}return entries}function restoreIndexEntries(directory,files,before){for(let i=0;i<files.length;i+=PATHSPEC_CHUNK)_internals56.gitExecOnce(["reset","-q","--",...files.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);let after=readIndexEntries(directory,files);for(let file2 of files){let wanted=before.get(file2),actual=after.get(file2);if(wanted===actual)continue;if(wanted){let[mode,sha]=wanted.split(" ");_internals56.gitExecOnce(["update-index","--cacheinfo",`${mode},${sha},${file2}`],directory)}else _internals56.gitExecOnce(["update-index","--force-remove","--",file2],directory)}}function commitPaths(directory,message,files,toAdd){let base=["-c","commit.gpgsign=false","commit","--only","--no-verify","-m",message],pathspecs=files.map(literal2),inlineBytes=pathspecs.reduce((sum,p)=>sum+Buffer.byteLength(p,"utf-8")+1,0),before=readIndexEntries(directory,files);try{for(let i=0;i<toAdd.length;i+=PATHSPEC_CHUNK)_internals56.gitExecOnce(["add","-A","--",...toAdd.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);if(inlineBytes<=COMMIT_ARGV_PATHSPEC_BUDGET_BYTES)_internals56.gitExecOnce([...base,"--",...pathspecs],directory);else{let gitPath=_internals56.gitExec(["rev-parse","--git-path",`swarm-epic-residue-${process.pid}-${_internals56.now()}`],directory).trim(),specFile=path56.resolve(directory,gitPath);try{fs32.writeFileSync(specFile,`${pathspecs.join("\x00")}\x00`,"utf-8"),_internals56.gitExecOnce([...base,`--pathspec-from-file=${specFile}`,"--pathspec-file-nul"],directory)}finally{try{fs32.rmSync(specFile,{force:!0})}catch{}}}}catch(error49){try{restoreIndexEntries(directory,files,before)}catch(restoreError){criticalWarn(`[epic] could not restore the index after a failed residue commit (${errorText5(restoreError)}); check \`git status\` for: ${files.slice(0,10).join(", ")}`)}throw error49}try{let head=_internals56.gitExec(["rev-parse","HEAD"],directory).trim();return/^[0-9a-f]{40,64}$/.test(head)?head:null}catch{return null}}function commitTaskResidue(args2){let wanted=new Set;for(let candidate of args2.candidates)if(typeof candidate==="string"&&candidate.length>0&&!candidate.startsWith(":")&&!isSwarmStatePath(candidate))wanted.add(caseKey(candidate.replace(/\\/g,"/")));let files=new Set,toAdd=new Set,scopes=(args2.scopes??[]).filter((entry)=>entry.length>0&&!entry.startsWith(":")),globLike=scopes.filter((entry)=>/[*?]/.test(entry));if(globLike.length>0)warn(`[epic] task ${args2.taskId}: declared scope entries are literal files or directories, never globs; ${globLike.slice(0,5).join(", ")} only match a path spelled exactly like that.`);for(let entry of args2.dirty){if(!wanted.has(caseKey(entry.path))&&!(scopes.length>0&&coveredBy(entry.path,scopes)))continue;if(files.add(entry.path),entry.needsAdd!==!1)toAdd.add(entry.path);if(entry.origin&&!isSwarmStatePath(entry.origin))files.add(entry.origin)}if(files.size===0)return{status:"nothing"};let list2=[...files].sort();try{return{status:"committed",sha:commitPaths(args2.directory,formatEpicTaskCommitMessage(args2.taskId,args2.epic.planKey,args2.label),list2,[...toAdd].sort()),files:list2}}catch(error49){return{status:"failed",error:errorText5(error49),files:list2}}}function inFlightWriterFiles(directory,exclude){let files=new Set;for(let[id,session]of _internals56.listAgentSessions()){if(exclude.has(id)||!session?.delegationActive)continue;if(!(session.modifiedFilesByTask instanceof Map))continue;for(let entries of session.modifiedFilesByTask.values())for(let file2 of entries){let canonical=canonicalAttributionPath(file2,directory);if(canonical!==null)files.add(caseKey(canonical))}}return files}function childSessionFiles(directory,ids){let files=[];for(let id of new Set(ids)){if(typeof id!=="string"||id.length===0)continue;let session=_internals56.getAgentSession(id);if(!session||!(session.modifiedFilesByTask instanceof Map))continue;for(let entries of session.modifiedFilesByTask.values())for(let file2 of entries){let canonical=canonicalAttributionPath(file2,directory);if(canonical!==null)files.push(canonical)}}return files}function declaredScopeOf(epic,taskId){return[...epic.waves.find((w)=>w.seq===epic.activeWaveSeq&&w.status==="issued")?.files[taskId]??[]]}async function commitEpicResidueAfterDelegation(request){try{if(!_internals56.epicSentinelExists(request.directory))return;let agent=stripKnownSwarmPrefix(request.agent);if(agent==="coder"||agent==="architect")return;let epic=_internals56.getOpenEpic(request.directory);if(!epic||!epic.git.isRepo)return;let taskIds=(await request.resolveTaskIds()).filter((id)=>_internals56.readPlanTaskRef(request.directory,id)!==null);if(taskIds.length===0)return;let branch=_internals56.checkEpicBranch(request.directory,epic);if(!branch.ok){criticalWarn(`[epic] ${agent} residue for task ${taskIds.join(", ")} NOT committed: ${branch.message}`);return}let childIds=await request.childSessionIds(),childFiles=childSessionFiles(request.directory,childIds),exclude=new Set([...childIds,request.sessionID].filter((id)=>typeof id==="string"&&id.length>0)),inFlight=inFlightWriterFiles(request.directory,exclude);await _internals56.serializeWithMergeBacks(()=>commitResidueForTasks(request,epic,agent,taskIds,childFiles,inFlight))}catch(error49){criticalWarn(`[epic] residue commit after a ${request.agent} delegation failed (non-fatal; epic_next_wave retries): ${errorText5(error49)}`)}}function commitResidueForTasks(request,epic,agent,taskIds,childFiles,inFlight=new Set){try{let dirty=listDirtyEntries(request.directory).filter((entry)=>!inFlight.has(caseKey(entry.path)));if(dirty.length===0)return;let remaining=dirty,commitStep=(taskId,label,candidates,scopes)=>{let result=commitTaskResidue({directory:request.directory,epic,taskId,label,candidates,scopes,dirty:remaining});if(result.status==="failed")return criticalWarn(`[epic] ${label} for task ${taskId} could not be committed (${result.error}); epic_next_wave retries before the next wave. Files: ${result.files.slice(0,10).join(", ")}`),!1;if(result.status==="committed"){let done=new Set(result.files.map(caseKey));remaining=remaining.filter((entry)=>!done.has(caseKey(entry.path)))}return!0};for(let[index,taskId]of taskIds.entries()){if(index===0&&childFiles.length>0&&!commitStep(taskId,`${agent} residue`,childFiles,[]))return;if(!commitStep(taskId,"residue",_internals56.collectTaskAttribution(request.directory,request.sessionID,taskId),declaredScopeOf(epic,taskId)))return}}catch(error49){criticalWarn(`[epic] residue commit after a ${request.agent} delegation failed (non-fatal; epic_next_wave retries): ${errorText5(error49)}`)}}function classifyDirtyBaseline(dirty){let unattributedTracked=[],unattributedUntracked=[];for(let entry of dirty)(entry.untracked?unattributedUntracked:unattributedTracked).push(entry.path);return{unattributedTracked,unattributedUntracked}}var COMMIT_ARGV_PATHSPEC_BUDGET_BYTES=24576,PATHSPEC_CHUNK=200,MAX_DIRTY_ENTRIES=5000,_internals56;var init_residue_commit=__esm(()=>{init_schema();init_branch();init_worktree_isolation();init_state();init_logger();init_path();init_epic_branch();init_git_once();init_lifecycle();init_plan_key();init_wave_close();_internals56={epicSentinelExists,getOpenEpic,readPlanTaskRef,checkEpicBranch,collectTaskAttribution,getAgentSession,listAgentSessions:()=>swarmState.agentSessions.entries(),gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),gitExecOnce,serializeWithMergeBacks:(task)=>runSerializedWithMergeBacks(task),now:()=>Date.now()}});function normalizeToolName(toolName){if(!toolName)return;return toolName.replace(NAMESPACE_PREFIX_PATTERN,"")}function normalizeToolNameLowerCase(toolName){return toolName.replace(NAMESPACE_PREFIX_PATTERN,"").toLowerCase()}function isTaskToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.task$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="task"}var NAMESPACE_PREFIX_PATTERN;var init_normalize_tool_name=__esm(()=>{NAMESPACE_PREFIX_PATTERN=/^[^:]+[:.]/});function declaresWindowsWrapper(command){return CMD_WRAPPER_DECLARATION.test(command)||PS_WRAPPER_DECLARATION.test(command)}function declaresWindowsWrapperLoose(command){return declaresWindowsWrapper(command)||PS_WRAPPER_LOOSE.test(command)}function recordObservedHostShell(shell){if(typeof shell!=="string"||shell.trim()==="")return;observedHostShell=shell}function getObservedHostShell(){return observedHostShell}function hostShellGrammarFamily(hostShell){let name=(hostShell.split(/[\\/]/).filter(Boolean).pop()??hostShell).replace(/\.exe$/i,"").toLowerCase();return name==="powershell"||name==="pwsh"||name==="cmd"?"windows":"posix"}var CMD_SWITCH,CMD_WRAPPER_DECLARATION,PS_WRAPPER_DECLARATION,PS_WRAPPER_LOOSE,CMD_BUILTIN_PREFIX,CMD_STRIP_PREFIX,PS_STRIP_PREFIX,observedHostShell;var init_shell_executor_context=__esm(()=>{CMD_SWITCH=String.raw`\/[a-z](?::(?:on|off))?`,CMD_WRAPPER_DECLARATION=new RegExp(String.raw`(?:^|[;|&\n])\s*cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/c(?:\s|$)`,"i"),PS_WRAPPER_DECLARATION=/(?:^|[;|&\n])\s*(?:powershell|pwsh)(?:\.exe)?\s+(?:-[A-Za-z]+\s+)*-command(?:\s|$)/i,PS_WRAPPER_LOOSE=/(?:^|\|)\s*(?:powershell|pwsh)(?:\.exe)?\s+-/i;CMD_BUILTIN_PREFIX=new RegExp(String.raw`(?:(?:^|\s)(?:if\s+(?:not\s+)?exist\s+(?:"[^"]*"|\S+)\s+)|(?:^|[;|&\n])\s*cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/c\s+|(?:^|\s)(?:call|start)\s+)*`,"i"),CMD_STRIP_PREFIX=new RegExp(String.raw`^cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/[ck]\s+`,"i"),PS_STRIP_PREFIX=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-[A-Za-z]+\s+)*-(?:command|c)\s+/i});import*as fsSync6 from"node:fs";import*as path57 from"node:path";function dcNormalizeCommand(cmd){let s=cmd.normalize("NFKC");return s=s.replace(/`(.)/g,"$1"),s=s.replace(/\^([a-zA-Z0-9 ])/g,"$1"),s=s.replace(/""/g,""),s=s.replace(/''/g,""),s}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=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].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,prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??envPrefix.exec(t)??/^nice\s+(?:-n\s+\d+\s+)?(.+)$/is.exec(t);if(prefixMatch)return prefixMatch[1].trim();let wslMatch=/^wsl(?:\.exe)?\s+(?:-e|--)\s+(.+)$/is.exec(t);if(wslMatch)return wslMatch[1].trim();let scriptBlockMatch=/^&\s*\{(.+)\}$/s.exec(t);if(scriptBlockMatch)return scriptBlockMatch[1].trim();let iexMatch=/^(?:Invoke-Expression|iex)\s+(.+)$/is.exec(t);if(iexMatch)return iexMatch[1].replace(/^["'`]|["'`]$/g,"").trim();let invokeCommandMatch=/^Invoke-Command\s+.*-ScriptBlock\s*\{(.+)\}$/is.exec(t);if(invokeCommandMatch)return invokeCommandMatch[1].trim();let callMatch=/^call\s+(.+)$/is.exec(t);if(callMatch)return callMatch[1].trim();return null}function dcUnwrapWrappers(cmd){let current=cmd.trim();for(let depth=0;depth<DC_MAX_UNWRAP_DEPTH;depth++){let inner=dcStripOneWrapper(current);if(inner===null||inner===current)break;current=inner.trim()}return current}function dcSplitSegments(cmd){let segments=[],current="",inDoubleQuote=!1,inSingleQuote=!1;for(let i=0;i<cmd.length;i++){let ch=cmd[i],next=cmd[i+1];if(ch==='"'&&!inSingleQuote){inDoubleQuote=!inDoubleQuote,current+=ch;continue}if(ch==="'"&&!inDoubleQuote){inSingleQuote=!inSingleQuote,current+=ch;continue}if(!inDoubleQuote&&!inSingleQuote){if(ch==="&"&&next==="&"||ch==="|"&&next==="|"){segments.push(current.trim()),current="",i++;continue}if(ch==="|"||ch===";"||ch===`
707
707
  `||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=path57.resolve(cwd,targetPath),normalizedCwd=path57.resolve(cwd),ancestors=[],current=normalizedTarget;while(!0){let rel=path57.relative(normalizedCwd,current);if(rel===".."||rel.startsWith(`..${path57.sep}`)||path57.isAbsolute(rel))break;if(ancestors.push(current),rel==="")break;let parent=path57.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat8=null;try{stat8=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(stat8.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,path57.sep),lstatBlock=dcLstatAncestorWalk(filesystemTarget,cwd);if(lstatBlock)return lstatBlock;let basename11=path57.basename(filesystemTarget);if(dcPathComponents(t).length===1&&DC_SAFE_TARGETS.has(basename11))continue;if(DC_FS_ROOTS.has(t)||DC_FS_ROOTS.has(t.replace(/\//g,"\\")))return`BLOCKED: Destructive command targets filesystem root "${t}"`;if(path57.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=path57.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,path57.sep),resolved=path57.resolve(input.cwd,filesystemTarget),relative13=path57.relative(path57.resolve(input.cwd),resolved);if(relative13===""||relative13===".."||relative13.startsWith(`..${path57.sep}`)||path57.isAbsolute(relative13))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUTSIDE_WORKSPACE",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not strictly contained by the workspace.`};let basename11=path57.basename(resolved);if(!DC_SAFE_TARGETS.has(basename11))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=path57.resolve(cwd,target),rel=path57.relative(cwd,resolved);if(rel.startsWith("..")||path57.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=path57.resolve(cwd,target),rel=path57.relative(cwd,resolved);if(rel.startsWith("..")||path57.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=path57.resolve(cwd,target),rel=path57.relative(cwd,resolved);if(rel.startsWith("..")||path57.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();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 path58 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)=>path58.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!=='"'&&quote!=="'")return null;this.pos+=1;let out="";while(!this.eof()){let ch=this.peek();if(this.pos+=1,ch===quote)return out;if(ch===`
708
708
  `||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 path59 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=path59.resolve(target),resolvedRoot=path59.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path59.sep)?resolvedRoot:resolvedRoot+path59.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=path59.isAbsolute(filePath)?filePath:path59.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=path59.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(path59.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(path59.relative(input.directory,path59.resolve(input.directory,p)),config2))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool}}}function buildStructuredDenial(decision,tool){return{full_auto_denial:!0,tool,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}var READ_ONLY_TOOLS,WRITE_LIKE_TOOLS,SHELL_TOOLS,NETWORK_TOOLS,SUBAGENT_TOOLS,HIGH_RISK_BUILD_PATHS,ALWAYS_PROTECTED_PREFIXES,PROTECTED_PATH_DEFAULTS,FULL_AUTO_SECRET_READ_PATTERN,FULL_AUTO_SECRET_ENV_PATTERN,FULL_AUTO_PRIMARY_PUSH_PATTERN,PATH_ARG_KEYS;var init_policy=__esm(()=>{init_constants();init_schema();init_config();init_normalize_tool_name();init_command_classifier();init_protected_path_policy();init_path();init_code_mode_program();READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine","suggest_patch"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","gitingest"]),SUBAGENT_TOOLS=new Set(["agent","delegate"]),HIGH_RISK_BUILD_PATHS=["src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto/","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"];FULL_AUTO_SECRET_READ_PATTERN=/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)\b/i,FULL_AUTO_SECRET_ENV_PATTERN=/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,FULL_AUTO_PRIMARY_PUSH_PATTERN=/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i;PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"]});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals57});import{existsSync as existsSync30,statSync as statSync19}from"node:fs";import*as path60 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(_internals57.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals57.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path60.join(grammarsDir,"tree-sitter.wasm");if(!_internals57.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
709
709
  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 _internals57.parserInit({locateFile(scriptName){return path60.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?path60.join(thisDir,"grammars"):isCliBundle?path60.join(thisDir,"..","lang","grammars"):path60.join(thisDir,"lang","grammars")}function getGrammarsDirAbsolute(){let thisDir=_internals57.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=path60.join(getGrammarsDirAbsolute(),wasmFileName);if(!_internals57.fileExists(wasmPath))throw Error(`Grammar file not found for ${languageId}: ${wasmPath}
@@ -1172,10 +1172,10 @@ in`);return tk},In(tk,iterable){if((iterable.behind(1)||tokens.mkToken("EMPTY"))
1172
1172
  `)}};module.exports=()=>compose(filterNonNull,map3(tokens.applyTokenizerVisitor(SkipRepeatedNewLines)),lookahead)});var require_assignment_word=__commonJS((exports,module)=>{var map3=require_map_iterable(),isValidName=require_is_valid_name();module.exports=function(){return map3((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 map3=require_map_iterable();module.exports=function(){return map3((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,hash4){if(hash4.recoverable)this.trace(str);else{let _parseError2=function(msg,hash5){this.message=msg,this.hash=hash5};var _parseError=_parseError2;throw _parseError2.prototype=Error,new _parseError2(str,hash4)}},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 symbol3,preErrorSymbol,state2,action,a,r,yyval={},p,len,newState2,expected;while(!0){if(state2=stack[stack.length-1],this.defaultActions[state2])action=this.defaultActions[state2];else{if(symbol3===null||typeof symbol3>"u")symbol3=lex();action=table[state2]&&table[state2][symbol3]}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)+`:
1173
1173
  `+lexer.showPosition()+`
1174
1174
  Expecting `+expected.join(", ")+", got '"+(this.terminals_[symbol3]||symbol3)+"'";else errStr="Parse error on line "+(yylineno+1)+": Unexpected "+(symbol3==EOF?"end of input":"'"+(this.terminals_[symbol3]||symbol3)+"'");this.parseError(errStr,{text:lexer.match,token:this.terminals_[symbol3]||symbol3,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: "+symbol3);switch(action[0]){case 1:if(stack.push(symbol3),vstack.push(lexer.yytext),lstack.push(lexer.yylloc),stack.push(action[1]),symbol3=null,!preErrorSymbol){if(yyleng=lexer.yyleng,yytext=lexer.yytext,yylineno=lexer.yylineno,yyloc=lexer.yylloc,recovering>0)recovering--}else symbol3=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._$),newState2=table[stack[stack.length-2]][stack[stack.length-1]],stack.push(newState2);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 map3=require_map_iterable(),tokenOrEmpty=require_tokens().tokenOrEmpty,convertToWord=()=>map3((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===`
1175
- `)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_utils2(),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 path97 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))),stripQuotes2=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),isQuoteArtifact=(write)=>{let stripped=stripQuotes2(write.path);if(stripped===write.path)return!1;return authority.writes.some((other)=>other.category===write.category&&other.operator===write.operator&&stripQuotes2(other.path)===stripped)},keptIndex=new Map,writes=[],demoteKept=(key2)=>{let index=keptIndex.get(key2);if(index!==void 0)writes[index]=withoutEmptyDirectoryRemoval(writes[index])};for(let write of[...authority.writes,...supplementary.writes]){let key2=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(key2)){demoteKept(key2);continue}if(isQuoteArtifact(write))continue}if(keptIndex.has(key2)){demoteKept(key2);continue}keptIndex.set(key2,writes.length),writes.push(write)}return{writes,hasWrites:writes.length>0||primary.hasWrites||additional.hasWrites,parseError:primary.parseError}}function buildDedupeKey(category,operator,path98){return`${category}|${operator}|${path98??"null"}`}function withoutEmptyDirectoryRemoval(write){if(write.emptyDirectoryRemoval!==!0)return write;let{emptyDirectoryRemoval:_dropped,...rest}=write;return rest}function dedupeWriteTargets(writes){let keptIndex=new Map,kept=[];for(let write of writes){let key2=buildDedupeKey(write.category,write.operator,write.path),index=keptIndex.get(key2);if(index===void 0){keptIndex.set(key2,kept.length),kept.push(write);continue}kept[index]=withoutEmptyDirectoryRemoval(kept[index])}return kept}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 path98=appendMatch[3];if(path98&&!isNullDevice(path98))results.push({category:"redirect",operator:">>",path:path98})}else{let writeMatch=stage.match(/^\s*(.*?)\s*>(?!>)(\s*)(\S+)\s*$/);if(writeMatch){let path98=writeMatch[3];if(path98&&!isNullDevice(path98))results.push({category:"redirect",operator:">",path:path98})}}}}return results}function detectBuiltinWritesFromString(cmd){let tokens=cmd.trim().split(/\s+/);if(tokens.length===0)return null;let name=tokens[0].toLowerCase();if(name==="rmdir"&&tokens.some((token)=>/^\/(?:s|q)$/i.test(token)))return null;if(BUILTIN_WRITE_COMMANDS.has(name)){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))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!==`
1176
- `)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 hex5=x??u??big;if(hex5!==void 0){let cp2=Number.parseInt(hex5,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 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 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(path98){return path98==="/dev/null"||path98==="/dev/zero"||path98==="/dev/urandom"}function isNullDeviceWord(word,path98){if(!isNullDevice(path98)||!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(path98){return path98!==null&&(isNumeric(path98)||path98==="-")}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,path98=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path98)){if(path98!==null&&isNullDeviceWord(fileNode,path98))continue;results.push({category:"redirect",operator:opLabel,path:path98})}else if(REDIRECT_HERE_TOKENS.has(opType))results.push({category:"here_doc",operator:opLabel,path:path98})}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=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(lowerName==="dd"){let suffixWords2=getSuffixWords(cmd);for(let word of suffixWords2)if(word.startsWith("of=")){let path98=word.slice(3);if(path98&&!isNullDevice(path98))results.push({category:"builtin_write",operator:"dd of=",path:path98})}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:name,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:name,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=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INPLACE_EDIT_COMMANDS.has(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:`${name} -i`,path:word});return results}function detectInterpreterEval(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INTERPRETER_EVAL_COMMANDS.has(lowerName))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(lowerName==="eval")return results.push({category:"interpreter_eval",operator:"eval",path:null}),results;let relevantFlags=evalFlags[lowerName]??[];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}),results}function detectNetworkDownloaders(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!NETWORK_DOWNLOAD_COMMANDS.has(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 path98=suffixWords[i+1];if(!path98.startsWith("-"))results.push({category:"network_download",operator:"curl -o",path:path98})}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 path98=suffixWords[i+1];if(!path98.startsWith("-"))results.push({category:"network_download",operator:"wget -O",path:path98})}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 lowerName=name.toLowerCase();if(!ARCHIVE_EXTRACT_COMMANDS.has(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 path98=suffixWords[dashDashIdx+1],op=path98==="."?"git checkout -- .":"git checkout --";results.push({category:"git_destructive",operator:op,path:path98})}}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===`
1177
- `&&!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 path98=iwrMatch[1]||iwrMatch[2];if(path98)results.push({category:"network_download",operator:"Invoke-WebRequest -OutFile",path:path98})}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((path98)=>({category:"redirect",operator:cmdletName,path:path98||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 path98=token.replace(/^["']|["']$/g,"");return[{category:"redirect",operator:cmdletName,path:path98}]}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 path98=token.replace(/^["']|["']$/g,"");if(path98){results.push({category:"redirect",operator:cmdletName,path:path98});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 path98=destFlagMatch[1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path98}}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 path98=tokens[tokens.length-1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path98}}else if(tokens.length===1){let path98=tokens[0].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path98}}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 path98=destFlagMatch[1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path98})}else{let nonFlagTokens=(afterCmdlet.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[]).filter((t)=>!t.startsWith("-")&&t.length>0);if(nonFlagTokens.length>0){let path98=nonFlagTokens[nonFlagTokens.length-1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path98})}}}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 path98=rdMatch[1].replace(/^["']|["']$/g,"");if(!path98.startsWith("/"))results.push({category:"builtin_write",operator:"rd",path:path98})}let mdMatch=trimmed.match(/^md\s+(\S+)/i);if(mdMatch){let path98=mdMatch[1].replace(/^["']|["']$/g,"");if(!path98.startsWith("/"))results.push({category:"builtin_write",operator:"md",path:path98})}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))}if(parseFailed){let procSubWrites=detectProcessSubstitutionWrites(command);allWrites.push(...procSubWrites)}let writes=dedupeWriteTargets(allWrites);if(!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 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){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 stripQuotes2=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),seen=new Set,seenStripped=[],writes=allWrites.filter((wt)=>{let key2=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key2))return!1;let stripped=stripQuotes2(wt.path);if(stripped!==wt.path){if(seenStripped.some((other)=>other.category===wt.category&&other.operator===wt.operator&&stripQuotes2(other.path)===stripped))return!1}return seen.add(key2),seenStripped.push({category:wt.category,operator:wt.operator,path:wt.path}),!0});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 path97.win32.resolve(cwd,pathText);let normalizedRelativeWindowsPath=!path97.posix.isAbsolute(pathText)&&!/^[a-zA-Z]:[\\/]/.test(pathText)?pathText.replace(/\\/g,"/"):pathText;return path97.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){if(!node||typeof node!=="object")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);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)}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]=path97.posix.resolve(currentStack[0]??"/",cdTarget);else collectWritesWithNodes(cmd,out,currentStack)}}break}case"Pipeline":case"Sequence":{if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack);break}case"LogicalExpression":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}break}case"And":case"Or":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}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]);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]);if(node.do)collectWritesWithNodes(node.do,out,[...cwdStack]);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]);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])}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]);break}case"Command":case"SimpleCommand":{let effectiveCwd=cwdStack[0]??"/",cdTarget=getCdTarget(node);if(cdTarget){cwdStack[0]=path97.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,path98=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path98)){if(path98!==null&&isNullDevice(path98))return[];return[{category:"redirect",operator:opLabel,path:path98}]}else if(REDIRECT_HERE_TOKENS.has(opType))return[{category:"here_doc",operator:opLabel,path:path98}];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)}));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)}));let cwdStack=[cwd],writesWithNodes=[];collectWritesWithNodes(ast,writesWithNodes,cwdStack);let seen=new Set,collidingKeys=new Set,deduplicated=writesWithNodes.filter((wwn)=>{let key2=buildDedupeKey(wwn.write.category,wwn.write.operator,wwn.write.path);if(seen.has(key2))return collidingKeys.add(key2),!1;return seen.add(key2),!0}),inputKeys=new Set;for(let write of writes){let key2=buildDedupeKey(write.category,write.operator,write.path);if(inputKeys.has(key2))collidingKeys.add(key2);inputKeys.add(key2)}let resolvedMap=new Map;for(let{write,context}of deduplicated){let resolvedPath=resolvePath(write.path,context),resolved=write.path!==null&&!isDynamicPath(write.path),key2=buildDedupeKey(write.category,write.operator,write.path);resolvedMap.set(key2,{resolvedPath,resolved})}return writes.map((input)=>{let key2=buildDedupeKey(input.category,input.operator,input.path),original=collidingKeys.has(key2)?withoutEmptyDirectoryRemoval(input):input,resolved=resolvedMap.get(key2);if(resolved)return{original,resolvedPath:resolved.resolvedPath,resolved:resolved.resolved};return{original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}})}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,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,_CMD_COPY_MOVE_SWITCHES,PLAIN_COMMAND_LINE,CWD_NEUTRAL_COMMANDS,CWD_TRANSPARENT_NODE_TYPES;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","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"]),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:`
1178
- `,r:"\r",b:"\b",f:"\f",v:"\v"};_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"])});import*as fs61 from"node:fs";import*as path98 from"node:path";function extractFilename(code,language,index){let lines=code.trim().split(`
1175
+ `)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_utils2(),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 path97 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))),stripQuotes2=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),isQuoteArtifact=(write)=>{let stripped=stripQuotes2(write.path);if(stripped===write.path)return!1;return authority.writes.some((other)=>other.category===write.category&&other.operator===write.operator&&stripQuotes2(other.path)===stripped)},keptIndex=new Map,writes=[],demoteKept=(key2)=>{let index=keptIndex.get(key2);if(index!==void 0)writes[index]=withoutEmptyDirectoryRemoval(writes[index])};for(let write of[...authority.writes,...supplementary.writes]){let key2=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(key2)){demoteKept(key2);continue}if(isQuoteArtifact(write))continue}if(keptIndex.has(key2)){demoteKept(key2);continue}keptIndex.set(key2,writes.length),writes.push(write)}return{writes,hasWrites:writes.length>0||primary.hasWrites||additional.hasWrites,parseError:primary.parseError}}function buildDedupeKey(category,operator,path98){return`${category}|${operator}|${path98??"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 path98=appendMatch[3];if(path98&&!isNullDevice(path98))results.push({category:"redirect",operator:">>",path:path98})}else{let writeMatch=stage.match(/^\s*(.*?)\s*>(?!>)(\s*)(\S+)\s*$/);if(writeMatch){let path98=writeMatch[3];if(path98&&!isNullDevice(path98))results.push({category:"redirect",operator:">",path:path98})}}}}return results}function detectBuiltinWritesFromString(cmd){let tokens=cmd.trim().split(/\s+/);if(tokens.length===0)return null;let name=tokens[0].toLowerCase();if(name==="rmdir"&&tokens.some((token)=>/^\/(?:s|q)$/i.test(token)))return null;if(BUILTIN_WRITE_COMMANDS.has(name)){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))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!==`
1176
+ `)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 hex5=x??u??big;if(hex5!==void 0){let cp2=Number.parseInt(hex5,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(word.split(/[\\/]/).filter(Boolean).pop()??word).replace(/\.exe$/i,"").toLowerCase()}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 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(path98){return path98==="/dev/null"||path98==="/dev/zero"||path98==="/dev/urandom"}function isNullDeviceWord(word,path98){if(!isNullDevice(path98)||!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(path98){return path98!==null&&(isNumeric(path98)||path98==="-")}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,path98=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path98)){if(path98!==null&&isNullDeviceWord(fileNode,path98))continue;results.push({category:"redirect",operator:opLabel,path:path98})}else if(REDIRECT_HERE_TOKENS.has(opType))results.push({category:"here_doc",operator:opLabel,path:path98})}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=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(lowerName==="dd"){let suffixWords2=getSuffixWords(cmd);for(let word of suffixWords2)if(word.startsWith("of=")){let path98=word.slice(3);if(path98&&!isNullDevice(path98))results.push({category:"builtin_write",operator:"dd of=",path:path98})}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:name,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:name,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=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INPLACE_EDIT_COMMANDS.has(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:`${name} -i`,path:word});return results}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=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!NETWORK_DOWNLOAD_COMMANDS.has(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 path98=suffixWords[i+1];if(!path98.startsWith("-"))results.push({category:"network_download",operator:"curl -o",path:path98})}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 path98=suffixWords[i+1];if(!path98.startsWith("-"))results.push({category:"network_download",operator:"wget -O",path:path98})}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 lowerName=name.toLowerCase();if(!ARCHIVE_EXTRACT_COMMANDS.has(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 path98=suffixWords[dashDashIdx+1],op=path98==="."?"git checkout -- .":"git checkout --";results.push({category:"git_destructive",operator:op,path:path98})}}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===`
1177
+ `&&!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 path98=iwrMatch[1]||iwrMatch[2];if(path98)results.push({category:"network_download",operator:"Invoke-WebRequest -OutFile",path:path98})}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((path98)=>({category:"redirect",operator:cmdletName,path:path98||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 path98=token.replace(/^["']|["']$/g,"");return[{category:"redirect",operator:cmdletName,path:path98}]}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 path98=token.replace(/^["']|["']$/g,"");if(path98){results.push({category:"redirect",operator:cmdletName,path:path98});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 path98=destFlagMatch[1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path98}}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 path98=tokens[tokens.length-1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path98}}else if(tokens.length===1){let path98=tokens[0].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path98}}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 path98=destFlagMatch[1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path98})}else{let nonFlagTokens=(afterCmdlet.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[]).filter((t)=>!t.startsWith("-")&&t.length>0);if(nonFlagTokens.length>0){let path98=nonFlagTokens[nonFlagTokens.length-1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path98})}}}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 path98=rdMatch[1].replace(/^["']|["']$/g,"");if(!path98.startsWith("/"))results.push({category:"builtin_write",operator:"rd",path:path98})}let mdMatch=trimmed.match(/^md\s+(\S+)/i);if(mdMatch){let path98=mdMatch[1].replace(/^["']|["']$/g,"");if(!path98.startsWith("/"))results.push({category:"builtin_write",operator:"md",path:path98})}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))}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 key2=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key2)){if(collidingKeys.add(key2),wt.capability!==!0||wt.category!=="interpreter_eval")continue;let n=(occurrence.get(key2)??1)+1;occurrence.set(key2,n),writes.push({...wt,operator:`${wt.operator} #${n}`});continue}seen.add(key2),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 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){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 stripQuotes2=(p)=>p===null||p===void 0?p:p.replace(/^['"]+/,"").replace(/['"]+$/,""),seen=new Set,seenStripped=[],writes=allWrites.filter((wt)=>{let key2=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key2))return!1;let stripped=stripQuotes2(wt.path);if(stripped!==wt.path){if(seenStripped.some((other)=>other.category===wt.category&&other.operator===wt.operator&&stripQuotes2(other.path)===stripped))return!1}return seen.add(key2),seenStripped.push({category:wt.category,operator:wt.operator,path:wt.path}),!0});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 path97.win32.resolve(cwd,pathText);let normalizedRelativeWindowsPath=!path97.posix.isAbsolute(pathText)&&!/^[a-zA-Z]:[\\/]/.test(pathText)?pathText.replace(/\\/g,"/"):pathText;return path97.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){if(!node||typeof node!=="object")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);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)}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]??"/")??path97.posix.resolve(currentStack[0]??"/",cdTarget);else collectWritesWithNodes(cmd,out,currentStack)}}break}case"Pipeline":case"Sequence":{if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack);break}case"LogicalExpression":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}break}case"And":case"Or":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}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]);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]);if(node.do)collectWritesWithNodes(node.do,out,[...cwdStack]);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]);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])}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]);break}case"Command":case"SimpleCommand":{let effectiveCwd=cwdStack[0]??"/",cdTarget=getCdTarget(node);if(cdTarget){cwdStack[0]=resolvePath(cdTarget,cwdStack[0]??"/")??path97.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,path98=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType)||REDIRECT_GREATAND_TOKENS.has(opType)&&!isNonFileGreatAndTarget(path98)){if(path98!==null&&isNullDevice(path98))return[];return[{category:"redirect",operator:opLabel,path:path98}]}else if(REDIRECT_HERE_TOKENS.has(opType))return[{category:"here_doc",operator:opLabel,path:path98}];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],writesWithNodes=[];collectWritesWithNodes(ast,writesWithNodes,cwdStack);let seen=new Set,occurrence=new Map,collidingKeys=new Set,deduplicated=[];for(let wwn of writesWithNodes){let key2=buildDedupeKey(wwn.write.category,wwn.write.operator,wwn.write.path);if(seen.has(key2)){if(collidingKeys.add(key2),wwn.write.capability!==!0||wwn.write.category!=="interpreter_eval")continue;let n=(occurrence.get(key2)??1)+1;occurrence.set(key2,n),deduplicated.push({write:{...wwn.write,operator:`${wwn.write.operator} #${n}`},context:wwn.context});continue}seen.add(key2),deduplicated.push(wwn)}let inputKeys=new Set;for(let write of writes){let key2=buildDedupeKey(write.category,write.operator,write.path);if(inputKeys.has(key2))collidingKeys.add(key2);inputKeys.add(key2)}let resolvedMap=new Map;for(let{write,context}of deduplicated){let resolvedPath=resolvePath(write.path,context),resolved=write.path!==null&&!isDynamicPath(write.path),key2=buildDedupeKey(write.category,write.operator,write.path),evalDirectory=write.capability===!0&&write.category==="interpreter_eval"?context:void 0;resolvedMap.set(key2,{resolvedPath,resolved,evalDirectory})}return writes.map((input)=>{let key2=buildDedupeKey(input.category,input.operator,input.path),original=collidingKeys.has(key2)?withoutEmptyDirectoryRemoval(input):input,resolved=resolvedMap.get(key2);if(resolved)return{original,resolvedPath:resolved.resolvedPath,resolved:resolved.resolved,...resolved.evalDirectory!==void 0?{evalDirectory:resolved.evalDirectory}:{}};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,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;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","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"]),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:`
1178
+ `,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"])});import*as fs61 from"node:fs";import*as path98 from"node:path";function extractFilename(code,language,index){let lines=code.trim().split(`
1179
1179
  `),ext=EXT_MAP[language.toLowerCase()]??".txt",firstLine=lines[0]?.trim()??"",filenameMatch=firstLine.match(/^[#/]+\s*filename[:\s]+(\S+\.\w+)/i);if(filenameMatch?.[1])return filenameMatch[1];let bareMatch=firstLine.match(/^[#/]+\s*(\w+\.\w+)\s*$/);if(bareMatch?.[1])return bareMatch[1];for(let line of lines.slice(0,5)){let defMatch=line.match(/^(?:def\s+|class\s+)(\w+)/);if(defMatch?.[1]&&!defMatch[1].startsWith("_"))return`${defMatch[1]}${ext}`;let psMatch=line.match(/^function\s+([\w-]+)/i);if(psMatch?.[1])return`${psMatch[1]}${ext}`}return`output_${index+1}${ext}`}function lstatIfPresent(filePath){try{return fs61.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}}function reservationKey(filename){return path98.normalize(filename).toLowerCase()}function planExtractCodeBlocks(args2,directory){let{content,output_dir:outputDir,prefix}=args2;if(!content)return{status:"noop",reason:"content-required"};let matches=[...content.matchAll(/```(\w*)\n([\s\S]*?)```/g)];if(matches.length===0)return{status:"noop",reason:"no-code-blocks"};if(matches.length>MAX_EXTRACTED_FILES)return{status:"invalid",reason:`Too many code blocks (${matches.length}; maximum ${MAX_EXTRACTED_FILES})`};let targetDir=directory;if(outputDir!==void 0&&outputDir.trim()!==""){let reason=validateTargetWithinRoot(outputDir,directory);if(reason)return{status:"invalid",reason:`output_dir rejected — ${reason}`};targetDir=path98.resolve(directory,outputDir)}let reserved=new Set,files=[];for(let index=0;index<matches.length;index++){let language=matches[index]?.[1]??"",code=matches[index]?.[2]??"",filename=extractFilename(code,language,index);if(prefix)filename=`${prefix}_${filename}`;if(filename.includes("/")||filename.includes("\\"))return{status:"invalid",reason:`Rejected unsafe filename (must be a bare name): ${filename}`};let requestedPath=path98.join(targetDir,filename);if(lstatIfPresent(requestedPath)?.isSymbolicLink())return{status:"invalid",reason:`Rejected write through symlink: ${requestedPath}`};let base=path98.basename(filename,path98.extname(filename)),ext=path98.extname(filename),candidate=filename,counter=1;while(reserved.has(reservationKey(candidate))||lstatIfPresent(path98.join(targetDir,candidate))!==null){if(counter>MAX_COLLISION_ATTEMPTS)return{status:"invalid",reason:`Too many filename collisions for ${filename}`};candidate=`${base}_${counter}${ext}`,counter++}let absolutePath=path98.join(targetDir,candidate),relativePath=path98.relative(directory,absolutePath)||candidate,reason=validateTargetWithinRoot(relativePath,directory);if(reason)return{status:"invalid",reason:`Rejected write outside workspace: ${absolutePath} — ${reason}`};reserved.add(reservationKey(candidate)),files.push({filename:candidate,absolutePath,relativePath,code:code.trim()})}return{status:"ready",targetDir,files}}function getOrPlanExtractCodeBlocks(args2,directory){if(typeof args2==="object"&&args2!==null){let cached3=cachedPlans.get(args2);if(cached3?.directory===directory)return cached3.plan;let plan=planExtractCodeBlocks(args2,directory);return cachedPlans.set(args2,{directory,plan}),plan}return planExtractCodeBlocks(args2,directory)}function consumeExtractCodeBlocksPlan(args2,directory){let plan=getOrPlanExtractCodeBlocks(args2,directory);if(typeof args2==="object"&&args2!==null)cachedPlans.delete(args2);return plan}var EXT_MAP,MAX_EXTRACTED_FILES=256,MAX_COLLISION_ATTEMPTS=1e4,cachedPlans;var init_file_extractor_planner=__esm(()=>{init_path_security();EXT_MAP={python:".py",py:".py",powershell:".ps1",ps1:".ps1",pwsh:".ps1",javascript:".js",js:".js",typescript:".ts",ts:".ts",bash:".sh",sh:".sh",json:".json",yaml:".yaml",yml:".yaml",xml:".xml",html:".html",css:".css",sql:".sql",pester:".Tests.ps1",test:".Tests.ps1","":".txt"},cachedPlans=new WeakMap});import{Buffer as Buffer3}from"node:buffer";function unverifiable(reason){return{status:"unverifiable",reason}}function dedupe(paths){return[...new Set(paths)]}function genericResolver(args2){let paths=[],observedTargetField=!1;for(let key2 of SCALAR_PATH_KEYS){if(!(key2 in args2))continue;observedTargetField=!0;let value=args2[key2];if(typeof value!=="string"||value.trim()===""||containsControlCharacter(value))return unverifiable(`Malformed ${key2} target`);paths.push(value)}for(let key2 of ARRAY_PATH_KEYS){if(!(key2 in args2))continue;observedTargetField=!0;let value=args2[key2];if(!Array.isArray(value)||value.some((item)=>typeof item!=="string"||item.trim()===""||containsControlCharacter(item)))return unverifiable(`Malformed ${key2} targets`);paths.push(...value)}if(!observedTargetField||paths.length===0)return unverifiable("No write target was provided");return{status:"resolved",paths:dedupe(paths)}}function normalizeComparisonPath(filePath){return filePath.replace(/\\/g,"/").replace(/^\.\//,"")}function containsControlCharacter(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function parseTarget(raw,stripGitPrefix){let value=raw.replace(/\r$/,"").split("\t",1)[0]?.trim()??"";if(!value)return{error:"Empty patch target"};if(value==="/dev/null")return{};if(value.startsWith('"')||value.startsWith("'")||value.endsWith('"')||value.endsWith("'"))return{error:`Quoted patch path is unsupported: ${value}`};if(stripGitPrefix&&/\s/.test(value))return{error:`Ambiguous whitespace in diff path: ${value}`};if(stripGitPrefix&&(value.startsWith("a/")||value.startsWith("b/")))value=value.slice(2);if(!value||containsControlCharacter(value))return{error:"Malformed patch target"};return{path:value}}function parsePatchPayload(payload){let paths=[],operations=new Map,add=(raw,operation,stripGitPrefix=!1)=>{let parsed=parseTarget(raw,stripGitPrefix);if(parsed.error)return parsed.error;if(!parsed.path)return null;paths.push(parsed.path);let key2=normalizeComparisonPath(parsed.path),existing=operations.get(key2)??new Set;return existing.add(operation),operations.set(key2,existing),null},lines=normalizePatchIndentation(payload).split(/\r?\n/),beginIndices=[],endIndices=[],nativeOperationIndices=[];for(let index=0;index<lines.length;index++){let trimmed=(lines[index]??"").trim();if(trimmed==="*** Begin Patch")beginIndices.push(index);if(trimmed==="*** End Patch")endIndices.push(index);if(/^\*\*\* (?:Update|Add|Delete) File:/i.test(trimmed)||/^\*\*\* Move (?:to|from):/i.test(trimmed))nativeOperationIndices.push(index)}let hasUnifiedHeaders=lines.some((l)=>/^(---|\+\+\+)\s+/.test(l));if(beginIndices.length>0||nativeOperationIndices.length>0||!hasUnifiedHeaders&&endIndices.length>0){if(beginIndices.length===0)return"Native patch is missing *** Begin Patch";if(endIndices.length===0)return"Native patch is missing *** End Patch";if(beginIndices.length!==1||endIndices.length!==1)return"Native patch framing must contain exactly one begin and end marker";let beginIndex=beginIndices[0]??-1,endIndex=endIndices[0]??-1;if(beginIndex>=endIndex)return"Native patch has invalid begin/end marker ordering";if(nativeOperationIndices.some((index)=>index<=beginIndex||index>=endIndex))return"Native patch contains an operation outside begin/end markers";for(let index=beginIndex+1;index<endIndex;index++){let line=(lines[index]??"").trim(),match=line.match(/^\*\*\* (Update|Add|Delete) File:\s*(.*)$/);if(match){let error93=add(match[2]??"",(match[1]??"").toLowerCase());if(error93)return error93;continue}let move=line.match(/^\*\*\* Move (?:to|from):\s*(.*)$/i);if(move){let error93=add(move[1]??"","move");if(error93)return error93}}}else for(let line of lines){let git=line.match(/^diff --git\s+(.+)$/);if(git){let remainder=git[1]?.trim()??"";if(remainder.startsWith('"')||remainder.startsWith("'"))return"Quoted diff --git paths are unsupported";let parts=remainder.split(/\s+/);if(parts.length!==2)return"Malformed diff --git header";for(let part of parts){let error93=add(part,"diff",!0);if(error93)return error93}continue}let unified=line.match(/^(---|\+\+\+)\s+(.+)$/);if(unified){let error93=add(unified[2]??"","diff",!0);if(error93)return error93;continue}let rename8=line.match(/^rename (from|to)\s+(.+)$/);if(rename8){let error93=add(rename8[2]??"","rename");if(error93)return error93}}if(paths.length===0)return"Patch contains no recognizable write targets";for(let[filePath,fileOperations]of operations)if(fileOperations.has("add")&&fileOperations.has("delete"))return`Contradictory add/delete operations for ${filePath}`;return{paths:dedupe(paths),operations}}function patchResolver(args2,_context,toolName){let payloadGroups=[],aggregateBytes=0;for(let field of PATCH_PAYLOAD_KEYS){if(!(field in args2))continue;let value=args2[field];if(typeof value!=="string")return unverifiable(`Malformed ${field} payload`);payloadGroups.push({field,payloads:[value]})}if("cmd"in args2){let cmd=args2.cmd;if(typeof cmd==="string")payloadGroups.push({field:"cmd",payloads:[cmd]});else if(Array.isArray(cmd)&&cmd.every((item)=>typeof item==="string")){let payloads=cmd.filter((item,index)=>{if(index===0&&/(?:^|[/\\])(?:apply_patch|patch)(?:\.exe)?$/i.test(item))return!1;return!(item.startsWith("-")&&!item.includes(`
1180
1180
  `)&&!item.includes("*** Begin Patch"))});payloadGroups.push({field:"cmd",payloads})}else return unverifiable("Malformed cmd payload")}if(payloadGroups.length===0)return unverifiable("No patch payload was provided");let resolvedGroups=[];for(let group of payloadGroups){if(group.payloads.length===0)return unverifiable(`Empty ${group.field} payload`);let groupPaths=[];for(let payload of group.payloads){let bytes=Buffer3.byteLength(payload,"utf8");if(bytes>MAX_PATCH_FIELD_BYTES)return unverifiable(`Patch payload exceeds 1 MB (${group.field} field)`);if(aggregateBytes+=bytes,aggregateBytes>MAX_PATCH_AGGREGATE_BYTES)return unverifiable("Aggregate patch payload exceeds size limit");let parsed=parsePatchPayload(payload);if(typeof parsed==="string")return unverifiable(`${group.field}: ${parsed}`);groupPaths.push(...parsed.paths)}resolvedGroups.push({field:group.field,paths:dedupe(groupPaths)})}let canonical=(paths2)=>paths2.map(normalizeComparisonPath).sort().join(`
1181
1181
  `),expected=canonical(resolvedGroups[0]?.paths??[]);if(resolvedGroups.some((group)=>canonical(group.paths)!==expected))return unverifiable("Conflicting targets across patch payload fields");let paths=resolvedGroups[0]?.paths??[];if(toolName==="swarm_apply_patch"){let declared=args2.files;if(!Array.isArray(declared)||declared.some((item)=>typeof item!=="string"||item.trim()===""))return unverifiable("swarm_apply_patch requires a valid files array");let declaredSet=new Set(declared.map(normalizeComparisonPath));if(paths.some((filePath)=>!declaredSet.has(normalizeComparisonPath(filePath))))return unverifiable("Parsed patch target is missing from declared files")}return{status:"resolved",paths}}function extractResolver(args2,context){let plan=getOrPlanExtractCodeBlocks(args2,context.directory);if(plan.status==="invalid")return unverifiable(plan.reason);if(plan.status==="noop")return plan.reason==="no-code-blocks"?{status:"resolved",paths:[]}:unverifiable("content is required");return{status:"resolved",paths:plan.files.map((file3)=>file3.relativePath)}}function resolveWriteTargets2(toolName,args2,context){if(!WRITE_TOOL_NAMES.includes(toolName))return unverifiable(`Unknown write tool: ${toolName}`);if(typeof args2!=="object"||args2===null||Array.isArray(args2))return unverifiable("Write tool arguments must be an object");try{return WRITE_TARGET_RESOLVERS[toolName](args2,context)}catch(error93){return unverifiable(`Target resolution failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}var MAX_PATCH_FIELD_BYTES=1e6,MAX_PATCH_AGGREGATE_BYTES=2000000,SCALAR_PATH_KEYS,ARRAY_PATH_KEYS,PATCH_PAYLOAD_KEYS,patch=(args2,context)=>patchResolver(args2,context,"patch"),applyPatch=(args2,context)=>patchResolver(args2,context,"apply_patch"),swarmApplyPatch=(args2,context)=>patchResolver(args2,context,"swarm_apply_patch"),WRITE_TARGET_RESOLVERS;var init_write_target_resolver=__esm(()=>{init_constants();init_file_extractor_planner();SCALAR_PATH_KEYS=["path","filePath","file","target"],ARRAY_PATH_KEYS=["files","paths","targetFiles"],PATCH_PAYLOAD_KEYS=["patch","input","diff","patchText","patch_text","patchPayload","text","content"];WRITE_TARGET_RESOLVERS={write:genericResolver,edit:genericResolver,patch,apply_patch:applyPatch,swarm_apply_patch:swarmApplyPatch,create_file:genericResolver,insert:genericResolver,replace:genericResolver,append:genericResolver,prepend:genericResolver,extract_code_blocks:extractResolver}});import*as fs62 from"node:fs";import*as path99 from"node:path";import{StringDecoder as StringDecoder2}from"node:string_decoder";function decisionClassOf(event){return typeof event.type==="string"&&event.type.length>0?"security":"allowed"}function decisionDiscriminator(event){if(typeof event.type==="string"&&event.type.length>0)return event.type.slice(0,64);return"shell"}function decisionTimestamp(event){if(typeof event.ts!=="string")return null;let ts=Date.parse(event.ts);return Number.isNaN(ts)?null:event.ts}function emptyFolded2(){return{totalDecisions:0,byType:{},corrupt:0,dropped:0,oldestTimestamp:null,newestTimestamp:null}}function emptyManifest2(){return{v:1,type:MANIFEST_TYPE2,schemaVersion:MANIFEST_SCHEMA2,folded:emptyFolded2(),updatedAt:new Date().toISOString()}}function parseManifestLine2(line){let trimmed=line.trim();if(!trimmed)return null;try{let obj=JSON.parse(trimmed);if(typeof obj!=="object"||obj===null)return null;let rec=obj;if(rec.type!==MANIFEST_TYPE2||rec.v!==1||rec.schemaVersion!==MANIFEST_SCHEMA2||typeof rec.folded!=="object"||rec.folded===null)return null;let f=rec.folded,manifest=emptyManifest2(),num=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0?v:0;if(manifest.folded.totalDecisions=num(f.totalDecisions),manifest.folded.corrupt=num(f.corrupt),manifest.folded.dropped=num(f.dropped),typeof f.byType==="object"&&f.byType!==null){for(let[k,v]of Object.entries(f.byType))if(typeof v==="number"&&Number.isFinite(v)&&v>=0)manifest.folded.byType[k]=v}if(typeof f.oldestTimestamp==="string")manifest.folded.oldestTimestamp=f.oldestTimestamp;if(typeof f.newestTimestamp==="string")manifest.folded.newestTimestamp=f.newestTimestamp;return manifest.updatedAt=typeof rec.updatedAt==="string"?rec.updatedAt:new Date().toISOString(),manifest}catch{return null}}function shellAuditFilePath(directory){return path99.join(directory,".swarm","session","shell-audit.jsonl")}function lockFilePath2(directory){return path99.join(directory,".swarm","session","shell-audit.lock")}function tmpPathFor2(finalPath){return`${finalPath}.${process.pid}.tmp`}function readBoundedChunk2(filePath,maxBytes,offset=0){try{if(!_internals90.existsSync(filePath))return{text:"",truncated:!1};let fd=_internals90.openSync(filePath,"r");try{let size=_internals90.statSync(filePath).size,readable=Math.max(0,size-offset),truncated=readable>maxBytes,len=Math.min(readable,maxBytes),buf=Buffer.alloc(len),read=0;while(read<len){let n=_internals90.readSync(fd,buf,read,len-read,offset+read);if(n<=0)break;read+=n}return{text:buf.toString("utf-8",0,read),truncated}}finally{_internals90.closeSync(fd)}}catch{return warnThrottled2("bounded read failed (transient I/O)"),{text:"",truncated:!1}}}function fileSizeOrZero2(filePath){try{if(!_internals90.existsSync(filePath))return 0;return _internals90.statSync(filePath).size}catch{return 0}}function fileEndsWithNewline2(filePath){try{if(!_internals90.existsSync(filePath))return!0;let size=_internals90.statSync(filePath).size;if(size===0)return!0;let fd=_internals90.openSync(filePath,"r");try{let buf=Buffer.alloc(1);return _internals90.readSync(fd,buf,0,1,size-1)<=0||buf[0]===10}finally{_internals90.closeSync(fd)}}catch{return!0}}function foldLineInto2(folded,event){folded.totalDecisions+=1;let key2=decisionDiscriminator(event),keys=Object.keys(folded.byType);if(folded.byType[key2]!==void 0||keys.length<BY_TYPE_MAX_KEYS2)folded.byType[key2]=(folded.byType[key2]??0)+1;else folded.byType[BY_TYPE_OTHER2]=(folded.byType[BY_TYPE_OTHER2]??0)+1;let ts=decisionTimestamp(event);if(ts!==null){if(folded.oldestTimestamp===null||ts<folded.oldestTimestamp)folded.oldestTimestamp=ts;if(folded.newestTimestamp===null||ts>folded.newestTimestamp)folded.newestTimestamp=ts}}function cloneFolded2(folded){return{totalDecisions:folded.totalDecisions,byType:{...folded.byType},corrupt:folded.corrupt,dropped:folded.dropped,oldestTimestamp:folded.oldestTimestamp,newestTimestamp:folded.newestTimestamp}}function atomicReplace2(directory,content){let lines=content.split(`
@@ -1197,8 +1197,8 @@ ${line}`)}else{let prefix=fileEndsWithNewline2(filePath)?"":`
1197
1197
  `;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)})}
1198
1198
  `;break}case"file_write":line=`${JSON.stringify({...entry,path:redactPath(entry.path),reason:truncateUtf8Safe(redactEmbeddedPaths(entry.reason),maxReason),resolvedScope:redactPath(entry.resolvedScope)})}
1199
1199
  `;break;case"scope_violation":line=`${JSON.stringify({...entry,path:redactPath(entry.path),declaredScope:redactPath(entry.declaredScope),resolvedScope:redactPath(entry.resolvedScope)})}
1200
- `;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 path101 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path101.join(dir,"package.json");if(!_internals91.existsSync(manifestPath))return null;let name=JSON.parse(_internals91.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=path101.dirname(fileURLToPath3(_internals91.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path101.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=path101.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path101.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals91.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path101.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(!path101.isAbsolute(expanded))continue;try{resolved.push(path101.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=_internals91.resolvePackageRoot();if(!packageRoot)return;if(_internals91.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path101.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path101.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,_internals91;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;_internals91={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 path102 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=path102.resolve(workspace);if(isControlStateRelativePath(path102.relative(lexicalRoot,path102.resolve(lexicalRoot,targetPath))))return!1;let root=fs63.realpathSync.native(lexicalRoot),absolute=path102.resolve(root,targetPath),parent=fs63.realpathSync.native(path102.dirname(absolute)),canonical=path102.join(parent,path102.basename(absolute));if(isControlStateRelativePath(path102.relative(root,canonical)))return!1;let stat10;try{stat10=fs63.lstatSync(canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}if(stat10&&(!stat10.isDirectory()||stat10.isSymbolicLink()))return!1;return!pathIdentitiesEqual(canonical,root)&&isPathIdentityWithin(canonical,root)}catch{return!1}}function resolveWindowsWriteAuthority(tool3,command,detectedShellType,shaped,platform=process.platform){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(inheritedWindows&&!(tool3==="bash"||tool3==="shell"&&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),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(`
1201
- `):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(enforce&&analysis.parseError&&!suppressParseError(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);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")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(enforce&&noScopeLenient&&universalDenyPrefixes.length>0){for(let prefix of universalDenyPrefixes)if(matchesAuthorityDenyPrefix(write.resolvedPath,prefix,shellDirectory))throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: Path is under universal deny prefix "${prefix}"`)}if(noScopeLenient)continue;let authorityCheck=checkFileAuthorityWithRules(shellWriteAgent,write.resolvedPath,shellDirectory,precomputedAuthorityRules,{declaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(enforce&&!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"protected_state_mutation",paths:[write.resolvedPath]}):void 0;throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}if(enforce&&declaredScope&&declaredScope.length>0&&!isInDeclaredScope(write.resolvedPath,declaredScope,shellDirectory)&&!(write.original.emptyDirectoryRemoval===!0&&isPosixRmdirExecutor(normalizedTool,windowsShell,detectionCommand)&&isEmptyDirectoryRemovalWithinWorkspace(write.resolvedPath,shellDirectory))){let safeTarget=sanitizeDiagnosticText(write.resolvedPath,320),scopeSummary=declaredScope.slice(0,10).map((entry)=>sanitizeDiagnosticText(entry,160)).join(", "),omitted=Math.max(0,declaredScope.length-10);throw Error(`WRITE BLOCKED: SCOPE_VIOLATION: shell write target "${safeTarget}" is outside the active scope [${scopeSummary}${omitted>0?`, ... (+${omitted} more)`:""}]. ACTION[architect]: if the target is intended, call declare_scope for the exact workspace-relative path and redispatch; otherwise correct the command.`)}if(isCoder&&session?.currentTaskId){let writeBinding=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path102.relative(path102.resolve(shellDirectory),path102.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?[]:[path102.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(`
1200
+ `;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 path101 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path101.join(dir,"package.json");if(!_internals91.existsSync(manifestPath))return null;let name=JSON.parse(_internals91.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=path101.dirname(fileURLToPath3(_internals91.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path101.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=path101.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path101.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals91.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path101.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(!path101.isAbsolute(expanded))continue;try{resolved.push(path101.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=_internals91.resolvePackageRoot();if(!packageRoot)return;if(_internals91.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path101.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path101.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,_internals91;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;_internals91={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 path102 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=path102.resolve(workspace);if(isControlStateRelativePath(path102.relative(lexicalRoot,path102.resolve(lexicalRoot,targetPath))))return!1;let root=fs63.realpathSync.native(lexicalRoot),absolute=path102.resolve(root,targetPath),parent=fs63.realpathSync.native(path102.dirname(absolute)),canonical=path102.join(parent,path102.basename(absolute));if(isControlStateRelativePath(path102.relative(root,canonical)))return!1;let stat10;try{stat10=fs63.lstatSync(canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}if(stat10&&(!stat10.isDirectory()||stat10.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(`
1201
+ `):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(enforce&&analysis.parseError&&!suppressParseError(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=path102.relative(path102.resolve(shellDirectory),path102.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?[]:[path102.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(`
1202
1202
  `),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=path102.resolve(effectiveDirectory,targetPath).toLowerCase(),planMdPath=path102.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path102.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=path102.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=path102.resolve(effectiveDirectory,p),planMdPath=path102.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path102.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase(),specStalenessPath=path102.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(path102.relative(effectiveDirectory,path102.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)=>path102.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=path102.relative(path102.resolve(writeDirectory),path102.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=path102.relative(path102.resolve(writeDirectory),path102.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 path103 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=path103.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?`
1203
1203
  Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:"";message+=`
1204
1204
 
@@ -4365,8 +4365,8 @@ Phase **${result.phase??"unknown"}** retrospective saved to \`.swarm/evidence/${
4365
4365
  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 path291 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=path291.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(`
4366
4366
  `)}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(`
4367
4367
  `);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(`
4368
- `):shellCommand;if(decision==="allow"){let detected=resolveShellType(shellCommand),authority=resolveWindowsWriteAuthority("shell",shellCommand,detected,isPowerShellShaped(shellCommand)),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)),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(`
4369
- `)}var init_guardrail_explain_service=__esm(()=>{init_tool_policy();init_audit_log();init_destructive_command();init_file_authority();init_helpers();init_tool_before();init_shell_executor_context();init_shell_write_detect();init_command_classifier()});var exports_guardrail_explain={};__export(exports_guardrail_explain,{handleGuardrailExplain:()=>handleGuardrailExplain});var init_guardrail_explain=__esm(()=>{init_guardrail_explain_service()});function isBlockEntry(entry){if(entry.type===null||entry.type===void 0)return!1;return BLOCK_TYPES.has(entry.type)}function redactSummary(entry){if(entry.type==="file_write"||entry.type==="scope_violation"){let raw=entry.path??"";return redactPath(raw)}if(entry.type==="destructive_block"||entry.type==="sandbox_wrap"||entry.type==="sandbox_skip"||entry.type==="shell"||entry.type===null||entry.type===void 0){let raw=entry.command??"";return redactShellCommand(raw)}return""}function sanitizeDisplayText(value){return value.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g,"").replace(/[\u202a-\u202e\u2066-\u2069]/g,"").replace(/[\u200e\u200f\u200b-\u200d\u2060-\u2064\ufeff]/g,"")}function formatEntry(entry){let decisionType=entry.type??"shell",summary=redactSummary(entry),line=`- [${sanitizeDisplayText(entry.ts)}] ${sanitizeDisplayText(decisionType)} | agent: ${sanitizeDisplayText(entry.agent)} | ${sanitizeDisplayText(summary)}`;if(entry.commandHash!==void 0)line+=` · fp:${sanitizeDisplayText(entry.commandHash)}`;return line.length>MAX_RENDERED_LINE_CHARS?`${line.slice(0,MAX_RENDERED_LINE_CHARS)}…`:line}function isPlainObject8(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function parseEntries(raw){let lines=raw.split(/\r?\n/),entries2=[];for(let line of lines){if(line.trim().length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}if(!isPlainObject8(parsed))continue;if(typeof parsed.ts!=="string")continue;if(typeof parsed.sessionID!=="string")continue;if(typeof parsed.agent!=="string")continue;if(typeof parsed.tool!=="string")continue;let entry={ts:parsed.ts,sessionID:parsed.sessionID,agent:parsed.agent,tool:parsed.tool};if(typeof parsed.type==="string")entry.type=parsed.type;if(typeof parsed.command==="string")entry.command=parsed.command;if(typeof parsed.path==="string")entry.path=parsed.path;if(typeof parsed.commandHash==="string")entry.commandHash=parsed.commandHash;entries2.push(entry)}return entries2}async function handleGuardrailLog(directory,args2){let window2=readShellAuditTail(directory),entries2=parseEntries(window2.text),blocksOnly=args2.includes("--blocks-only");if(entries2.length===0){let folded2=getShellAuditFoldedSummary(directory);if(folded2!==null&&folded2.totalDecisions>0){let note=`${folded2.totalDecisions} earlier decision(s) compacted into the audit manifest.`;return blocksOnly?`No guardrail block decisions in the read window; ${note}`:`No guardrail decisions in the read window; ${note}`}return blocksOnly?"No guardrail block decisions recorded yet.":"No guardrail decisions recorded yet."}let filtered=blocksOnly?entries2.filter(isBlockEntry):entries2;if(filtered.length===0){let folded2=getShellAuditFoldedSummary(directory);if(blocksOnly&&folded2!==null){let foldedBlocks=[...BLOCK_TYPES].reduce((sum,type)=>sum+(folded2.byType[type]??0),0);if(foldedBlocks>0)return`No guardrail block decisions in the read window; ${foldedBlocks} earlier block decision(s) compacted into the audit manifest.`}if(blocksOnly)return"No guardrail block decisions recorded yet.";return"No guardrail decisions recorded yet."}filtered.sort((a,b)=>{let diff=b.ts.localeCompare(a.ts);return diff===0?0:diff});let rendered=filtered.slice(0,MAX_RENDERED_ENTRIES),header=blocksOnly?"# Guardrail Block Log (most-recent-first)":"# Guardrail Decision Log (most-recent-first)",body=rendered.map(formatEntry).join(`
4368
+ `):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(`
4369
+ `)}var init_guardrail_explain_service=__esm(()=>{init_tool_policy();init_audit_log();init_destructive_command();init_file_authority();init_helpers();init_tool_before();init_shell_executor_context();init_shell_executor_context();init_shell_write_detect();init_command_classifier()});var exports_guardrail_explain={};__export(exports_guardrail_explain,{handleGuardrailExplain:()=>handleGuardrailExplain});var init_guardrail_explain=__esm(()=>{init_guardrail_explain_service()});function isBlockEntry(entry){if(entry.type===null||entry.type===void 0)return!1;return BLOCK_TYPES.has(entry.type)}function redactSummary(entry){if(entry.type==="file_write"||entry.type==="scope_violation"){let raw=entry.path??"";return redactPath(raw)}if(entry.type==="destructive_block"||entry.type==="sandbox_wrap"||entry.type==="sandbox_skip"||entry.type==="shell"||entry.type===null||entry.type===void 0){let raw=entry.command??"";return redactShellCommand(raw)}return""}function sanitizeDisplayText(value){return value.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g,"").replace(/[\u202a-\u202e\u2066-\u2069]/g,"").replace(/[\u200e\u200f\u200b-\u200d\u2060-\u2064\ufeff]/g,"")}function formatEntry(entry){let decisionType=entry.type??"shell",summary=redactSummary(entry),line=`- [${sanitizeDisplayText(entry.ts)}] ${sanitizeDisplayText(decisionType)} | agent: ${sanitizeDisplayText(entry.agent)} | ${sanitizeDisplayText(summary)}`;if(entry.commandHash!==void 0)line+=` · fp:${sanitizeDisplayText(entry.commandHash)}`;return line.length>MAX_RENDERED_LINE_CHARS?`${line.slice(0,MAX_RENDERED_LINE_CHARS)}…`:line}function isPlainObject8(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function parseEntries(raw){let lines=raw.split(/\r?\n/),entries2=[];for(let line of lines){if(line.trim().length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}if(!isPlainObject8(parsed))continue;if(typeof parsed.ts!=="string")continue;if(typeof parsed.sessionID!=="string")continue;if(typeof parsed.agent!=="string")continue;if(typeof parsed.tool!=="string")continue;let entry={ts:parsed.ts,sessionID:parsed.sessionID,agent:parsed.agent,tool:parsed.tool};if(typeof parsed.type==="string")entry.type=parsed.type;if(typeof parsed.command==="string")entry.command=parsed.command;if(typeof parsed.path==="string")entry.path=parsed.path;if(typeof parsed.commandHash==="string")entry.commandHash=parsed.commandHash;entries2.push(entry)}return entries2}async function handleGuardrailLog(directory,args2){let window2=readShellAuditTail(directory),entries2=parseEntries(window2.text),blocksOnly=args2.includes("--blocks-only");if(entries2.length===0){let folded2=getShellAuditFoldedSummary(directory);if(folded2!==null&&folded2.totalDecisions>0){let note=`${folded2.totalDecisions} earlier decision(s) compacted into the audit manifest.`;return blocksOnly?`No guardrail block decisions in the read window; ${note}`:`No guardrail decisions in the read window; ${note}`}return blocksOnly?"No guardrail block decisions recorded yet.":"No guardrail decisions recorded yet."}let filtered=blocksOnly?entries2.filter(isBlockEntry):entries2;if(filtered.length===0){let folded2=getShellAuditFoldedSummary(directory);if(blocksOnly&&folded2!==null){let foldedBlocks=[...BLOCK_TYPES].reduce((sum,type)=>sum+(folded2.byType[type]??0),0);if(foldedBlocks>0)return`No guardrail block decisions in the read window; ${foldedBlocks} earlier block decision(s) compacted into the audit manifest.`}if(blocksOnly)return"No guardrail block decisions recorded yet.";return"No guardrail decisions recorded yet."}filtered.sort((a,b)=>{let diff=b.ts.localeCompare(a.ts);return diff===0?0:diff});let rendered=filtered.slice(0,MAX_RENDERED_ENTRIES),header=blocksOnly?"# Guardrail Block Log (most-recent-first)":"# Guardrail Decision Log (most-recent-first)",body=rendered.map(formatEntry).join(`
4370
4370
  `),notes=[];if(rendered.length<filtered.length)notes.push(`showing ${rendered.length} most recent of ${filtered.length} matching entries in the read window`);if(window2.truncated||window2.coverage==="truncated")notes.push("read window truncated to the newest bounded tail (older decisions may exist beyond it)");let folded=getShellAuditFoldedSummary(directory);if(folded!==null&&folded.totalDecisions>0)notes.push(`${folded.totalDecisions} earlier decision(s) already compacted into the audit manifest (lifetime total)`);if(notes.length===0)return`${header}
4371
4371
 
4372
4372
  ${body}`;return`${header}
@@ -7465,11 +7465,11 @@ Review before proceeding.`;injectSystemMessage(input.sessionID,message)}}}init_c
7465
7465
 
7466
7466
  `);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_utils();init_timeout();var V2_MODEL_APPLY_TIMEOUT_MS=1e4,DEFAULT_V2_MODEL_APPLY_OWNER="__default__",MAX_HELD_APPLY_REGISTRATIONS=128,modelApplyOwners=new Map;function touchModelApplyOwner(token){let existing=modelApplyOwners.get(token);if(existing!==void 0)return modelApplyOwners.delete(token),modelApplyOwners.set(token,existing),existing;let state2={transform:void 0,registrationsByAgent:new Map};return modelApplyOwners.set(token,state2),state2}function disposeHeldRegistrations(owner,label){let held=[...owner.registrationsByAgent.values()];owner.registrationsByAgent.clear();for(let reg of held)reg.dispose().catch((err)=>{log(`v2 model-apply registration dispose failed (${label}; non-fatal)`,{error:err instanceof Error?err.message:String(err)})})}function registerV2AgentTransformSurface(ctx,token){let ownerToken=token??DEFAULT_V2_MODEL_APPLY_OWNER,transform3=ctx?.agent&&typeof ctx.agent.transform==="function"?ctx.agent.transform.bind(ctx.agent):void 0,owner=touchModelApplyOwner(ownerToken);if(owner.transform=transform3,transform3===void 0)log("v2 agent transform surface absent; runtime model apply disabled",{})}function clearV2AgentTransformSurface(token){if(token===void 0){for(let[ownerToken,owner2]of[...modelApplyOwners.entries()])disposeHeldRegistrations(owner2,`clear-all ${ownerToken}`);modelApplyOwners.clear();return}let owner=modelApplyOwners.get(token);if(owner===void 0)return;if(owner.transform=void 0,disposeHeldRegistrations(owner,`owner ${token}`),owner.transform===void 0&&owner.registrationsByAgent.size===0)modelApplyOwners.delete(token)}function resolveActiveModelApplyOwner(){let tokens2=[...modelApplyOwners.keys()];for(let i=tokens2.length-1;i>=0;i-=1){let owner=modelApplyOwners.get(tokens2[i]??"");if(owner?.transform!==void 0)return owner}return}async function applyV2AgentModelOverride(agentName,modelString){let owner=resolveActiveModelApplyOwner(),transform3=owner?.transform;if(owner===void 0||transform3===void 0)return!1;let separator=modelString.indexOf("/");if(typeof agentName!=="string"||agentName.length===0||separator<=0||separator===modelString.length-1)return log("v2 model apply rejected malformed input (non-fatal)",{agentName,modelString}),!1;let providerID=modelString.slice(0,separator),id=modelString.slice(separator+1);try{let applied2=await withTimeout(Promise.resolve(transform3((editor)=>{editor.update(agentName,(agent)=>{agent.model={providerID,id}})})),V2_MODEL_APPLY_TIMEOUT_MS,Error(`[opencode-swarm] v2: model apply for ${agentName} exceeded budget`)),previous=owner.registrationsByAgent.get(agentName);owner.registrationsByAgent.set(agentName,applied2);while(owner.registrationsByAgent.size>MAX_HELD_APPLY_REGISTRATIONS){let oldest=owner.registrationsByAgent.keys().next().value;if(typeof oldest!=="string")break;let evicted=owner.registrationsByAgent.get(oldest);owner.registrationsByAgent.delete(oldest),evicted?.dispose().catch((err)=>{log("v2 evicted model-apply registration dispose failed (non-fatal)",{agentName:oldest,error:err instanceof Error?err.message:String(err)})})}if(previous)previous.dispose().catch((err)=>{log("v2 previous model-apply registration dispose failed (non-fatal)",{agentName,error:err instanceof Error?err.message:String(err)})});return log("v2 agent model applied",{agentName,modelString}),!0}catch(err){return log("v2 agent model apply failed (non-fatal)",{agentName,modelString,error:err instanceof Error?err.message:String(err)}),!1}}init_zod();init_loader();init_model_preflight();init_warning_buffer();init_state();init_utils();init_project_boundary();init_timeout();init_command_dispatch();init_registry2();init_utils2();init_warning_buffer();init_utils();init_timeout();var V2_AGENT_COMMAND_CALL_TIMEOUT_MS=60000,V2_COMMAND_DISPATCH_TIMEOUT_MS=300000,_internals272={dispatchTimeoutMs:V2_COMMAND_DISPATCH_TIMEOUT_MS},V2_OPERATOR_WARNING_BOUND=32,operatorWarningsSeen=new Map,AMBIENT_V2_OWNER="__ambient__",v2OwnerStates=new Map,currentV2OwnerToken=AMBIENT_V2_OWNER,ownerTokenByCtx=new WeakMap,CONFIG_DOCTOR_FIX_POLICY_REFUSAL_MARKER="/swarm config doctor --fix is not available through";function v2OwnerEntry(token,create){let entry=v2OwnerStates.get(token);if(entry===void 0&&create)entry={},v2OwnerStates.set(token,entry);return entry}function dropV2OwnerEntryIfEmpty(token){let entry=v2OwnerStates.get(token);if(entry===void 0)return;if(entry.rebuild===void 0&&entry.quiet===void 0&&entry.snapshot===void 0)v2OwnerStates.delete(token)}function resolveCurrentV2OwnerToken(){if(v2OwnerStates.has(currentV2OwnerToken))return currentV2OwnerToken;return[...v2OwnerStates.keys()].filter((token)=>token!==AMBIENT_V2_OWNER).pop()??AMBIENT_V2_OWNER}function resolveV2OwnerTokenForCtx(ctx){return ownerTokenByCtx.get(ctx)??resolveCurrentV2OwnerToken()}function resolveV2ConfigRebuildSourceForToken(token){let entry=v2OwnerStates.get(token);if(entry?.rebuild!==void 0)return entry.rebuild;return v2OwnerStates.get(AMBIENT_V2_OWNER)?.rebuild}function resolveV2OperatorQuiet(){return resolveV2OperatorQuietForToken(resolveCurrentV2OwnerToken())}function resolveV2OperatorQuietForToken(token){let entry=v2OwnerStates.get(token);if(entry?.quiet!==void 0)return entry.quiet;return v2OwnerStates.get(AMBIENT_V2_OWNER)?.quiet??!1}function resolveV2RegistrationSnapshotForToken(token){return v2OwnerStates.get(token)?.snapshot??v2OwnerStates.get(AMBIENT_V2_OWNER)?.snapshot}function setV2OperatorQuiet(quiet){setV2OperatorQuietForOwner(resolveCurrentV2OwnerToken(),quiet)}function setV2OperatorQuietForOwner(token,quiet){if(quiet===void 0){let existing=v2OwnerStates.get(token);if(existing!==void 0)existing.quiet=void 0,dropV2OwnerEntryIfEmpty(token);return}let entry=v2OwnerEntry(token,!0);if(entry===void 0)return;entry.quiet=quiet,currentV2OwnerToken=token}function deferredV2WarnOperator(message,dedupKey,ownerToken){let key3=dedupKey??message;if(operatorWarningsSeen.has(key3))return;operatorWarningsSeen.set(key3,!0);while(operatorWarningsSeen.size>V2_OPERATOR_WARNING_BOUND){let oldest=operatorWarningsSeen.keys().next().value;if(oldest===void 0)break;operatorWarningsSeen.delete(oldest)}if(addDeferredWarning(message),!(ownerToken!==void 0?resolveV2OperatorQuietForToken(ownerToken):resolveV2OperatorQuiet()))console.warn(message)}function clearV2OwnerRegistrationSnapshot(ownerToken){let entry=v2OwnerStates.get(ownerToken);if(entry!==void 0)entry.snapshot=void 0,dropV2OwnerEntryIfEmpty(ownerToken)}function clearV2CtxOwnerBinding(ctx){ownerTokenByCtx.delete(ctx)}function normalizeV2PermissionAction(action2){if(action2==="write"||action2==="patch")return"edit";if(action2==="task")return"subagent";if(action2==="bash")return"shell";return action2}function migrateV1PermissionBlock(permission){let rules=[];if(!permission||typeof permission!=="object")return rules;for(let[name,value]of Object.entries(permission)){let action2=normalizeV2PermissionAction(name);if(typeof value==="string"){rules.push({action:action2,resource:"*",effect:value});continue}if(value&&typeof value==="object")for(let[resource,effect]of Object.entries(value)){if(typeof effect!=="string")continue;rules.push({action:action2,resource,effect})}}return rules}function mapV1AgentToV2(name,config3){let info={id:name,name,mode:config3.mode==="primary"||config3.mode==="subagent"||config3.mode==="all"?config3.mode:"subagent",hidden:!1,request:{settings:{},headers:{},body:{}}};if(typeof config3.prompt==="string"&&config3.prompt.length>0)info.system=config3.prompt;if(typeof config3.description==="string"&&config3.description.length>0)info.description=config3.description;if(typeof config3.model==="string"&&config3.model.includes("/")){let separator=config3.model.indexOf("/");info.model={providerID:config3.model.slice(0,separator),id:config3.model.slice(separator+1)}}let rules=migrateV1PermissionBlock(config3.permission);if(rules.length>0)info.permissions=rules;return info}function expandV1Template(template,argumentsText){return template.replaceAll("$ARGUMENTS",argumentsText).trim()}function normalizeV2CommandArguments(text){let trimmed=text.trim();if(trimmed==="/swarm"||trimmed==="swarm")return"";let match=trimmed.match(/^(?:\/swarm|swarm)\s+([\s\S]*)$/);return match!==null?match[1]:trimmed}function extractDispatchedPromptText(parts){let texts=[];for(let part of parts){if(!part||typeof part!=="object")continue;let typed=part;if(typed.type!==void 0&&typed.type!=="text")continue;if(typeof typed.text!=="string")continue;if(typed.text.trim().length===0)continue;texts.push(typed.text)}if(texts.length===0)return null;return texts.join(`
7467
7467
 
7468
- `)}function buildFallbackPromptText(template,argumentsText){if(template.includes("$ARGUMENTS"))return expandV1Template(template,argumentsText);let trimmed=argumentsText.trim();return trimmed.length>0?`${template} ${trimmed}`:template}function isConfigDoctorFixInvocation(key3,argumentsText){let normalized=normalizeSwarmCommandInput(key3,argumentsText);if(!normalized.isSwarmCommand)return!1;let resolved=resolveCommand(normalized.tokens);if(resolved===null)return!1;if(canonicalCommandKey(resolved)!=="config doctor")return!1;return normalized.tokens.includes("--fix")||normalized.tokens.includes("-f")}async function deferredV2ExecuteSwarmCommand(hooks2,key3,template,ctx,invocation,directory,registrations){let dispatchOwnerToken=resolveV2OwnerTokenForCtx(ctx),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key3}),deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} was not run — the host exposes no session prompt surface; the registry handler was skipped.`,`no-prompt-surface:${directory}:${key3}`,dispatchOwnerToken);return}let rawArguments=invocation?.prompt?.text,rawText=typeof rawArguments==="string"?rawArguments:"",delivery=invocation?.delivery;log("v2 command invocation",{name:key3,text:rawText.length>200?`${rawText.slice(0,200)}… [+${rawText.length-200} chars]`:rawText,delivery});let argumentsText=normalizeV2CommandArguments(rawText),deliveryPart=delivery!==void 0?{delivery}:{},dispatched=null,hook=hooks2["command.execute.before"];if(typeof hook==="function"){let output={parts:[]},dispatchTimeoutError=Error(`[opencode-swarm] v2: command ${key3} dispatch exceeded budget`),dispatchStartedAt=Date.now();try{await withTimeout(Promise.resolve(hook({command:key3,sessionID:invocation.sessionID,arguments:argumentsText},output)),_internals272.dispatchTimeoutMs,dispatchTimeoutError),dispatched=extractDispatchedPromptText(output.parts)}catch(err){if(err===dispatchTimeoutError){let budgetSeconds=_internals272.dispatchTimeoutMs/1000;try{await withTimeout(Promise.resolve(prompt({sessionID:invocation.sessionID,text:`[opencode-swarm] v2: command ${key3} dispatch exceeded its ${budgetSeconds}s budget; the command may still be completing `+"in the background — check its status before re-running.",...deliveryPart})),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key3} prompt exceeded budget`))}catch(noticeErr){log("v2 command timeout notice submission failed",{name:key3,error:noticeErr instanceof Error?noticeErr.message:String(noticeErr)})}return}log("v2 command dispatch failed (falling back to template)",{name:key3,error:err instanceof Error?err.message:String(err)}),deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} dispatch failed (${err instanceof Error?err.message:String(err)}); the expanded template fallback was submitted.`,`dispatch-failed:${key3}`,dispatchOwnerToken)}let configDoctorFixInvocation=isConfigDoctorFixInvocation(key3,argumentsText),policyRefused=configDoctorFixInvocation&&dispatched!==null&&dispatched.includes(CONFIG_DOCTOR_FIX_POLICY_REFUSAL_MARKER);if(dispatched===null){let swallowed=getLastSwallowedCommandError(invocation.sessionID,key3,dispatchStartedAt);if(swallowed!==void 0)deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} handler failed (${swallowed}); the expanded template fallback was submitted.`,`handler-failed:${invocation.sessionID}:${key3}`,dispatchOwnerToken)}if(configDoctorFixInvocation&&!policyRefused&&dispatched!==null&&getLastSwallowedCommandError(invocation.sessionID,key3,dispatchStartedAt)===void 0)await deferredV2RefreshRegistrations(ctx,hooks2,directory,registrations)}let text=dispatched??buildFallbackPromptText(template,argumentsText);try{await withTimeout(Promise.resolve(prompt({sessionID:invocation.sessionID,text,...deliveryPart})),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key3} prompt exceeded budget`))}catch(err){log("v2 command prompt submission failed",{name:key3,error:err instanceof Error?err.message:String(err)}),deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} prompt submission failed (${err instanceof Error?err.message:String(err)}); the handler output was not delivered to the session.`,`prompt-failed:${invocation.sessionID}:${key3}`,dispatchOwnerToken)}}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations,ownerToken){if(ownerToken!==void 0)ownerTokenByCtx.set(ctx,ownerToken);if(typeof hooks2.config!=="function")return;let syntheticConfig={};try{await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"))}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 synthetic config-hook run failed (non-fatal)",{error:message}),deferredV2WarnOperator(`[opencode-swarm] v2: command registration failed — the shared config-hook run errored (${message}); no agents or commands were registered.`,`registration-config-hook-failed:${directory}`,ownerToken);return}let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},registrationSnapshot={agentTable,commandTable,dirtyAgent:!1,dirtyCommand:!1},ownerEntry=v2OwnerEntry(ownerToken??resolveCurrentV2OwnerToken(),!0);if(ownerEntry!==void 0)ownerEntry.snapshot=registrationSnapshot;let agentLanded=!1;try{let agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(registrationSnapshot.agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{let existingPermissions=Array.isArray(agent.permissions)?[...agent.permissions]:[];if(Object.assign(agent,mapped),mapped.permissions!==void 0)agent.permissions=[...existingPermissions,...mapped.permissions]})}}),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration),agentLanded=!0}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 agent transform failed (non-fatal)",{error:message}),deferredV2WarnOperator(`[opencode-swarm] v2: agent registration failed (${message}); no v2 agents were registered.`,`agent-registration-failed:${directory}`,ownerToken)}let commandLanded=!1;try{let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key3,entry]of Object.entries(registrationSnapshot.commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key3,description:typeof entry.description==="string"?entry.description:void 0,execute:(invocation)=>deferredV2ExecuteSwarmCommand(hooks2,key3,template,ctx,invocation,directory,registrations)};editor.add(definition)}}),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),commandLanded=!0}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 command transform failed (non-fatal)",{error:message}),deferredV2WarnOperator(`[opencode-swarm] v2: command registration failed (${message}); the v2 command table was not registered.`,`command-registration-failed:${directory}`,ownerToken)}if(log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length}),!agentLanded&&!commandLanded)throw Error("[opencode-swarm] v2: agent and command registrations both failed")}function registerV2ConfigRebuildSourceForOwner(token,rebuild){if(rebuild===void 0){let entry2=v2OwnerStates.get(token);if(entry2!==void 0)entry2.rebuild=void 0,dropV2OwnerEntryIfEmpty(token);return}let entry=v2OwnerEntry(token,!0);if(entry===void 0)return;entry.rebuild=rebuild,currentV2OwnerToken=token}async function deferredV2ReloadRegistrationDomain(ctx,domain3){let reload=ctx[domain3]?.reload;if(typeof reload!=="function")return!1;try{return await withTimeout(Promise.resolve(reload()),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error(`[opencode-swarm] v2: ${domain3} registration reload exceeded budget`)),!0}catch(err){return log(`v2 ${domain3} registration reload failed (non-fatal)`,{error:err instanceof Error?err.message:String(err)}),!1}}async function deferredV2RefreshRegistrations(ctx,hooks2,directory,registrations){let ownerToken=resolveV2OwnerTokenForCtx(ctx),rebuild=resolveV2ConfigRebuildSourceForToken(ownerToken);if(rebuild===void 0){deferredV2WarnOperator("[opencode-swarm] v2: registration refresh skipped — no config rebuild source is registered on this host; the registration tables were not reloaded.",`refresh-no-rebuild-source:${directory}`,ownerToken);return}let tables;try{tables=await withTimeout(Promise.resolve(rebuild(directory)),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: registration rebuild exceeded budget"))}catch(err){deferredV2WarnOperator(`[opencode-swarm] v2: registration refresh failed — the config rebuild source errored (${err instanceof Error?err.message:String(err)}); the registration tables were not reloaded.`,`refresh-rebuild-failed:${directory}`,ownerToken);return}let snapshot=resolveV2RegistrationSnapshotForToken(ownerToken);if(snapshot===void 0){log("v2 registration refresh skipped — no registration snapshot",{directory});return}if(!(snapshot.dirtyAgent||snapshot.dirtyCommand||JSON.stringify(snapshot.agentTable)!==JSON.stringify(tables.agentTable)||JSON.stringify(snapshot.commandTable)!==JSON.stringify(tables.commandTable))){log("v2 registration refresh — tables unchanged, no reload",{directory,registrations:registrations?.length??0,hooksConfigPresent:typeof hooks2.config==="function"});return}snapshot.agentTable=tables.agentTable,snapshot.commandTable=tables.commandTable;let agentReloaded=await deferredV2ReloadRegistrationDomain(ctx,"agent");snapshot.dirtyAgent=!agentReloaded;let commandReloaded=await deferredV2ReloadRegistrationDomain(ctx,"command");if(snapshot.dirtyCommand=!commandReloaded,!agentReloaded||!commandReloaded){let failed=[agentReloaded?void 0:"agent",commandReloaded?void 0:"command"].filter((domain3)=>domain3!==void 0).join(", ");deferredV2WarnOperator(`[opencode-swarm] v2: registration tables changed but the ${failed} domain reload failed; the domain stays marked dirty and the next refresh retries it.`,`refresh-reload-failed:${directory}`,ownerToken)}log("v2 registration tables refreshed",{directory,registrations:registrations?.length??0,agentReloaded,commandReloaded})}init_task_model_routing();init_utils();init_timeout();init_state2();init_normalize_tool_name();init_warning_buffer();init_utils();init_timeout();var DEFAULT_CONFIG2={oversightTotalMs:120000},budgets=new Map;function finitePositive(value){return typeof value==="number"&&Number.isFinite(value)&&value>0?value:void 0}function configureV2ToolBeforeBudget(fullAuto,directory){let oversight=fullAuto?.oversight,hook=finitePositive(oversight?.hook_timeout_ms),key3=directory??"";if(!budgets.has(key3)&&budgets.size>=64){let oldest=budgets.keys().next().value;if(oldest!==void 0)budgets.delete(oldest)}budgets.set(key3,{...hook!==void 0?{hookTimeoutMs:Math.min(900000,Math.round(hook))}:{},oversightTotalMs:finitePositive(oversight?.total_timeout_ms)??120000})}function resolveV2ToolBeforeBudgetMs(fullAutoActive,directory){let cfg=(directory!==void 0?budgets.get(directory):void 0)??budgets.get("")??DEFAULT_CONFIG2;if(cfg.hookTimeoutMs!==void 0)return cfg.hookTimeoutMs;if(!fullAutoActive)return 60000;return Math.min(900000,Math.max(60000,cfg.oversightTotalMs+30000))}function resetV2ToolBeforeBudget(directory){if(directory===void 0)budgets.clear();else budgets.delete(directory)}var V2_HOOK_TIMEOUT_MS=60000;function isV2SubagentToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.subagent$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="subagent"}function isV2CodeModeWrapper(event){return event.tool==="execute"&&isPlainObject9(event.input)&&typeof event.input.code==="string"}function isPlainObject9(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function mapV2SubagentArgsToV1(input){if(!isPlainObject9(input))return input;let mapped={};for(let[key3,value]of Object.entries(input))if(key3==="agent")mapped.subagent_type=value;else if(key3==="sessionID")mapped.task_id=value;else mapped[key3]=value;return mapped}function mapV1TaskArgsToV2(args2){if(!isPlainObject9(args2))return args2;let mapped={};for(let[key3,value]of Object.entries(args2))if(key3==="subagent_type")mapped.agent=value;else if(key3==="task_id")mapped.sessionID=value;else mapped[key3]=value;return mapped}var V2_SUBAGENT_WRAPPER_RE=/<subagent\s+sessionID="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"[^>]*>/,MAX_V2_WRAPPER_INNER_CHARS=20000;function parseV2SubagentWrapper(content){if(typeof content!=="string")return null;let match=content.match(V2_SUBAGENT_WRAPPER_RE);if(!match)return null;let sessionID=match[1];if(sessionID.includes("<")||sessionID.includes(">"))return null;let rawState=match[2],matchStart=match.index??0,inner=content.slice(matchStart+match[0].length).replace(/\s*<\/subagent>\s*$/,"");return{sessionID,state:rawState==="canceled"?"cancelled":rawState,inner}}var V2_WRAPPER_STRUCTURAL_TAG_RE=/<\/?(?:task_result|task_error|summary)>/g;function renderV1TaskEnvelopeFromV2(wrapper){let inner=wrapper.inner;if(inner.length>MAX_V2_WRAPPER_INNER_CHARS){let omitted=inner.length-MAX_V2_WRAPPER_INNER_CHARS;inner=`${inner.slice(0,MAX_V2_WRAPPER_INNER_CHARS)}
7468
+ `)}function buildFallbackPromptText(template,argumentsText){if(template.includes("$ARGUMENTS"))return expandV1Template(template,argumentsText);let trimmed=argumentsText.trim();return trimmed.length>0?`${template} ${trimmed}`:template}function isConfigDoctorFixInvocation(key3,argumentsText){let normalized=normalizeSwarmCommandInput(key3,argumentsText);if(!normalized.isSwarmCommand)return!1;let resolved=resolveCommand(normalized.tokens);if(resolved===null)return!1;if(canonicalCommandKey(resolved)!=="config doctor")return!1;return normalized.tokens.includes("--fix")||normalized.tokens.includes("-f")}async function deferredV2ExecuteSwarmCommand(hooks2,key3,template,ctx,invocation,directory,registrations){let dispatchOwnerToken=resolveV2OwnerTokenForCtx(ctx),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key3}),deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} was not run — the host exposes no session prompt surface; the registry handler was skipped.`,`no-prompt-surface:${directory}:${key3}`,dispatchOwnerToken);return}let rawArguments=invocation?.prompt?.text,rawText=typeof rawArguments==="string"?rawArguments:"",delivery=invocation?.delivery;log("v2 command invocation",{name:key3,text:rawText.length>200?`${rawText.slice(0,200)}… [+${rawText.length-200} chars]`:rawText,delivery});let argumentsText=normalizeV2CommandArguments(rawText),deliveryPart=delivery!==void 0?{delivery}:{},dispatched=null,hook=hooks2["command.execute.before"];if(typeof hook==="function"){let output={parts:[]},dispatchTimeoutError=Error(`[opencode-swarm] v2: command ${key3} dispatch exceeded budget`),dispatchStartedAt=Date.now();try{await withTimeout(Promise.resolve(hook({command:key3,sessionID:invocation.sessionID,arguments:argumentsText},output)),_internals272.dispatchTimeoutMs,dispatchTimeoutError),dispatched=extractDispatchedPromptText(output.parts)}catch(err){if(err===dispatchTimeoutError){let budgetSeconds=_internals272.dispatchTimeoutMs/1000;try{await withTimeout(Promise.resolve(prompt({sessionID:invocation.sessionID,text:`[opencode-swarm] v2: command ${key3} dispatch exceeded its ${budgetSeconds}s budget; the command may still be completing `+"in the background — check its status before re-running.",...deliveryPart})),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key3} prompt exceeded budget`))}catch(noticeErr){log("v2 command timeout notice submission failed",{name:key3,error:noticeErr instanceof Error?noticeErr.message:String(noticeErr)})}return}log("v2 command dispatch failed (falling back to template)",{name:key3,error:err instanceof Error?err.message:String(err)}),deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} dispatch failed (${err instanceof Error?err.message:String(err)}); the expanded template fallback was submitted.`,`dispatch-failed:${key3}`,dispatchOwnerToken)}let configDoctorFixInvocation=isConfigDoctorFixInvocation(key3,argumentsText),policyRefused=configDoctorFixInvocation&&dispatched!==null&&dispatched.includes(CONFIG_DOCTOR_FIX_POLICY_REFUSAL_MARKER);if(dispatched===null){let swallowed=getLastSwallowedCommandError(invocation.sessionID,key3,dispatchStartedAt);if(swallowed!==void 0)deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} handler failed (${swallowed}); the expanded template fallback was submitted.`,`handler-failed:${invocation.sessionID}:${key3}`,dispatchOwnerToken)}if(configDoctorFixInvocation&&!policyRefused&&dispatched!==null&&getLastSwallowedCommandError(invocation.sessionID,key3,dispatchStartedAt)===void 0)await deferredV2RefreshRegistrations(ctx,hooks2,directory,registrations)}let text=dispatched??buildFallbackPromptText(template,argumentsText);try{await withTimeout(Promise.resolve(prompt({sessionID:invocation.sessionID,text,...deliveryPart})),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key3} prompt exceeded budget`))}catch(err){log("v2 command prompt submission failed",{name:key3,error:err instanceof Error?err.message:String(err)}),deferredV2WarnOperator(`[opencode-swarm] v2: command ${key3} prompt submission failed (${err instanceof Error?err.message:String(err)}); the handler output was not delivered to the session.`,`prompt-failed:${invocation.sessionID}:${key3}`,dispatchOwnerToken)}}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations,ownerToken){if(ownerToken!==void 0)ownerTokenByCtx.set(ctx,ownerToken);if(typeof hooks2.config!=="function")return;let syntheticConfig={};try{await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"))}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 synthetic config-hook run failed (non-fatal)",{error:message}),deferredV2WarnOperator(`[opencode-swarm] v2: command registration failed — the shared config-hook run errored (${message}); no agents or commands were registered.`,`registration-config-hook-failed:${directory}`,ownerToken);return}let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},registrationSnapshot={agentTable,commandTable,dirtyAgent:!1,dirtyCommand:!1},ownerEntry=v2OwnerEntry(ownerToken??resolveCurrentV2OwnerToken(),!0);if(ownerEntry!==void 0)ownerEntry.snapshot=registrationSnapshot;let agentLanded=!1;try{let agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(registrationSnapshot.agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{let existingPermissions=Array.isArray(agent.permissions)?[...agent.permissions]:[];if(Object.assign(agent,mapped),mapped.permissions!==void 0)agent.permissions=[...existingPermissions,...mapped.permissions]})}}),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration),agentLanded=!0}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 agent transform failed (non-fatal)",{error:message}),deferredV2WarnOperator(`[opencode-swarm] v2: agent registration failed (${message}); no v2 agents were registered.`,`agent-registration-failed:${directory}`,ownerToken)}let commandLanded=!1;try{let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key3,entry]of Object.entries(registrationSnapshot.commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key3,description:typeof entry.description==="string"?entry.description:void 0,execute:(invocation)=>deferredV2ExecuteSwarmCommand(hooks2,key3,template,ctx,invocation,directory,registrations)};editor.add(definition)}}),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),commandLanded=!0}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 command transform failed (non-fatal)",{error:message}),deferredV2WarnOperator(`[opencode-swarm] v2: command registration failed (${message}); the v2 command table was not registered.`,`command-registration-failed:${directory}`,ownerToken)}if(log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length}),!agentLanded&&!commandLanded)throw Error("[opencode-swarm] v2: agent and command registrations both failed")}function registerV2ConfigRebuildSourceForOwner(token,rebuild){if(rebuild===void 0){let entry2=v2OwnerStates.get(token);if(entry2!==void 0)entry2.rebuild=void 0,dropV2OwnerEntryIfEmpty(token);return}let entry=v2OwnerEntry(token,!0);if(entry===void 0)return;entry.rebuild=rebuild,currentV2OwnerToken=token}async function deferredV2ReloadRegistrationDomain(ctx,domain3){let reload=ctx[domain3]?.reload;if(typeof reload!=="function")return!1;try{return await withTimeout(Promise.resolve(reload()),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error(`[opencode-swarm] v2: ${domain3} registration reload exceeded budget`)),!0}catch(err){return log(`v2 ${domain3} registration reload failed (non-fatal)`,{error:err instanceof Error?err.message:String(err)}),!1}}async function deferredV2RefreshRegistrations(ctx,hooks2,directory,registrations){let ownerToken=resolveV2OwnerTokenForCtx(ctx),rebuild=resolveV2ConfigRebuildSourceForToken(ownerToken);if(rebuild===void 0){deferredV2WarnOperator("[opencode-swarm] v2: registration refresh skipped — no config rebuild source is registered on this host; the registration tables were not reloaded.",`refresh-no-rebuild-source:${directory}`,ownerToken);return}let tables;try{tables=await withTimeout(Promise.resolve(rebuild(directory)),V2_AGENT_COMMAND_CALL_TIMEOUT_MS,Error("[opencode-swarm] v2: registration rebuild exceeded budget"))}catch(err){deferredV2WarnOperator(`[opencode-swarm] v2: registration refresh failed — the config rebuild source errored (${err instanceof Error?err.message:String(err)}); the registration tables were not reloaded.`,`refresh-rebuild-failed:${directory}`,ownerToken);return}let snapshot=resolveV2RegistrationSnapshotForToken(ownerToken);if(snapshot===void 0){log("v2 registration refresh skipped — no registration snapshot",{directory});return}if(!(snapshot.dirtyAgent||snapshot.dirtyCommand||JSON.stringify(snapshot.agentTable)!==JSON.stringify(tables.agentTable)||JSON.stringify(snapshot.commandTable)!==JSON.stringify(tables.commandTable))){log("v2 registration refresh — tables unchanged, no reload",{directory,registrations:registrations?.length??0,hooksConfigPresent:typeof hooks2.config==="function"});return}snapshot.agentTable=tables.agentTable,snapshot.commandTable=tables.commandTable;let agentReloaded=await deferredV2ReloadRegistrationDomain(ctx,"agent");snapshot.dirtyAgent=!agentReloaded;let commandReloaded=await deferredV2ReloadRegistrationDomain(ctx,"command");if(snapshot.dirtyCommand=!commandReloaded,!agentReloaded||!commandReloaded){let failed=[agentReloaded?void 0:"agent",commandReloaded?void 0:"command"].filter((domain3)=>domain3!==void 0).join(", ");deferredV2WarnOperator(`[opencode-swarm] v2: registration tables changed but the ${failed} domain reload failed; the domain stays marked dirty and the next refresh retries it.`,`refresh-reload-failed:${directory}`,ownerToken)}log("v2 registration tables refreshed",{directory,registrations:registrations?.length??0,agentReloaded,commandReloaded})}init_task_model_routing();init_utils();init_timeout();init_state2();init_normalize_tool_name();init_shell_executor_context();init_warning_buffer();init_utils();init_timeout();var DEFAULT_CONFIG2={oversightTotalMs:120000},budgets=new Map;function finitePositive(value){return typeof value==="number"&&Number.isFinite(value)&&value>0?value:void 0}function configureV2ToolBeforeBudget(fullAuto,directory){let oversight=fullAuto?.oversight,hook=finitePositive(oversight?.hook_timeout_ms),key3=directory??"";if(!budgets.has(key3)&&budgets.size>=64){let oldest=budgets.keys().next().value;if(oldest!==void 0)budgets.delete(oldest)}budgets.set(key3,{...hook!==void 0?{hookTimeoutMs:Math.min(900000,Math.round(hook))}:{},oversightTotalMs:finitePositive(oversight?.total_timeout_ms)??120000})}function resolveV2ToolBeforeBudgetMs(fullAutoActive,directory){let cfg=(directory!==void 0?budgets.get(directory):void 0)??budgets.get("")??DEFAULT_CONFIG2;if(cfg.hookTimeoutMs!==void 0)return cfg.hookTimeoutMs;if(!fullAutoActive)return 60000;return Math.min(900000,Math.max(60000,cfg.oversightTotalMs+30000))}function resetV2ToolBeforeBudget(directory){if(directory===void 0)budgets.clear();else budgets.delete(directory)}var V2_HOOK_TIMEOUT_MS=60000;function isV2SubagentToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.subagent$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="subagent"}function isV2CodeModeWrapper(event){return event.tool==="execute"&&isPlainObject9(event.input)&&typeof event.input.code==="string"}function isPlainObject9(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function mapV2SubagentArgsToV1(input){if(!isPlainObject9(input))return input;let mapped={};for(let[key3,value]of Object.entries(input))if(key3==="agent")mapped.subagent_type=value;else if(key3==="sessionID")mapped.task_id=value;else mapped[key3]=value;return mapped}function mapV1TaskArgsToV2(args2){if(!isPlainObject9(args2))return args2;let mapped={};for(let[key3,value]of Object.entries(args2))if(key3==="subagent_type")mapped.agent=value;else if(key3==="task_id")mapped.sessionID=value;else mapped[key3]=value;return mapped}var V2_SUBAGENT_WRAPPER_RE=/<subagent\s+sessionID="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"[^>]*>/,MAX_V2_WRAPPER_INNER_CHARS=20000;function parseV2SubagentWrapper(content){if(typeof content!=="string")return null;let match=content.match(V2_SUBAGENT_WRAPPER_RE);if(!match)return null;let sessionID=match[1];if(sessionID.includes("<")||sessionID.includes(">"))return null;let rawState=match[2],matchStart=match.index??0,inner=content.slice(matchStart+match[0].length).replace(/\s*<\/subagent>\s*$/,"");return{sessionID,state:rawState==="canceled"?"cancelled":rawState,inner}}var V2_WRAPPER_STRUCTURAL_TAG_RE=/<\/?(?:task_result|task_error|summary)>/g;function renderV1TaskEnvelopeFromV2(wrapper){let inner=wrapper.inner;if(inner.length>MAX_V2_WRAPPER_INNER_CHARS){let omitted=inner.length-MAX_V2_WRAPPER_INNER_CHARS;inner=`${inner.slice(0,MAX_V2_WRAPPER_INNER_CHARS)}
7469
7469
  [... ${omitted} chars truncated by v2 task translation ...]`}return inner=inner.replace(V2_WRAPPER_STRUCTURAL_TAG_RE,(tag)=>tag.replace("<","<\\")),`<task id="${wrapper.sessionID}" state="${wrapper.state}"><task_result>${inner}</task_result></task>`}function isFullAutoRunActive2(directory,sessionID){try{let status2=loadFullAutoRunState(directory,sessionID)?.status;return status2!==void 0&&status2!=="idle"}catch{return!1}}async function onV2ToolBefore(event,hooks2,directory){let handler=hooks2["tool.execute.before"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let isSubagent2=isV2SubagentToolId(event.tool),wrapperMarked=isV2CodeModeWrapper(event);if(wrapperMarked)recordCodeModeWrapperCall(event.sessionID,event.id);try{let output={args:isSubagent2?mapV2SubagentArgsToV1(event.input):event.input},budgetMs=resolveV2ToolBeforeBudgetMs(isFullAutoRunActive2(directory,event.sessionID),directory);if(await withTimeout(Promise.resolve(handler({tool:isSubagent2?"task":event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),budgetMs,Error(`[opencode-swarm] v2: tool.execute.before exceeded budget (${budgetMs} ms; set full_auto.oversight.hook_timeout_ms to change)`)),isSubagent2){let mapped=mapV1TaskArgsToV2(output.args);if(isPlainObject9(event.input)&&isPlainObject9(mapped)){for(let key3 of Object.keys(event.input))delete event.input[key3];Object.assign(event.input,mapped)}}else event.input=output.args}finally{if(wrapperMarked)clearCodeModeWrapperCall(event.sessionID,event.id)}}async function onV2ToolAfter(event,hooks2,directory){clearCodeModeWrapperCall(event.sessionID,event.id);let handler=hooks2["tool.execute.after"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let isSubagent2=isV2SubagentToolId(event.tool),output=translateV2ResultToV1Output(event,isSubagent2);await withTimeout(Promise.resolve(handler({tool:isSubagent2?"task":event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID,...isSubagent2?{args:mapV2SubagentArgsToV1(event.input)}:{}},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.after exceeded budget")).catch((err)=>{log("v2 tool.execute.after failed (non-fatal)",{tool:event.tool,error:err instanceof Error?err.message:String(err)})})}function translateV2ResultToV1Output(event,isSubagent2){if(event.status==="error")return{title:"error",state:"error",output:event.error&&typeof event.error.message==="string"?event.error.message:"tool error",metadata:{}};let result=event.result,content=typeof result?.content==="string"?result.content:Array.isArray(result?.content)?(result?.content).filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>p.text).join(`
7470
- `):"";if(isSubagent2){let wrapper=parseV2SubagentWrapper(content);if(wrapper)return{title:"",state:wrapper.state==="running"?"running":wrapper.state==="completed"?"completed":wrapper.state==="error"?"error":"cancelled",output:renderV1TaskEnvelopeFromV2(wrapper),metadata:result?.metadata??{}};if(content.includes("<subagent"))log("v2 subagent wrapper not recognized; passing result text through",{chars:content.length})}return{title:"",state:"completed",output:content,metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}function warnV2HookRegistrationFailure(label,err){let message=err instanceof Error?err.message:String(err);log(`v2 ${label} registration failed (non-fatal)`,{error:message}),addDeferredWarning(`[opencode-swarm] v2: ${label} registration failed (${message}); the hook was not installed on this host.`)}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("execute.before",err);return});if(before!==void 0)registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("execute.after",err);return});if(after!==void 0)registrations.push(after);if(before===void 0&&after===void 0)throw Error("[opencode-swarm] v2: execute.before and execute.after registrations both failed")}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("compaction",err);return});if(compaction!==void 0)registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("prompt",err);return});if(prompt!==void 0)registrations.push(prompt);if(compaction===void 0&&prompt===void 0)throw Error("[opencode-swarm] v2: compaction and prompt registrations both failed")}init_canonical_root();init_logger();init_timeout();var SYSTEM_DIRECTIVE_FENCE_OPEN="<swarm_system_directive",MAX_PLACEHOLDER_SESSIONS=64,MAX_RECORDED_SESSION_ERRORS=128,ERROR_RECHECK_ATTEMPTS=3,ERROR_RECHECK_DELAY_MS=50,SIGNAL_LESS_WAIT_CAP_MS=600000,placeholderSessions=new Map,sessionErrors=new Map,placeholderCounter=0;function rememberPlaceholder(id,record3){placeholderSessions.set(id,record3);while(placeholderSessions.size>MAX_PLACEHOLDER_SESSIONS){let oldest=placeholderSessions.keys().next().value;if(oldest===void 0)break;placeholderSessions.delete(oldest)}}function rememberSessionError(sessionId,error93){sessionErrors.set(sessionId,error93);while(sessionErrors.size>MAX_RECORDED_SESSION_ERRORS){let oldest=sessionErrors.keys().next().value;if(oldest===void 0)break;sessionErrors.delete(oldest)}}function recordV2SessionErrorFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.error"&&type!=="session.execution.failed")return;let payload=envelope.data??envelope.properties??{},sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,error93=payload.error;if(sessionID!==void 0&&error93!==void 0)rememberSessionError(sessionID,error93)}function clearV2SessionClientState(){placeholderSessions.clear(),sessionErrors.clear()}function readOnlyToolsToV2Permissions(tools){if(!tools||typeof tools!=="object")return[];let permissions=[];for(let resource of Object.keys(tools)){if(resource.length===0)continue;permissions.push({action:"tool",resource,effect:"deny"})}return permissions}function sameDirectoryLexical(a,b){return canonicalRootKeyLexical(a)===canonicalRootKeyLexical(b)}function isAssistantEntry(entry){if(!entry||typeof entry!=="object")return!1;let record3=entry;if(record3.role==="assistant")return!0;return typeof record3.type==="string"&&record3.type.includes("assistant")}function isUserEntry(entry){if(!entry||typeof entry!=="object")return!1;let record3=entry;if(record3.role==="user")return!0;return typeof record3.type==="string"&&record3.type.includes("user")}function entryText2(entry){if(!entry||typeof entry!=="object")return;let record3=entry;if(typeof record3.text==="string")return record3.text;let blocks=Array.isArray(record3.content)?record3.content:Array.isArray(record3.parts)?record3.parts:void 0;if(!blocks)return;let texts=[];for(let block of blocks)if(block&&typeof block==="object"&&block.type==="text"&&typeof block.text==="string")texts.push(block.text);return texts.length>0?texts.join(`
7470
+ `):"";if(isSubagent2){let wrapper=parseV2SubagentWrapper(content);if(wrapper)return{title:"",state:wrapper.state==="running"?"running":wrapper.state==="completed"?"completed":wrapper.state==="error"?"error":"cancelled",output:renderV1TaskEnvelopeFromV2(wrapper),metadata:result?.metadata??{}};if(content.includes("<subagent"))log("v2 subagent wrapper not recognized; passing result text through",{chars:content.length})}return{title:"",state:"completed",output:content,metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}function warnV2HookRegistrationFailure(label,err){let message=err instanceof Error?err.message:String(err);log(`v2 ${label} registration failed (non-fatal)`,{error:message}),addDeferredWarning(`[opencode-swarm] v2: ${label} registration failed (${message}); the hook was not installed on this host.`)}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("execute.before",err);return});if(before!==void 0)registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("execute.after",err);return});if(after!==void 0)registrations.push(after);if(before===void 0&&after===void 0)throw Error("[opencode-swarm] v2: execute.before and execute.after registrations both failed")}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("compaction",err);return});if(compaction!==void 0)registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("prompt",err);return});if(prompt!==void 0)registrations.push(prompt);if(compaction===void 0&&prompt===void 0)throw Error("[opencode-swarm] v2: compaction and prompt registrations both failed")}async function registerV2ShellHooks(ctx,registrations){let shellDomain=ctx.shell;if(!shellDomain||typeof shellDomain.hook!=="function")return;let registration=await withTimeout(Promise.resolve(shellDomain.hook("create.before",(invocation)=>{let shell=invocation&&typeof invocation.shell==="string"?invocation.shell:"";recordObservedHostShell(shell)})),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: shell.create.before registration exceeded budget")).catch((err)=>{warnV2HookRegistrationFailure("shell.create.before",err);return});if(registration!==void 0&&registration!==null)registrations.push(registration)}init_canonical_root();init_logger();init_timeout();var SYSTEM_DIRECTIVE_FENCE_OPEN="<swarm_system_directive",MAX_PLACEHOLDER_SESSIONS=64,MAX_RECORDED_SESSION_ERRORS=128,ERROR_RECHECK_ATTEMPTS=3,ERROR_RECHECK_DELAY_MS=50,SIGNAL_LESS_WAIT_CAP_MS=600000,placeholderSessions=new Map,sessionErrors=new Map,placeholderCounter=0;function rememberPlaceholder(id,record3){placeholderSessions.set(id,record3);while(placeholderSessions.size>MAX_PLACEHOLDER_SESSIONS){let oldest=placeholderSessions.keys().next().value;if(oldest===void 0)break;placeholderSessions.delete(oldest)}}function rememberSessionError(sessionId,error93){sessionErrors.set(sessionId,error93);while(sessionErrors.size>MAX_RECORDED_SESSION_ERRORS){let oldest=sessionErrors.keys().next().value;if(oldest===void 0)break;sessionErrors.delete(oldest)}}function recordV2SessionErrorFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.error"&&type!=="session.execution.failed")return;let payload=envelope.data??envelope.properties??{},sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,error93=payload.error;if(sessionID!==void 0&&error93!==void 0)rememberSessionError(sessionID,error93)}function clearV2SessionClientState(){placeholderSessions.clear(),sessionErrors.clear()}function readOnlyToolsToV2Permissions(tools){if(!tools||typeof tools!=="object")return[];let permissions=[];for(let resource of Object.keys(tools)){if(resource.length===0)continue;permissions.push({action:"tool",resource,effect:"deny"})}return permissions}function sameDirectoryLexical(a,b){return canonicalRootKeyLexical(a)===canonicalRootKeyLexical(b)}function isAssistantEntry(entry){if(!entry||typeof entry!=="object")return!1;let record3=entry;if(record3.role==="assistant")return!0;return typeof record3.type==="string"&&record3.type.includes("assistant")}function isUserEntry(entry){if(!entry||typeof entry!=="object")return!1;let record3=entry;if(record3.role==="user")return!0;return typeof record3.type==="string"&&record3.type.includes("user")}function entryText2(entry){if(!entry||typeof entry!=="object")return;let record3=entry;if(typeof record3.text==="string")return record3.text;let blocks=Array.isArray(record3.content)?record3.content:Array.isArray(record3.parts)?record3.parts:void 0;if(!blocks)return;let texts=[];for(let block of blocks)if(block&&typeof block==="object"&&block.type==="text"&&typeof block.text==="string")texts.push(block.text);return texts.length>0?texts.join(`
7471
7471
  `):void 0}function entryModelIds(entry){if(!entry||typeof entry!=="object")return{};let record3=entry,providerID=typeof record3.model?.providerID==="string"?record3.model.providerID:typeof record3.providerID==="string"?record3.providerID:void 0,modelID=typeof record3.model?.id==="string"?record3.model.id:typeof record3.modelID==="string"?record3.modelID:void 0;return{providerID,modelID}}function idleOutcome(entries2){for(let i=entries2.length-1;i>=0;i-=1){let entry=entries2[i];if(!entry||typeof entry!=="object")continue;let record3=entry;if(record3.type!=="idle")continue;return typeof record3.outcome==="string"?record3.outcome:void 0}return}function recordedErrorToInfoError(error93){if(error93&&typeof error93==="object"){let record3=error93,message=typeof record3.data?.message==="string"&&record3.data.message.length>0?record3.data.message:typeof record3.message==="string"&&record3.message.length>0?record3.message:"no message",statusCodeValue=typeof record3.data?.statusCode==="number"&&Number.isFinite(record3.data.statusCode)?record3.data.statusCode:typeof record3.statusCode==="number"&&Number.isFinite(record3.statusCode)?record3.statusCode:typeof record3.status==="number"&&Number.isFinite(record3.status)?record3.status:void 0;return{name:typeof record3.name==="string"&&record3.name.length>0?record3.name.slice(0,64):"ProviderError",data:{message,...statusCodeValue===void 0?{}:{statusCode:statusCodeValue}}}}return{name:"ProviderError",data:{message:"v2 session failed without recorded error detail"}}}function classifyContextEntries(entries2){let lastUserIndex=entries2.reduce((last,entry,index)=>isUserEntry(entry)?index:last,-1),assistantEntries=entries2.slice(lastUserIndex+1).filter(isAssistantEntry),texts=assistantEntries.map(entryText2).filter((text)=>typeof text==="string"),outcome=idleOutcome(entries2);return{outcome,texts,model:assistantEntries.reduce((acc,entry)=>{let ids=entryModelIds(entry);if(ids.providerID!==void 0&&ids.modelID!==void 0)return{providerID:ids.providerID,modelID:ids.modelID};return acc},{}),needsErrorLookup:outcome==="failed"||outcome===void 0&&texts.length===0}}function buildTranslatedPromptData(classification,recordedError){if(classification.needsErrorLookup||recordedError!==void 0)return{info:{error:recordedErrorToInfoError(recordedError)},parts:[]};return{info:classification.model,parts:classification.texts.map((text)=>({type:"text",text}))}}async function deferredV2SessionErrorRecheck(realId){for(let attempt=0;attempt<ERROR_RECHECK_ATTEMPTS;attempt+=1){if(sessionErrors.has(realId))return sessionErrors.get(realId);if(attempt<ERROR_RECHECK_ATTEMPTS-1)await new Promise((resolve124)=>setTimeout(resolve124,ERROR_RECHECK_DELAY_MS))}return}async function deferredV2SessionTranslate(entries2,sessionId){let classification=classifyContextEntries(entries2),recordedError=sessionErrors.get(sessionId);if(classification.needsErrorLookup&&recordedError===void 0)recordedError=await deferredV2SessionErrorRecheck(sessionId);return buildTranslatedPromptData(classification,recordedError)}async function deferredV2SessionGetParentDirectory(ctx,parentID){let info=await ctx.session.get({sessionID:parentID});if(!info||typeof info!=="object")return;let location=info.location;return typeof location?.directory==="string"?location.directory:void 0}async function deferredV2SessionWait(ctx,realId,signal2){if(signal2?.aborted)throw await ctx.session.interrupt({sessionID:realId}).catch(()=>{return}),Error("v2 session-client: prompt wait aborted");await new Promise((resolve124,reject3)=>{let settled=!1,timer=signal2===void 0?setTimeout(()=>{if(settled)return;settled=!0,ctx.session.interrupt({sessionID:realId}).catch(()=>{return}).finally(()=>{reject3(Error("v2 session-client: signal-less prompt wait exceeded cap"))})},SIGNAL_LESS_WAIT_CAP_MS):void 0,onAbort=()=>{if(settled)return;if(settled=!0,timer!==void 0)clearTimeout(timer);ctx.session.interrupt({sessionID:realId}).catch(()=>{return}).finally(()=>{reject3(Error("v2 session-client: prompt wait aborted"))})};signal2?.addEventListener("abort",onAbort,{once:!0}),Promise.resolve(ctx.session.wait({sessionID:realId})).then(()=>{if(settled)return;if(settled=!0,timer!==void 0)clearTimeout(timer);signal2?.removeEventListener("abort",onAbort),resolve124()}).catch((error93)=>{if(settled)return;if(settled=!0,timer!==void 0)clearTimeout(timer);signal2?.removeEventListener("abort",onAbort),reject3(error93 instanceof Error?error93:String(error93))})})}function makeV2SessionContextHandler(realId,system,tools){return(event)=>{let typed=event;if(!typed||typed.sessionID!==realId)return Promise.resolve();if(system!==void 0&&Array.isArray(typed.system)){let fenced=typed.system.filter((part)=>part&&typeof part.text==="string"&&part.text.includes(SYSTEM_DIRECTIVE_FENCE_OPEN));typed.system.length=0,typed.system.push(...fenced.map((part)=>({type:"text",text:part.text})),{type:"text",text:system})}if(tools&&typed.tools&&typeof typed.tools==="object"){let deleted=0;for(let name of Object.keys(tools))if(Object.hasOwn(typed.tools,name))delete typed.tools[name],deleted+=1;if(deleted>0)log("v2 session-client: denied tools via context hook",{count:deleted})}return Promise.resolve()}}function promptBodyText(parts){if(!Array.isArray(parts))return"";let texts=[];for(let part of parts)if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")texts.push(part.text);return texts.join(`
7472
- `)}async function deferredV2SessionPromptPlaceholder(ctx,_placeholderId,stash,body,text,signal2){if(stash.promptStarted=!0,signal2?.aborted)throw Error("v2 session-client: prompt wait aborted");let previousRealId=stash.realId;if(previousRealId!==void 0)stash.realId=void 0,stash.abortPending=!1,stash.deletePending=!1,await ctx.session.remove({sessionID:previousRealId}).catch(()=>{return});let agent=typeof body.agent==="string"?body.agent:void 0,model=body.model&&typeof body.model.providerID==="string"&&typeof body.model.modelID==="string"?{id:body.model.modelID,providerID:body.model.providerID}:void 0,system=typeof body.system==="string"?body.system:void 0,createdRecord=await ctx.session.create({...stash.parentID!==void 0?{parentID:stash.parentID}:{},...stash.title!==void 0?{title:stash.title}:{},...agent!==void 0?{agent}:{},...model!==void 0?{model}:{},location:{directory:stash.directory},permissions:readOnlyToolsToV2Permissions(body.tools)}),realId=typeof createdRecord?.id==="string"?createdRecord.id:void 0;if(realId===void 0)throw Error("v2 session-client: session create returned no id");let echoedDirectory=typeof createdRecord.location?.directory==="string"?createdRecord.location.directory:void 0;if(echoedDirectory!==void 0&&!sameDirectoryLexical(echoedDirectory,stash.directory))throw await ctx.session.remove({sessionID:realId}).catch(()=>{return}),Error(`v2 session-client: created session landed in ${echoedDirectory}, not the requested ${stash.directory} (#3169 Phase 0 C1)`);sessionErrors.delete(realId);let registration;try{if(system!==void 0||body.tools!==void 0)registration=await ctx.session.hook("context",makeV2SessionContextHandler(realId,system,body.tools));await ctx.session.prompt({sessionID:realId,text}),await deferredV2SessionWait(ctx,realId,signal2);let entries2=await ctx.session.context({sessionID:realId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],realId)}}finally{if(stash.realId=realId,registration?.dispose)await registration.dispose().catch(()=>{return});if(stash.abortPending)await ctx.session.interrupt({sessionID:realId}).catch(()=>{return});if(stash.deletePending)sessionErrors.delete(realId),await ctx.session.remove({sessionID:realId}).catch(()=>{return})}}async function deferredV2SessionPromptReal(ctx,sessionId,body,text,signal2){if(typeof body.agent==="string"){let switchAgent=ctx.session.switchAgent;if(typeof switchAgent==="function")await switchAgent({sessionID:sessionId,agent:body.agent})}sessionErrors.delete(sessionId),await ctx.session.prompt({sessionID:sessionId,text}),await deferredV2SessionWait(ctx,sessionId,signal2);let entries2=await ctx.session.context({sessionID:sessionId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],sessionId)}}function resolveSessionId(id){let stash=placeholderSessions.get(id);if(stash===void 0)return id;return stash.realId}function createV2SessionClient(ctx){let session=ctx?.session;if(!session||typeof session!=="object")return;for(let member of["create","get","remove","prompt","wait","context","interrupt","hook"])if(typeof session[member]!=="function")return;return{session:{create:(args2)=>deferredV2SessionCreate(ctx,args2),prompt:(args2)=>deferredV2SessionPrompt(ctx,args2),abort:(args2)=>{let id=args2?.path?.id,resolved=resolveSessionId(id);if(resolved!==void 0)return ctx.session.interrupt({sessionID:resolved}).catch(()=>{return});let stash=placeholderSessions.get(id);if(stash?.promptStarted)stash.abortPending=!0;return Promise.resolve(void 0)},delete:(args2)=>{let id=args2?.path?.id,stash=placeholderSessions.get(id),resolved=resolveSessionId(id);if(resolved!==void 0)return sessionErrors.delete(resolved),deferredV2SessionRemoveEager(ctx,resolved).then((outcome)=>{if(stash?.eager===!0&&outcome.ok)placeholderSessions.delete(id);else if(stash?.eager===!0)log("v2 session-client: eager delete cleanup failed",{reason:outcome.reason})});if(stash?.promptStarted)stash.deletePending=!0;return Promise.resolve(void 0)},get:(args2)=>{let id=args2?.path?.id,stash=placeholderSessions.get(id),overlayParentID=stash?.eager===!0&&typeof stash.parentID==="string"?stash.parentID:void 0,resolved=resolveSessionId(id);if(resolved===void 0)return Promise.resolve({data:null});return ctx.session.get({sessionID:resolved}).then((info)=>({data:overlayParentID!==void 0&&info&&typeof info==="object"?{...info,parentID:overlayParentID}:info})).catch((error93)=>({data:null,error:error93}))}}}}var MAX_PATH_IN_MESSAGE_CHARS=200;function boundPathForMessage(path321){if(path321===void 0)return"an unverifiable location";if(path321.length<=MAX_PATH_IN_MESSAGE_CHARS)return path321;return`${path321.slice(0,MAX_PATH_IN_MESSAGE_CHARS)}… (truncated)`}var EAGER_CLEANUP_TIMEOUT_MS=1e4;async function deferredV2SessionRemoveEager(ctx,sessionID){try{return await withTimeout(ctx.session.remove({sessionID}),EAGER_CLEANUP_TIMEOUT_MS,Error(`v2 session-client: eager cleanup of session ${sessionID} exceeded ${EAGER_CLEANUP_TIMEOUT_MS}ms`)),{ok:!0}}catch(error93){return{ok:!1,reason:error93 instanceof Error?error93.message:String(error93)}}}async function deferredV2SessionCreateEager(ctx,parentID,title,directory,signal2){let created;try{created=await ctx.session.create({...title!==void 0?{title}:{},location:{directory}})}catch(error93){return{data:null,error:{message:`v2 session-client: eager lane create failed (${error93 instanceof Error?error93.message:String(error93)})`}}}let createdRecord=created,realId=typeof createdRecord?.id==="string"?createdRecord.id:void 0;if(realId===void 0)return{data:null,error:{message:"v2 session-client: eager lane create returned no id (#3169 Phase 3)"}};if(signal2?.aborted){let compensated=await deferredV2SessionRemoveEager(ctx,realId);if(!compensated.ok)log("v2 session-client: aborted eager create compensation failed",{reason:compensated.reason});return{data:null,error:{message:`v2 session-client: eager lane create aborted by the caller; ${compensated.ok?"the created session was removed":`removing session ${realId} also failed (${compensated.reason??"unknown error"}) — remove it manually`}`,...compensated.ok?{}:{sessionID:realId,cleanupFailed:!0}}}}let landed=typeof createdRecord.location?.directory==="string"?createdRecord.location.directory:void 0;if(landed===void 0){let reported=await ctx.session.get({sessionID:realId}).catch(()=>{return});landed=typeof reported?.location?.directory==="string"?reported.location.directory:void 0}if(landed===void 0||!sameDirectoryLexical(landed,directory)){let removed=await deferredV2SessionRemoveEager(ctx,realId);return{data:null,error:{message:`v2 session-client: eager lane create landed in ${boundPathForMessage(landed)}, not the requested ${boundPathForMessage(directory)} (#3169 Phase 3 placement guard; Phase 0 C1)${removed.ok?"":`; cleanup of session ${realId} also failed (${removed.reason??"unknown error"}) — remove it before retrying`}`,...removed.ok?{}:{sessionID:realId,cleanupFailed:!0}}}}return rememberPlaceholder(realId,{parentID,...title!==void 0?{title}:{},directory,realId,eager:!0}),{data:{id:realId}}}async function deferredV2SessionCreate(ctx,args2){let directory=args2?.query?.directory;if(typeof directory!=="string"||directory.length===0)return{data:null,error:{message:"v2 session-client: create requires query.directory (v1 contract)"}};let parentID=args2?.body?.parentID;if(parentID!==void 0){let parentDirectory=await deferredV2SessionGetParentDirectory(ctx,parentID).catch(()=>{return});if(parentDirectory===void 0)return{data:null,error:{message:"v2 session-client: parent session placement unverifiable (get returned no location.directory — live-verification item on #3169 Phase 2)"}};if(!sameDirectoryLexical(parentDirectory,directory))return deferredV2SessionCreateEager(ctx,parentID,args2?.body?.title,directory,args2?.signal)}placeholderCounter+=1;let placeholderId=`v2shim-${placeholderCounter}-${Math.random().toString(36).slice(2,10)}`;return rememberPlaceholder(placeholderId,{...parentID!==void 0?{parentID}:{},...args2?.body?.title!==void 0?{title:args2.body.title}:{},directory}),{data:{id:placeholderId}}}async function deferredV2SessionPromptEager(ctx,realId,body,text,signal2){if(signal2?.aborted)throw Error("v2 session-client: eager prompt aborted before dispatch");let agent=typeof body.agent==="string"?body.agent:void 0;if(agent!==void 0){let switchAgent=ctx.session.switchAgent;if(typeof switchAgent==="function")await switchAgent({sessionID:realId,agent});else log("v2 session-client: eager prompt skipped switchAgent (host lacks it)",{agent})}let model=body.model&&typeof body.model.providerID==="string"&&typeof body.model.modelID==="string"?{id:body.model.modelID,providerID:body.model.providerID}:void 0;if(model!==void 0){let switchModel=ctx.session.switchModel;if(typeof switchModel==="function")await switchModel({sessionID:realId,model});else log("v2 session-client: eager prompt skipped switchModel (host lacks it)",{model})}let system=typeof body.system==="string"?body.system:void 0;sessionErrors.delete(realId);let registration;try{if(system!==void 0||body.tools!==void 0)registration=await ctx.session.hook("context",makeV2SessionContextHandler(realId,system,body.tools));await ctx.session.prompt({sessionID:realId,text}),await deferredV2SessionWait(ctx,realId,signal2);let entries2=await ctx.session.context({sessionID:realId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],realId)}}finally{if(registration?.dispose)await registration.dispose().catch(()=>{return})}}async function deferredV2SessionPrompt(ctx,args2){let id=args2?.path?.id;if(typeof id!=="string"||id.length===0)return{data:null,error:{message:"v2 session-client: prompt requires path.id"}};let body=args2?.body??{},text=promptBodyText(body.parts),stash=placeholderSessions.get(id);if(stash!==void 0&&stash.eager===!0&&stash.realId!==void 0)return deferredV2SessionPromptEager(ctx,stash.realId,body,text,args2?.signal);if(stash!==void 0)return deferredV2SessionPromptPlaceholder(ctx,id,stash,body,text,args2?.signal);return deferredV2SessionPromptReal(ctx,id,body,text,args2?.signal)}var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function envelopePayload(envelope){return envelope.data??envelope.properties??{}}var MAX_TRACKED_TOOL_NAME_CHARS=256,MAX_DISPATCH_ID_CHARS=256;function isBoundedId(value){return value.trim()!==""&&value.length<=MAX_DISPATCH_ID_CHARS}var MAX_TRACKED_TOOL_NAMES=512,toolNameByDispatchKey=new Map;function rememberToolNameFromEnvelope(envelope){if(envelope?.type!=="session.tool.input.started")return;let payload=envelopePayload(envelope),name=typeof payload.name==="string"?payload.name:void 0;if(!name||name.length>MAX_TRACKED_TOOL_NAME_CHARS)return;if(!isV2SubagentToolId(name))return;let sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,callID=typeof payload.id==="string"?payload.id:void 0;if(!sessionID||!callID)return;if(!isBoundedId(sessionID)||!isBoundedId(callID))return;let key3=dispatchKey2(sessionID,callID);if(toolNameByDispatchKey.delete(key3),toolNameByDispatchKey.size>=MAX_TRACKED_TOOL_NAMES){let oldest=toolNameByDispatchKey.keys().next().value;if(oldest!==void 0)toolNameByDispatchKey.delete(oldest)}toolNameByDispatchKey.set(key3,name)}function dispatchKey2(sessionID,callID){return`${sessionID.length}#${sessionID}${callID}`}function lookupToolNameForDispatch(sessionID,callID){return toolNameByDispatchKey.get(dispatchKey2(sessionID,callID))}function clearToolNameRegistry(){toolNameByDispatchKey.clear()}function readProgressChildSessionID(data){try{let metadata=data.metadata;if(!isPlainObject9(metadata))return;let child=metadata.sessionID;return typeof child==="string"?child:void 0}catch{return}}function mapV2EventToV1(envelope,lookupToolName){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelopePayload(envelope),sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.status":return{type:"session.status",properties:{...sessionID?{sessionID}:{},...data}};case"session.error":case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.tool.progress":{let callID=typeof data.id==="string"?data.id:void 0,childSessionID=readProgressChildSessionID(data),drop=(reason)=>{log("v2 subagent progress dropped",{reason});return};if(!lookupToolName)return drop("no-tool-name-lookup");if(typeof sessionID!=="string"||!isBoundedId(sessionID))return drop("invalid-parent-session");if(!callID||!isBoundedId(callID))return drop("invalid-call-id");if(!childSessionID||!isBoundedId(childSessionID))return drop("invalid-child-session");if(childSessionID===sessionID)return drop("self-referencing-child");let toolName=lookupToolName(sessionID,callID);if(!toolName)return drop("untracked-tool-name");if(!isV2SubagentToolId(toolName))return drop("non-subagent-tool");return{type:"message.part.updated",properties:{part:{type:"tool",tool:"task",callID,sessionID,state:{metadata:{sessionId:childSessionID}}}}}}case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function seedSessionIdentityFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.created"&&type!=="session.agent.selected")return;let payload=envelopePayload(envelope),sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,agent=typeof payload.agent==="string"?payload.agent:void 0;if(sessionID&&agent)recordSessionChatAgent(sessionID,agent)}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;seedSessionIdentityFromEnvelope(envelope),recordV2SessionErrorFromEnvelope(envelope),rememberToolNameFromEnvelope(envelope);let mapped=mapV2EventToV1(envelope,lookupToolNameForDispatch);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function contentParts(message){return Array.isArray(message.content)?message.content:[]}function toV1MessageView(message,sessionID,originIndex,agentName){let textParts=[];for(let part of contentParts(message))if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID,swarmV2Origin:originIndex,...message.role==="user"&&agentName!==void 0?{agent:agentName}:{}},parts:textParts}}function writeBackTextParts(message,parts){if(!Array.isArray(message.content))return;let texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text})),content=[],nextText=0,afterLastText=0;for(let part of message.content)if(part&&typeof part==="object"&&part.type==="text"){if(nextText<texts.length)content.push(texts[nextText++]);afterLastText=content.length}else content.push(part);content.splice(afterLastText,0,...texts.slice(nextText)),message.content=content}function hasNonTextParts(message){if(message.content===void 0)return!1;if(!Array.isArray(message.content))return!0;return message.content.some((part)=>!(part&&typeof part==="object"&&part.type==="text"))}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let eventAgentName=normalizeV2AgentRef(event.agent),messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let originalMessages=[...event.messages??[]],views=originalMessages.map((m,i)=>toV1MessageView(m,sessionID,i,eventAgentName)),originalByView=new Map;for(let i=0;i<views.length;i+=1)originalByView.set(views[i],originalMessages[i]);await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)}),views.length=0,originalByView.clear(),originalMessages.forEach((message,i)=>{let view=toV1MessageView(message,sessionID,i,eventAgentName);views.push(view),originalByView.set(view,message)})});let originalById=new Map;for(let message of originalMessages)if(typeof message.id==="string"&&message.id.length>0)originalById.set(message.id,message);let isCarrier=(view)=>typeof view.info.id==="string"&&view.info.id.startsWith(GUIDANCE_CARRIER_ID_PREFIX),resolved=new Map,taken=new Set,resolve124=(view,message)=>{if(taken.has(message))return;taken.add(message),resolved.set(view,message)},unresolved=[];for(let view of views){let id=view.info.id,exact=originalByView.get(view)??(typeof id==="string"&&id.length>0?originalById.get(id):void 0);if(exact)resolve124(view,exact);else unresolved.push(view)}for(let view of unresolved){let origin=view.info.swarmV2Origin;if(typeof origin!=="number"||!Number.isInteger(origin)||origin<0||origin>=originalMessages.length)continue;let original=originalMessages[origin];if(!isCarrier(view)&&view.info.role!==original.role)continue;resolve124(view,original)}let consumed=new Set,claimed=new Map;event.system=event.system??[];for(let view of views){let source=resolved.get(view);if(isCarrier(view)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});if(source)consumed.add(source)}else if(source)claimed.set(source,view.parts)}let kept=[];for(let message of originalMessages){let parts=claimed.get(message);if(parts)writeBackTextParts(message,parts),kept.push(message);else if(!consumed.has(message)&&hasNonTextParts(message))kept.push(message)}event.messages.length=0;for(let message of kept)event.messages.push(message)}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,buildPermissionBridge(ctx,context)))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx,context){let permission=ctx.permission;if(!permission)return;if(typeof permission.assert==="function"){let assert3=permission.assert,agentName=normalizeV2AgentRef(context.agent)??"architect";return async(input)=>{let askInput=input,action2=normalizeV2PermissionAction(typeof askInput?.permission==="string"?askInput.permission:""),resources=Array.isArray(askInput?.patterns)?askInput.patterns:[];log("v2 permission bridge ask routed through assert",{action:action2,resourceCount:resources.length}),await withTimeout(Promise.resolve(assert3({sessionID:context.sessionID,agent:agentName,action:action2,resources})),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission assert exceeded budget"))}}if(typeof permission.reply==="function"){let reply=permission.reply;return async(input)=>{log("v2 permission bridge invoked (reply-only host; fail-closed)",{permission:typeof input?.permission==="string"?input.permission:"unknown",patternCount:Array.isArray(input?.patterns)?input.patterns.length:0}),await withTimeout(Promise.resolve(reply(input)).then(()=>{throw Error("[opencode-swarm] v2: permission ask denied — the reply surface resolved without a grant decision (fail-closed, #3351).")}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}return}async function deferredV2StartupModelPreflight(directory){let budgetMs=_internals273.preflightConfigTimeoutMs;try{let loaded=await withTimeout(_internals273.loadConfig(directory),_internals273.preflightConfigTimeoutMs,Error(`[opencode-swarm] v2: startup preflight config read exceeded the ${budgetMs}ms budget`));if(setV2OperatorQuiet(loaded?.config?.quiet===!0),loaded?.configHadErrors===!0)addDeferredWarning(`[opencode-swarm] v2: startup model preflight degraded — the config read resolved with errors (configHadErrors) within its ${budgetMs}ms budget; the roster check ran against the degraded configuration.`);let models=collectEnabledAgentModels(loaded?.config).map((entry)=>entry.model).filter((model)=>typeof model==="string"&&model.length>0),quiet=loaded?.config?.quiet===!0;for(let warning of collectModelRosterWarnings(models,VERIFIED_KEYLESS_MODEL_ROSTER))if(addDeferredWarning(warning),!quiet)console.warn(warning)}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 startup model preflight failed (non-fatal)",{error:message}),addDeferredWarning(`[opencode-swarm] v2: startup model preflight failed after the ${budgetMs}ms config budget (${message}); the roster check did not run.`)}}async function deferredV2ConfigureToolBeforeBudget(directory,loadConfig=loadPluginConfigWithMetaAsync){try{let loaded=await withTimeout(loadConfig(directory),V2_PREFLIGHT_CONFIG_TIMEOUT_MS,Error("[opencode-swarm] v2: hook-budget config read exceeded budget"));configureV2ToolBeforeBudget(loaded?.config?.full_auto,directory)}catch(err){resetV2ToolBeforeBudget(directory);let reason=err instanceof Error?err.message:String(err);addDeferredWarning(`[opencode-swarm] v2: could not read full_auto.oversight for the tool.execute.before budget (${reason}); default budgets apply (60 s, or 150 s while Full-Auto runs).`),log("v2 hook-budget config read failed (non-fatal)",{error:reason})}}async function deferredV2RegisterToolHooks(ctx,hooks2,directory,registrations){await Promise.all([deferredV2ConfigureToolBeforeBudget(directory),registerV2ToolHooks(ctx,hooks2,directory,registrations)])}var V2_SETUP_TIMEOUT_MS=60000,V2_REGISTRATION_TIMEOUT_MS=3500,V2_PREFLIGHT_CONFIG_TIMEOUT_MS=2000,_internals273={registrationTimeoutMs:V2_REGISTRATION_TIMEOUT_MS,preflightConfigTimeoutMs:V2_PREFLIGHT_CONFIG_TIMEOUT_MS,loadConfig:loadPluginConfigWithMetaAsync,configureToolBeforeBudget:deferredV2ConfigureToolBeforeBudget};function createRegistrationSink(){let registrations=[],push=registrations.push.bind(registrations),closed=!1;return registrations.push=(...items)=>{if(!closed)return push(...items);for(let item of items)withTimeout(Promise.resolve().then(()=>item.dispose()),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: late registration dispose exceeded budget")).catch((err)=>{log("v2 late registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});return registrations.length},{registrations,closeRegistrations:()=>{closed=!0}}}function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}var v2SetupOwnerCounter=0;function nextV2OwnerToken(){return v2SetupOwnerCounter+=1,`v2-owner-${v2SetupOwnerCounter}`}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let ownerToken=nextV2OwnerToken();registerV2ConfigRebuildSourceForOwner(ownerToken,deps.buildV2RegistrationTables),setV2OperatorQuietForOwner(ownerToken,!1);try{let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2=createRegistrationSink(),input={client:createV2SessionClient(ctx),directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget")),pendingDomains=new Set,runRegistration=(domain3,register)=>{return pendingDomains.add(domain3),register().catch((err)=>{let message=err instanceof Error?err.message:String(err);log(`v2 ${domain3} registration failed (non-fatal)`,{error:message}),addDeferredWarning(`[opencode-swarm] v2 setup: ${domain3} registration failed (${message}); the domain was not registered.`)}).finally(()=>{pendingDomains.delete(domain3)})};await withTimeout(Promise.all([runRegistration("agent/command",()=>registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations,ownerToken)),runRegistration("tool",()=>registerV2Tools(ctx,hooks2,directory,state2.registrations)),runRegistration("context-hook",()=>registerV2ContextHook(ctx,hooks2,directory,state2.registrations)),runRegistration("tool-hook",()=>deferredV2RegisterToolHooks(ctx,hooks2,directory,state2.registrations)),runRegistration("prompt-hook",()=>registerV2SessionHooks(ctx,hooks2,directory,state2.registrations))]),_internals273.registrationTimeoutMs,Error("[opencode-swarm] v2 setup: parallel registration exceeded budget")).catch((err)=>{let pending=[...pendingDomains];log("v2 registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err),pending});let pendingText=pending.length>0?pending.join(", "):"none — domains completed but the stage exceeded budget";addDeferredWarning(`[opencode-swarm] v2 setup: registration still pending after ${_internals273.registrationTimeoutMs}ms (${pendingText}); the plugin loaded with partial registration.`)});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,registerV2AgentTransformSurface(ctx,ownerToken),await withTimeout(deferredV2StartupModelPreflight(directory),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2: startup model preflight exceeded budget")),state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(state2.closeRegistrations(),typeof state2.pumpStop==="function")state2.pumpStop();clearV2SessionClientState(),clearV2AgentTransformSurface(ownerToken),clearToolNameRegistry(),registerV2ConfigRebuildSourceForOwner(ownerToken,void 0),setV2OperatorQuietForOwner(ownerToken,void 0),clearV2OwnerRegistrationSnapshot(ownerToken),clearV2CtxOwnerBinding(ctx);for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}catch(err){throw registerV2ConfigRebuildSourceForOwner(ownerToken,void 0),setV2OperatorQuietForOwner(ownerToken,void 0),clearV2OwnerRegistrationSnapshot(ownerToken),clearV2AgentTransformSurface(ownerToken),clearV2CtxOwnerBinding(ctx),err}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;recordPrimaryOwner(sessionID,agentName);try{let session=ensureAgentSession(sessionID,agentName,directory);session.lastAgentEventTime=Date.now()}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
7472
+ `)}async function deferredV2SessionPromptPlaceholder(ctx,_placeholderId,stash,body,text,signal2){if(stash.promptStarted=!0,signal2?.aborted)throw Error("v2 session-client: prompt wait aborted");let previousRealId=stash.realId;if(previousRealId!==void 0)stash.realId=void 0,stash.abortPending=!1,stash.deletePending=!1,await ctx.session.remove({sessionID:previousRealId}).catch(()=>{return});let agent=typeof body.agent==="string"?body.agent:void 0,model=body.model&&typeof body.model.providerID==="string"&&typeof body.model.modelID==="string"?{id:body.model.modelID,providerID:body.model.providerID}:void 0,system=typeof body.system==="string"?body.system:void 0,createdRecord=await ctx.session.create({...stash.parentID!==void 0?{parentID:stash.parentID}:{},...stash.title!==void 0?{title:stash.title}:{},...agent!==void 0?{agent}:{},...model!==void 0?{model}:{},location:{directory:stash.directory},permissions:readOnlyToolsToV2Permissions(body.tools)}),realId=typeof createdRecord?.id==="string"?createdRecord.id:void 0;if(realId===void 0)throw Error("v2 session-client: session create returned no id");let echoedDirectory=typeof createdRecord.location?.directory==="string"?createdRecord.location.directory:void 0;if(echoedDirectory!==void 0&&!sameDirectoryLexical(echoedDirectory,stash.directory))throw await ctx.session.remove({sessionID:realId}).catch(()=>{return}),Error(`v2 session-client: created session landed in ${echoedDirectory}, not the requested ${stash.directory} (#3169 Phase 0 C1)`);sessionErrors.delete(realId);let registration;try{if(system!==void 0||body.tools!==void 0)registration=await ctx.session.hook("context",makeV2SessionContextHandler(realId,system,body.tools));await ctx.session.prompt({sessionID:realId,text}),await deferredV2SessionWait(ctx,realId,signal2);let entries2=await ctx.session.context({sessionID:realId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],realId)}}finally{if(stash.realId=realId,registration?.dispose)await registration.dispose().catch(()=>{return});if(stash.abortPending)await ctx.session.interrupt({sessionID:realId}).catch(()=>{return});if(stash.deletePending)sessionErrors.delete(realId),await ctx.session.remove({sessionID:realId}).catch(()=>{return})}}async function deferredV2SessionPromptReal(ctx,sessionId,body,text,signal2){if(typeof body.agent==="string"){let switchAgent=ctx.session.switchAgent;if(typeof switchAgent==="function")await switchAgent({sessionID:sessionId,agent:body.agent})}sessionErrors.delete(sessionId),await ctx.session.prompt({sessionID:sessionId,text}),await deferredV2SessionWait(ctx,sessionId,signal2);let entries2=await ctx.session.context({sessionID:sessionId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],sessionId)}}function resolveSessionId(id){let stash=placeholderSessions.get(id);if(stash===void 0)return id;return stash.realId}function createV2SessionClient(ctx){let session=ctx?.session;if(!session||typeof session!=="object")return;for(let member of["create","get","remove","prompt","wait","context","interrupt","hook"])if(typeof session[member]!=="function")return;return{session:{create:(args2)=>deferredV2SessionCreate(ctx,args2),prompt:(args2)=>deferredV2SessionPrompt(ctx,args2),abort:(args2)=>{let id=args2?.path?.id,resolved=resolveSessionId(id);if(resolved!==void 0)return ctx.session.interrupt({sessionID:resolved}).catch(()=>{return});let stash=placeholderSessions.get(id);if(stash?.promptStarted)stash.abortPending=!0;return Promise.resolve(void 0)},delete:(args2)=>{let id=args2?.path?.id,stash=placeholderSessions.get(id),resolved=resolveSessionId(id);if(resolved!==void 0)return sessionErrors.delete(resolved),deferredV2SessionRemoveEager(ctx,resolved).then((outcome)=>{if(stash?.eager===!0&&outcome.ok)placeholderSessions.delete(id);else if(stash?.eager===!0)log("v2 session-client: eager delete cleanup failed",{reason:outcome.reason})});if(stash?.promptStarted)stash.deletePending=!0;return Promise.resolve(void 0)},get:(args2)=>{let id=args2?.path?.id,stash=placeholderSessions.get(id),overlayParentID=stash?.eager===!0&&typeof stash.parentID==="string"?stash.parentID:void 0,resolved=resolveSessionId(id);if(resolved===void 0)return Promise.resolve({data:null});return ctx.session.get({sessionID:resolved}).then((info)=>({data:overlayParentID!==void 0&&info&&typeof info==="object"?{...info,parentID:overlayParentID}:info})).catch((error93)=>({data:null,error:error93}))}}}}var MAX_PATH_IN_MESSAGE_CHARS=200;function boundPathForMessage(path321){if(path321===void 0)return"an unverifiable location";if(path321.length<=MAX_PATH_IN_MESSAGE_CHARS)return path321;return`${path321.slice(0,MAX_PATH_IN_MESSAGE_CHARS)}… (truncated)`}var EAGER_CLEANUP_TIMEOUT_MS=1e4;async function deferredV2SessionRemoveEager(ctx,sessionID){try{return await withTimeout(ctx.session.remove({sessionID}),EAGER_CLEANUP_TIMEOUT_MS,Error(`v2 session-client: eager cleanup of session ${sessionID} exceeded ${EAGER_CLEANUP_TIMEOUT_MS}ms`)),{ok:!0}}catch(error93){return{ok:!1,reason:error93 instanceof Error?error93.message:String(error93)}}}async function deferredV2SessionCreateEager(ctx,parentID,title,directory,signal2){let created;try{created=await ctx.session.create({...title!==void 0?{title}:{},location:{directory}})}catch(error93){return{data:null,error:{message:`v2 session-client: eager lane create failed (${error93 instanceof Error?error93.message:String(error93)})`}}}let createdRecord=created,realId=typeof createdRecord?.id==="string"?createdRecord.id:void 0;if(realId===void 0)return{data:null,error:{message:"v2 session-client: eager lane create returned no id (#3169 Phase 3)"}};if(signal2?.aborted){let compensated=await deferredV2SessionRemoveEager(ctx,realId);if(!compensated.ok)log("v2 session-client: aborted eager create compensation failed",{reason:compensated.reason});return{data:null,error:{message:`v2 session-client: eager lane create aborted by the caller; ${compensated.ok?"the created session was removed":`removing session ${realId} also failed (${compensated.reason??"unknown error"}) — remove it manually`}`,...compensated.ok?{}:{sessionID:realId,cleanupFailed:!0}}}}let landed=typeof createdRecord.location?.directory==="string"?createdRecord.location.directory:void 0;if(landed===void 0){let reported=await ctx.session.get({sessionID:realId}).catch(()=>{return});landed=typeof reported?.location?.directory==="string"?reported.location.directory:void 0}if(landed===void 0||!sameDirectoryLexical(landed,directory)){let removed=await deferredV2SessionRemoveEager(ctx,realId);return{data:null,error:{message:`v2 session-client: eager lane create landed in ${boundPathForMessage(landed)}, not the requested ${boundPathForMessage(directory)} (#3169 Phase 3 placement guard; Phase 0 C1)${removed.ok?"":`; cleanup of session ${realId} also failed (${removed.reason??"unknown error"}) — remove it before retrying`}`,...removed.ok?{}:{sessionID:realId,cleanupFailed:!0}}}}return rememberPlaceholder(realId,{parentID,...title!==void 0?{title}:{},directory,realId,eager:!0}),{data:{id:realId}}}async function deferredV2SessionCreate(ctx,args2){let directory=args2?.query?.directory;if(typeof directory!=="string"||directory.length===0)return{data:null,error:{message:"v2 session-client: create requires query.directory (v1 contract)"}};let parentID=args2?.body?.parentID;if(parentID!==void 0){let parentDirectory=await deferredV2SessionGetParentDirectory(ctx,parentID).catch(()=>{return});if(parentDirectory===void 0)return{data:null,error:{message:"v2 session-client: parent session placement unverifiable (get returned no location.directory — live-verification item on #3169 Phase 2)"}};if(!sameDirectoryLexical(parentDirectory,directory))return deferredV2SessionCreateEager(ctx,parentID,args2?.body?.title,directory,args2?.signal)}placeholderCounter+=1;let placeholderId=`v2shim-${placeholderCounter}-${Math.random().toString(36).slice(2,10)}`;return rememberPlaceholder(placeholderId,{...parentID!==void 0?{parentID}:{},...args2?.body?.title!==void 0?{title:args2.body.title}:{},directory}),{data:{id:placeholderId}}}async function deferredV2SessionPromptEager(ctx,realId,body,text,signal2){if(signal2?.aborted)throw Error("v2 session-client: eager prompt aborted before dispatch");let agent=typeof body.agent==="string"?body.agent:void 0;if(agent!==void 0){let switchAgent=ctx.session.switchAgent;if(typeof switchAgent==="function")await switchAgent({sessionID:realId,agent});else log("v2 session-client: eager prompt skipped switchAgent (host lacks it)",{agent})}let model=body.model&&typeof body.model.providerID==="string"&&typeof body.model.modelID==="string"?{id:body.model.modelID,providerID:body.model.providerID}:void 0;if(model!==void 0){let switchModel=ctx.session.switchModel;if(typeof switchModel==="function")await switchModel({sessionID:realId,model});else log("v2 session-client: eager prompt skipped switchModel (host lacks it)",{model})}let system=typeof body.system==="string"?body.system:void 0;sessionErrors.delete(realId);let registration;try{if(system!==void 0||body.tools!==void 0)registration=await ctx.session.hook("context",makeV2SessionContextHandler(realId,system,body.tools));await ctx.session.prompt({sessionID:realId,text}),await deferredV2SessionWait(ctx,realId,signal2);let entries2=await ctx.session.context({sessionID:realId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],realId)}}finally{if(registration?.dispose)await registration.dispose().catch(()=>{return})}}async function deferredV2SessionPrompt(ctx,args2){let id=args2?.path?.id;if(typeof id!=="string"||id.length===0)return{data:null,error:{message:"v2 session-client: prompt requires path.id"}};let body=args2?.body??{},text=promptBodyText(body.parts),stash=placeholderSessions.get(id);if(stash!==void 0&&stash.eager===!0&&stash.realId!==void 0)return deferredV2SessionPromptEager(ctx,stash.realId,body,text,args2?.signal);if(stash!==void 0)return deferredV2SessionPromptPlaceholder(ctx,id,stash,body,text,args2?.signal);return deferredV2SessionPromptReal(ctx,id,body,text,args2?.signal)}var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function envelopePayload(envelope){return envelope.data??envelope.properties??{}}var MAX_TRACKED_TOOL_NAME_CHARS=256,MAX_DISPATCH_ID_CHARS=256;function isBoundedId(value){return value.trim()!==""&&value.length<=MAX_DISPATCH_ID_CHARS}var MAX_TRACKED_TOOL_NAMES=512,toolNameByDispatchKey=new Map;function rememberToolNameFromEnvelope(envelope){if(envelope?.type!=="session.tool.input.started")return;let payload=envelopePayload(envelope),name=typeof payload.name==="string"?payload.name:void 0;if(!name||name.length>MAX_TRACKED_TOOL_NAME_CHARS)return;if(!isV2SubagentToolId(name))return;let sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,callID=typeof payload.id==="string"?payload.id:void 0;if(!sessionID||!callID)return;if(!isBoundedId(sessionID)||!isBoundedId(callID))return;let key3=dispatchKey2(sessionID,callID);if(toolNameByDispatchKey.delete(key3),toolNameByDispatchKey.size>=MAX_TRACKED_TOOL_NAMES){let oldest=toolNameByDispatchKey.keys().next().value;if(oldest!==void 0)toolNameByDispatchKey.delete(oldest)}toolNameByDispatchKey.set(key3,name)}function dispatchKey2(sessionID,callID){return`${sessionID.length}#${sessionID}${callID}`}function lookupToolNameForDispatch(sessionID,callID){return toolNameByDispatchKey.get(dispatchKey2(sessionID,callID))}function clearToolNameRegistry(){toolNameByDispatchKey.clear()}function readProgressChildSessionID(data){try{let metadata=data.metadata;if(!isPlainObject9(metadata))return;let child=metadata.sessionID;return typeof child==="string"?child:void 0}catch{return}}function mapV2EventToV1(envelope,lookupToolName){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelopePayload(envelope),sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.status":return{type:"session.status",properties:{...sessionID?{sessionID}:{},...data}};case"session.error":case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.tool.progress":{let callID=typeof data.id==="string"?data.id:void 0,childSessionID=readProgressChildSessionID(data),drop=(reason)=>{log("v2 subagent progress dropped",{reason});return};if(!lookupToolName)return drop("no-tool-name-lookup");if(typeof sessionID!=="string"||!isBoundedId(sessionID))return drop("invalid-parent-session");if(!callID||!isBoundedId(callID))return drop("invalid-call-id");if(!childSessionID||!isBoundedId(childSessionID))return drop("invalid-child-session");if(childSessionID===sessionID)return drop("self-referencing-child");let toolName=lookupToolName(sessionID,callID);if(!toolName)return drop("untracked-tool-name");if(!isV2SubagentToolId(toolName))return drop("non-subagent-tool");return{type:"message.part.updated",properties:{part:{type:"tool",tool:"task",callID,sessionID,state:{metadata:{sessionId:childSessionID}}}}}}case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function seedSessionIdentityFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.created"&&type!=="session.agent.selected")return;let payload=envelopePayload(envelope),sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,agent=typeof payload.agent==="string"?payload.agent:void 0;if(sessionID&&agent)recordSessionChatAgent(sessionID,agent)}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;seedSessionIdentityFromEnvelope(envelope),recordV2SessionErrorFromEnvelope(envelope),rememberToolNameFromEnvelope(envelope);let mapped=mapV2EventToV1(envelope,lookupToolNameForDispatch);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function contentParts(message){return Array.isArray(message.content)?message.content:[]}function toV1MessageView(message,sessionID,originIndex,agentName){let textParts=[];for(let part of contentParts(message))if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID,swarmV2Origin:originIndex,...message.role==="user"&&agentName!==void 0?{agent:agentName}:{}},parts:textParts}}function writeBackTextParts(message,parts){if(!Array.isArray(message.content))return;let texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text})),content=[],nextText=0,afterLastText=0;for(let part of message.content)if(part&&typeof part==="object"&&part.type==="text"){if(nextText<texts.length)content.push(texts[nextText++]);afterLastText=content.length}else content.push(part);content.splice(afterLastText,0,...texts.slice(nextText)),message.content=content}function hasNonTextParts(message){if(message.content===void 0)return!1;if(!Array.isArray(message.content))return!0;return message.content.some((part)=>!(part&&typeof part==="object"&&part.type==="text"))}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let eventAgentName=normalizeV2AgentRef(event.agent),messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let originalMessages=[...event.messages??[]],views=originalMessages.map((m,i)=>toV1MessageView(m,sessionID,i,eventAgentName)),originalByView=new Map;for(let i=0;i<views.length;i+=1)originalByView.set(views[i],originalMessages[i]);await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)}),views.length=0,originalByView.clear(),originalMessages.forEach((message,i)=>{let view=toV1MessageView(message,sessionID,i,eventAgentName);views.push(view),originalByView.set(view,message)})});let originalById=new Map;for(let message of originalMessages)if(typeof message.id==="string"&&message.id.length>0)originalById.set(message.id,message);let isCarrier=(view)=>typeof view.info.id==="string"&&view.info.id.startsWith(GUIDANCE_CARRIER_ID_PREFIX),resolved=new Map,taken=new Set,resolve124=(view,message)=>{if(taken.has(message))return;taken.add(message),resolved.set(view,message)},unresolved=[];for(let view of views){let id=view.info.id,exact=originalByView.get(view)??(typeof id==="string"&&id.length>0?originalById.get(id):void 0);if(exact)resolve124(view,exact);else unresolved.push(view)}for(let view of unresolved){let origin=view.info.swarmV2Origin;if(typeof origin!=="number"||!Number.isInteger(origin)||origin<0||origin>=originalMessages.length)continue;let original=originalMessages[origin];if(!isCarrier(view)&&view.info.role!==original.role)continue;resolve124(view,original)}let consumed=new Set,claimed=new Map;event.system=event.system??[];for(let view of views){let source=resolved.get(view);if(isCarrier(view)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});if(source)consumed.add(source)}else if(source)claimed.set(source,view.parts)}let kept=[];for(let message of originalMessages){let parts=claimed.get(message);if(parts)writeBackTextParts(message,parts),kept.push(message);else if(!consumed.has(message)&&hasNonTextParts(message))kept.push(message)}event.messages.length=0;for(let message of kept)event.messages.push(message)}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,buildPermissionBridge(ctx,context)))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx,context){let permission=ctx.permission;if(!permission)return;if(typeof permission.assert==="function"){let assert3=permission.assert,agentName=normalizeV2AgentRef(context.agent)??"architect";return async(input)=>{let askInput=input,action2=normalizeV2PermissionAction(typeof askInput?.permission==="string"?askInput.permission:""),resources=Array.isArray(askInput?.patterns)?askInput.patterns:[];log("v2 permission bridge ask routed through assert",{action:action2,resourceCount:resources.length}),await withTimeout(Promise.resolve(assert3({sessionID:context.sessionID,agent:agentName,action:action2,resources})),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission assert exceeded budget"))}}if(typeof permission.reply==="function"){let reply=permission.reply;return async(input)=>{log("v2 permission bridge invoked (reply-only host; fail-closed)",{permission:typeof input?.permission==="string"?input.permission:"unknown",patternCount:Array.isArray(input?.patterns)?input.patterns.length:0}),await withTimeout(Promise.resolve(reply(input)).then(()=>{throw Error("[opencode-swarm] v2: permission ask denied — the reply surface resolved without a grant decision (fail-closed, #3351).")}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}return}async function deferredV2StartupModelPreflight(directory){let budgetMs=_internals273.preflightConfigTimeoutMs;try{let loaded=await withTimeout(_internals273.loadConfig(directory),_internals273.preflightConfigTimeoutMs,Error(`[opencode-swarm] v2: startup preflight config read exceeded the ${budgetMs}ms budget`));if(setV2OperatorQuiet(loaded?.config?.quiet===!0),loaded?.configHadErrors===!0)addDeferredWarning(`[opencode-swarm] v2: startup model preflight degraded — the config read resolved with errors (configHadErrors) within its ${budgetMs}ms budget; the roster check ran against the degraded configuration.`);let models=collectEnabledAgentModels(loaded?.config).map((entry)=>entry.model).filter((model)=>typeof model==="string"&&model.length>0),quiet=loaded?.config?.quiet===!0;for(let warning of collectModelRosterWarnings(models,VERIFIED_KEYLESS_MODEL_ROSTER))if(addDeferredWarning(warning),!quiet)console.warn(warning)}catch(err){let message=err instanceof Error?err.message:String(err);log("v2 startup model preflight failed (non-fatal)",{error:message}),addDeferredWarning(`[opencode-swarm] v2: startup model preflight failed after the ${budgetMs}ms config budget (${message}); the roster check did not run.`)}}async function deferredV2ConfigureToolBeforeBudget(directory,loadConfig=loadPluginConfigWithMetaAsync){try{let loaded=await withTimeout(loadConfig(directory),V2_PREFLIGHT_CONFIG_TIMEOUT_MS,Error("[opencode-swarm] v2: hook-budget config read exceeded budget"));configureV2ToolBeforeBudget(loaded?.config?.full_auto,directory)}catch(err){resetV2ToolBeforeBudget(directory);let reason=err instanceof Error?err.message:String(err);addDeferredWarning(`[opencode-swarm] v2: could not read full_auto.oversight for the tool.execute.before budget (${reason}); default budgets apply (60 s, or 150 s while Full-Auto runs).`),log("v2 hook-budget config read failed (non-fatal)",{error:reason})}}async function deferredV2RegisterToolHooks(ctx,hooks2,directory,registrations){await Promise.all([deferredV2ConfigureToolBeforeBudget(directory),registerV2ToolHooks(ctx,hooks2,directory,registrations)])}var V2_SETUP_TIMEOUT_MS=60000,V2_REGISTRATION_TIMEOUT_MS=3500,V2_PREFLIGHT_CONFIG_TIMEOUT_MS=2000,_internals273={registrationTimeoutMs:V2_REGISTRATION_TIMEOUT_MS,preflightConfigTimeoutMs:V2_PREFLIGHT_CONFIG_TIMEOUT_MS,loadConfig:loadPluginConfigWithMetaAsync,configureToolBeforeBudget:deferredV2ConfigureToolBeforeBudget};function createRegistrationSink(){let registrations=[],push=registrations.push.bind(registrations),closed=!1;return registrations.push=(...items)=>{if(!closed)return push(...items);for(let item of items)withTimeout(Promise.resolve().then(()=>item.dispose()),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: late registration dispose exceeded budget")).catch((err)=>{log("v2 late registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});return registrations.length},{registrations,closeRegistrations:()=>{closed=!0}}}function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}var v2SetupOwnerCounter=0;function nextV2OwnerToken(){return v2SetupOwnerCounter+=1,`v2-owner-${v2SetupOwnerCounter}`}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let ownerToken=nextV2OwnerToken();registerV2ConfigRebuildSourceForOwner(ownerToken,deps.buildV2RegistrationTables),setV2OperatorQuietForOwner(ownerToken,!1);try{let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2=createRegistrationSink(),input={client:createV2SessionClient(ctx),directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget")),pendingDomains=new Set,runRegistration=(domain3,register)=>{return pendingDomains.add(domain3),register().catch((err)=>{let message=err instanceof Error?err.message:String(err);log(`v2 ${domain3} registration failed (non-fatal)`,{error:message}),addDeferredWarning(`[opencode-swarm] v2 setup: ${domain3} registration failed (${message}); the domain was not registered.`)}).finally(()=>{pendingDomains.delete(domain3)})};await withTimeout(Promise.all([runRegistration("agent/command",()=>registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations,ownerToken)),runRegistration("tool",()=>registerV2Tools(ctx,hooks2,directory,state2.registrations)),runRegistration("context-hook",()=>registerV2ContextHook(ctx,hooks2,directory,state2.registrations)),runRegistration("tool-hook",()=>deferredV2RegisterToolHooks(ctx,hooks2,directory,state2.registrations)),runRegistration("prompt-hook",()=>registerV2SessionHooks(ctx,hooks2,directory,state2.registrations)),runRegistration("shell-observer",()=>registerV2ShellHooks(ctx,state2.registrations))]),_internals273.registrationTimeoutMs,Error("[opencode-swarm] v2 setup: parallel registration exceeded budget")).catch((err)=>{let pending=[...pendingDomains];log("v2 registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err),pending});let pendingText=pending.length>0?pending.join(", "):"none — domains completed but the stage exceeded budget";addDeferredWarning(`[opencode-swarm] v2 setup: registration still pending after ${_internals273.registrationTimeoutMs}ms (${pendingText}); the plugin loaded with partial registration.`)});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,registerV2AgentTransformSurface(ctx,ownerToken),await withTimeout(deferredV2StartupModelPreflight(directory),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2: startup model preflight exceeded budget")),state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(state2.closeRegistrations(),typeof state2.pumpStop==="function")state2.pumpStop();clearV2SessionClientState(),clearV2AgentTransformSurface(ownerToken),clearToolNameRegistry(),registerV2ConfigRebuildSourceForOwner(ownerToken,void 0),setV2OperatorQuietForOwner(ownerToken,void 0),clearV2OwnerRegistrationSnapshot(ownerToken),clearV2CtxOwnerBinding(ctx);for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}catch(err){throw registerV2ConfigRebuildSourceForOwner(ownerToken,void 0),setV2OperatorQuietForOwner(ownerToken,void 0),clearV2OwnerRegistrationSnapshot(ownerToken),clearV2AgentTransformSurface(ownerToken),clearV2CtxOwnerBinding(ctx),err}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;recordPrimaryOwner(sessionID,agentName);try{let session=ensureAgentSession(sessionID,agentName,directory);session.lastAgentEventTime=Date.now()}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
7473
7473
  `).slice(0,SCREENING_PROMPT_CAP)}async function screenCandidate(candidate2,deps){let perCandidateMs=deps.llmTimeoutMs??0;if(!deps.llmDelegate||perCandidateMs<=0||!deps.sessionID)return!0;let llmDelegate=deps.llmDelegate;if(!deps.llmBudget)return!0;let remainingMs2=deps.remainingBudgetMs?.()??Number.POSITIVE_INFINITY,timeoutMs=Math.min(perCandidateMs,Math.max(0,remainingMs2));if(timeoutMs<=0)return!0;if(!reserveLlmBudget(deps.sessionID,SCREENING_TOKEN_ESTIMATE,deps.llmBudget))return!0;return!/\bREJECT\b/i.test(await withTimeoutSignal((signal2)=>llmDelegate("",buildScreeningPrompt(candidate2),signal2),timeoutMs,Error(`Knowledge admission screening timed out after ${timeoutMs}ms`)))}async function admitCandidate(directory,candidate2,deps){let candidateId2=resolveInsightCandidateId(candidate2),marker=insightAdmissionMarker(candidateId2),now2=deps.now??(()=>Date.now());if(!validateActionableFields({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks,triggers:candidate2.triggers,directive_priority:candidate2.directive_priority}).valid)return{outcome:"rejected",reason:"invalid_shape",marker};let actionability=validateActionability({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks});if(!actionability.actionable)return{outcome:"rejected",reason:actionability.reason??"unactionable",marker};if(!await screenCandidate(candidate2,deps))return{outcome:"rejected",reason:"screened_out",marker};let provenance=stampLearningProvenance({mechanism:candidate2.source?.kind==="prm_pattern"?"prm_pattern":"micro_reflection",sourceKnowledgeIds:[marker],sourceTaskIds:candidate2.source?.task_id?[candidate2.source.task_id]:[],sourceEvidenceRefs:candidate2.source_refs??[]},{sessionId:deps.sessionID,agentRole:candidate2.source?.agent,producedAt:new Date(now2()).toISOString()}),knowledgePath=(deps.resolveKnowledgePath??resolveSwarmKnowledgePath)(directory),entry=insightCandidateToEntry(candidate2,deps.projectName,deps.phaseNumber,deps.knowledgeConfig);if(unionSourceKnowledgeIds(entry,provenance.sourceKnowledgeIds),provenance.sourceEvidenceRefs.length>0){let refs=new Set([...entry.source_refs??[],...provenance.sourceEvidenceRefs]);entry.source_refs=[...refs]}let outcome="rejected",reason="no_change",entryId;if(await transactKnowledge(knowledgePath,(current)=>{if(findActiveEntryWithMarker(current,marker))return outcome="rejected",reason="already_admitted",null;let duplicate=findActiveSwarmNearDuplicate(entry.lesson,current,deps.knowledgeConfig.dedup_threshold);if(duplicate){let result=reinforceSwarmKnowledgeEntry(duplicate,{phase_number:deps.phaseNumber,confirmed_at:new Date(now2()).toISOString(),project_name:deps.projectName});return unionSourceKnowledgeIds(duplicate,[marker]),outcome="reinforced",reason=result.reason,entryId=duplicate.id,current}return current.push(entry),outcome="admitted",reason=void 0,entryId=entry.id,current}),outcome!=="rejected")deps.onKnowledgeChanged?.();return{outcome,reason,entryId,marker,provenance}}async function realtimeAdmissionAfter(directory,input,config3,resolveDeps){if(!isTaskTool(input.tool))return;if(!config3?.enabled)return;let sessionID=typeof input.sessionID==="string"&&input.sessionID.length>0?input.sessionID:void 0;if(!sessionID)return;if(getQueueDepth(sessionID)===0)return;let deps=await resolveDeps();return drainSessionQueue(directory,sessionID,config3,deps)}function emptySummary(){return{attempted:0,admitted:0,reinforced:0,rejected:0,deferred:0,failed:0,retries:0}}async function drainSessionQueue(directory,sessionID,config3,deps){let summary=emptySummary();if(!config3.enabled)return summary;let now2=deps.now??(()=>Date.now()),stats2=getQueueStats(sessionID);if(stats2.depth===0)return summary;let velocity=computeArrivalVelocity(stats2,now2()),size=computeDrainSize(stats2.depth,velocity,{minDrain:config3.min_drain,maxDrain:config3.max_drain,drainDepthFactor:config3.drain_depth_factor,drainVelocityFactor:config3.drain_velocity_factor});if(size<=0)return summary;let batch=takeDrainBatch(sessionID,size);if(batch.length===0)return summary;summary.attempted=batch.length;let startedAt=now2(),wallTimeMs=Math.max(0,Number(config3.max_drain_wall_time_ms)||0),deadline=wallTimeMs>0?startedAt+wallTimeMs:Number.POSITIVE_INFINITY,budgetExhausted=()=>now2()>=deadline,maxRetries=Math.max(0,Math.floor(Number(config3.max_retries_per_candidate)||0)),limit=pLimit(Math.max(1,Math.floor(Number(config3.max_concurrent_admissions)||1))),admissionDeps={...deps,sessionID,llmTimeoutMs:config3.max_llm_calls_per_session>0?deps.llmTimeoutMs??config3.per_candidate_llm_timeout_ms:0,llmBudget:deps.llmBudget??{maxLlmCallsPerSession:config3.max_llm_calls_per_session,maxTokensPerSession:config3.max_tokens_per_session},remainingBudgetMs:()=>deadline-now2()},deferOrAbandon=(item)=>{if(item.attempts>=MAX_CANDIDATE_DRAIN_ATTEMPTS){summary.failed++,warn(`[learning-admission] candidate abandoned after ${item.attempts} drain attempt(s) without completing`);return}requeueCandidate(sessionID,item,{maxQueueSize:config3.max_queue_size}),summary.deferred++};return await Promise.all(batch.map((item)=>limit(async()=>{if(budgetExhausted()){deferOrAbandon(item);return}for(let attempt=0;;attempt++)try{let result=await admitCandidate(directory,item.candidate,admissionDeps);if(result.outcome==="admitted")summary.admitted++;else if(result.outcome==="reinforced")summary.reinforced++;else summary.rejected++;return}catch(err){if(attempt>=maxRetries){warn(`[learning-admission] candidate failed after ${attempt+1} attempt(s): ${isAbortError(err)?"cancelled":err instanceof Error?err.message:String(err)}`),deferOrAbandon(item);return}if(summary.retries++,recordRetry(sessionID),budgetExhausted()){deferOrAbandon(item);return}}}))),summary}init_memory();init_provider_pool();init_task_model_routing();init_observability();init_otlp_exporter();init_startup_contract();init_manager();init_prm();init_trajectory_store();init_sweep();init_ephemeral_agent_dispatcher();function createReviewModelDispatcher(client,pricing){return{dispatch:(request)=>dispatchEphemeralAgent({client,directory:request.directory,parentSessionId:request.parentSessionId,agentName:request.agentName,model:request.model,system:request.system,prompt:request.prompt,readOnlyTools:request.tools??DEFAULT_READ_ONLY_TOOLS,title:request.title,timeoutMs:request.timeoutMs&&request.timeoutMs>0?request.timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,promptByteLimit:request.promptByteLimit,responseByteLimit:request.responseByteLimit,abortSignal:request.abortSignal,pricing})}}init_finding_validator();init_runtime3();init_effective_spec();init_compaction_service();init_config_doctor();init_cost_accounting();init_injection_budget();init_model_preflight();init_version_check();init_snapshot_coordination_init();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();init_state();init_telemetry();init_startup_contract();init_zod();init_lifecycle();init_loader();init_ephemeral_agent_dispatcher();init_gate_evidence();init_utils2();init_ledger();init_manager();init_utils3();init_runtime3();init_atomic_write();init_logger();init_model_dispatch_fallback();init_provider_error_classification();init_swarm_artifact_cache();init_config();init_lifecycle();init_next_wave_format();import{createHash as createHash106}from"node:crypto";import*as fs187 from"node:fs";import*as path321 from"node:path";var EPIC_PHASE_REVIEW_FILENAME="epic-phase-review.json",EPIC_PHASE_REVIEW_TTL_MS=86400000,EPIC_PHASE_REVIEW_FORWARD_SKEW_MS=300000,EPIC_PHASE_REVIEW_DISPATCH_TIMEOUT_MS=300000;function resolveEpicPhaseReviewTimeoutMs(directory){try{let configured=resolveEpicConfig(loadPluginConfigWithMeta(directory).config)?.phase_review?.timeout_ms;return typeof configured==="number"?configured:EPIC_PHASE_REVIEW_DISPATCH_TIMEOUT_MS}catch{return EPIC_PHASE_REVIEW_DISPATCH_TIMEOUT_MS}}var EPIC_PHASE_REVIEW_TOOL="epic_phase_review",EPIC_PHASE_REVIEW_BASH_RETRY_NOTE="You have a `bash` tool for this review. Use it only to read and inspect (for example cat, ls, grep, git log, git diff, git show). Never run a command that creates, modifies or deletes files, changes git state (checkout, stash, reset, commit), installs packages, or runs tests.",EPIC_PHASE_REVIEW_BASH_RETRY_TOOLS=Object.freeze(Object.fromEntries(Object.entries(DEFAULT_READ_ONLY_TOOLS).filter(([name])=>name!=="bash"))),MAX_REASON_CHARS=2000;function sha25612(text){return createHash106("sha256").update(text,"utf8").digest("hex")}function taskEvidenceFingerprint(directory,taskId){if(!isValidTaskId(taskId))return"invalid-task-id";try{let bytes=fs187.readFileSync(path321.join(directory,".swarm","evidence",`${taskId}.json`));return createHash106("sha256").update(bytes).digest("hex")}catch(error93){let code=error93.code;return code==="ENOENT"||code==="ENAMETOOLONG"?"missing":"unreadable"}}function currentEpicKey(directory){try{return _internals274.getOpenEpic(directory)?.epicKey??null}catch{return null}}function computeEpicPhaseBinding(directory,plan,phase){let target=plan.phases.find((item)=>item.id===phase);if(!target)return{ok:!1,reason:`phase ${phase} is not in the current plan`};let tasks=[...target.tasks].sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0),taskIds=tasks.map((task2)=>task2.id);return{ok:!0,incompleteTaskIds:tasks.filter((task2)=>task2.status!=="completed"&&task2.status!=="closed").map((task2)=>task2.id),binding:{epic_key:currentEpicKey(directory),plan_id:derivePlanId(plan),plan_structure_hash:computePlanStructureHash(plan),phase_task_ids:taskIds,phase_tasks_digest:sha25612(JSON.stringify(tasks.map((task2)=>[task2.id,task2.status]))),task_evidence_digest:sha25612(JSON.stringify(taskIds.map((id)=>[id,_internals274.taskEvidenceFingerprint(directory,id)])))}}}function evidencePath(directory,phase){return validateSwarmPath(directory,path321.posix.join("evidence",String(phase),EPIC_PHASE_REVIEW_FILENAME))}var VERDICTS=new Set(["APPROVED","NEEDS_REVISION","REJECTED"]);function isRoleVerdict(value,role){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let v=value;return v.role===role&&typeof v.agent==="string"&&v.agent.length>0&&typeof v.verdict==="string"&&VERDICTS.has(v.verdict)&&(v.reason===null||typeof v.reason==="string")&&(v.dispatch==="completed"||v.dispatch==="unparseable"||v.dispatch==="failed")&&(v.tool_profile===void 0||v.tool_profile==="read-only"||v.tool_profile==="read-only-with-bash")&&typeof v.dispatched_at==="string"}function isBinding(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let v=value;return(v.epic_key===void 0||v.epic_key===null||typeof v.epic_key==="string")&&typeof v.plan_id==="string"&&typeof v.plan_structure_hash==="string"&&Array.isArray(v.phase_task_ids)&&v.phase_task_ids.every((id)=>typeof id==="string")&&typeof v.phase_tasks_digest==="string"&&typeof v.task_evidence_digest==="string"}function parseEpicPhaseReviewEvidence(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;let v=raw;if(v.schema_version!==1||v.kind!=="epic_phase_review"||typeof v.phase!=="number"||!Number.isInteger(v.phase)||typeof v.reviewed_at!=="string"||typeof v.parent_session_id!=="string"||!isBinding(v.binding)||!isRoleVerdict(v.reviewer,"reviewer")||!(v.critic===null||isRoleVerdict(v.critic,"critic")))return null;return raw}function readEpicPhaseReviewEvidence(directory,phase){let text;try{text=fs187.readFileSync(evidencePath(directory,phase),"utf-8")}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"invalid",detail:error93 instanceof Error?error93.message:String(error93)}}let parsed;try{parsed=JSON.parse(text)}catch{return{status:"invalid",detail:"evidence is not valid JSON"}}let evidence2=parseEpicPhaseReviewEvidence(parsed);return evidence2?{status:"found",evidence:evidence2}:{status:"invalid",detail:"evidence does not match schema v1"}}function rerunHint(phase){return`Call ${EPIC_PHASE_REVIEW_TOOL}({ phase: ${phase} }) — it dispatches the phase reviewer and then the phase critic and records both verdicts — then retry phase_complete.`}function openEpicWavesForPhase(record3,phase){return record3.waves.filter((wave)=>wave.phase===phase&&wave.status==="issued").map((wave)=>wave.seq)}function describeOpenEpicWaves(directory,phase){let record3;try{record3=_internals274.getOpenEpic(directory)}catch(error93){return`the open epic's record is unreadable (${error93 instanceof Error?error93.message:String(error93)}), so its waves cannot be verified (fail closed). Ask the user to run \`/swarm epic status\`.`}if(!record3)return null;let open11=openEpicWavesForPhase(record3,phase);if(open11.length===0)return null;return`wave ${open11.join(", ")} of phase ${phase} is still open. Call epic_next_wave — it closes a wave once every task in it is resolved — until it returns phase-ready-for-review.`}async function verifyEpicPhaseReadiness(directory,phase,nowMs3){let openWaves=describeOpenEpicWaves(directory,phase);if(openWaves!==null)return{ok:!1,code:"EPIC_PHASE_WAVES_OPEN",reason:`Phase ${phase} cannot complete: ${openWaves}`};let read=_internals274.readEvidence(directory,phase),rel3=`.swarm/evidence/${phase}/${EPIC_PHASE_REVIEW_FILENAME}`;if(read.status==="missing")return{ok:!1,code:"EPIC_PHASE_REVIEW_MISSING",reason:`Epic Mode requires an APPROVED phase reviewer and phase critic before phase ${phase} can complete, but ${rel3} does not exist. ${rerunHint(phase)}`};if(read.status==="invalid")return{ok:!1,code:"EPIC_PHASE_REVIEW_INVALID",reason:`Epic phase review evidence ${rel3} is unreadable or malformed (${read.detail}). Do not edit it by hand. ${rerunHint(phase)}`};let evidence2=read.evidence;if(evidence2.phase!==phase)return{ok:!1,code:"EPIC_PHASE_REVIEW_INVALID",reason:`Epic phase review evidence at ${rel3} records phase ${evidence2.phase}, not phase ${phase}. ${rerunHint(phase)}`};if(evidence2.reviewer.verdict!=="APPROVED")return{ok:!1,code:"EPIC_PHASE_REVIEWER_NOT_APPROVED",reason:`Epic phase reviewer (${evidence2.reviewer.agent}) returned ${evidence2.reviewer.verdict} for phase ${phase}${evidence2.reviewer.reason?`: ${evidence2.reviewer.reason}`:""}. ${epicPhaseFixPath(phase)} Then retry phase_complete.`};if(!evidence2.critic)return{ok:!1,code:"EPIC_PHASE_CRITIC_MISSING",reason:`Epic phase critic verdict is missing for phase ${phase}. ${rerunHint(phase)}`};if(evidence2.critic.verdict!=="APPROVED")return{ok:!1,code:"EPIC_PHASE_CRITIC_NOT_APPROVED",reason:`Epic phase critic (${evidence2.critic.agent}) returned ${evidence2.critic.verdict} for phase ${phase}${evidence2.critic.reason?`: ${evidence2.critic.reason}`:""}. ${epicPhaseFixPath(phase)} Then retry phase_complete.`};let reviewedAtMs=Date.parse(evidence2.reviewed_at);if(!Number.isFinite(reviewedAtMs))return{ok:!1,code:"EPIC_PHASE_REVIEW_INVALID",reason:`Epic phase review evidence for phase ${phase} has an invalid reviewed_at timestamp. ${rerunHint(phase)}`};let age=nowMs3-reviewedAtMs;if(age<-EPIC_PHASE_REVIEW_FORWARD_SKEW_MS)return{ok:!1,code:"EPIC_PHASE_REVIEW_STALE",reason:`Epic phase review evidence for phase ${phase} is future-dated (${evidence2.reviewed_at}); rejected as forged or clock-skewed. ${rerunHint(phase)}`};if(age>EPIC_PHASE_REVIEW_TTL_MS)return{ok:!1,code:"EPIC_PHASE_REVIEW_STALE",reason:`Epic phase review evidence for phase ${phase} is older than 24h. ${rerunHint(phase)}`};let plan;try{plan=await _internals274.loadPlan(directory)}catch{plan=null}if(!plan)return{ok:!1,code:"EPIC_PHASE_PLAN_UNREADABLE",reason:`Cannot verify Epic phase review freshness for phase ${phase}: the plan could not be loaded.`};let current=computeEpicPhaseBinding(directory,plan,phase);if(!current.ok)return{ok:!1,code:"EPIC_PHASE_PLAN_UNREADABLE",reason:`Cannot verify Epic phase review freshness: ${current.reason}.`};let recorded=evidence2.binding,drift=[];if((recorded.epic_key??null)!==current.binding.epic_key)drift.push("epic instance");if(recorded.plan_id!==current.binding.plan_id)drift.push("plan identity");if(recorded.plan_structure_hash!==current.binding.plan_structure_hash)drift.push("plan structure");if(recorded.phase_tasks_digest!==current.binding.phase_tasks_digest)drift.push("phase task set/status");if(recorded.task_evidence_digest!==current.binding.task_evidence_digest)drift.push("task gate evidence (rework after review)");if(drift.length>0)return{ok:!1,code:"EPIC_PHASE_REVIEW_STALE",reason:`Epic phase review evidence for phase ${phase} is stale — ${drift.join(", ")} changed after the review. ${rerunHint(phase)}`};return{ok:!0,evidence:evidence2}}function parseEpicPhaseVerdict(text){let lines=text.split(/\r?\n/),found=[];for(let i=0;i<lines.length;i++){let match=/^\s*(?:\*\*)?VERDICT(?:\*\*)?\s*:\s*(?:\*\*)?\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*(?:\*\*)?\s*$/i.exec(lines[i]);if(match)found.push({verdict:match[1].toUpperCase(),index:i})}if(found.length===0)return null;if(new Set(found.map((item)=>item.verdict)).size>1)return null;let last=found[found.length-1],reason=null;for(let i=last.index+1;i<Math.min(lines.length,last.index+4);i++){let reasonMatch=/^\s*(?:\*\*)?REASON(?:\*\*)?\s*:\s*(.+)$/i.exec(lines[i]);if(reasonMatch){reason=reasonMatch[1].trim().slice(0,MAX_REASON_CHARS);break}}return{verdict:last.verdict,reason}}function buildReviewPackage(directory,plan,phase){let target=plan.phases.find((item)=>item.id===phase),tasks=target?.tasks??[],outcomes={};try{outcomes=_internals274.getOpenEpic(directory)?.tasks??{}}catch(error93){warn(`[epic-phase-readiness] epic record unreadable; reviewing without divergence: ${error93 instanceof Error?error93.message:String(error93)}`)}let filesChanged=new Set,packaged=tasks.map((task2)=>{let outcome=Object.hasOwn(outcomes,task2.id)?outcomes[task2.id]:void 0,divergence=outcome&&outcome.resolution!=="removed"?outcome:void 0,attributed=divergence?.attribution==="session"||divergence?.attribution==="git-single-task";for(let file3 of divergence&&attributed?[...divergence.declared,...divergence.undeclared]:[...divergence?.declared??[],...task2.files_touched])filesChanged.add(file3);return{id:task2.id,status:task2.status,description:task2.description,...task2.acceptance?{acceptance:task2.acceptance}:{},files_touched:[...task2.files_touched],depends:[...task2.depends],...divergence?{divergence:{declared_scope:[...divergence.declared],undeclared:[...divergence.undeclared],attribution:divergence.attribution}}:{}}});return{phase,phase_name:target?.name??`Phase ${phase}`,tasks:packaged,files_changed:[...filesChanged].sort()}}var VERDICT_FOOTER=`Conclude with exactly ONE verdict line followed by a REASON line:
7474
7474
 
7475
7475
  VERDICT: APPROVED