opencode-swarm 7.144.7 → 7.144.8

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 (48) hide show
  1. package/dist/cli/{capability-probe-976tt4ba.js → capability-probe-va4kk8vg.js} +2 -2
  2. package/dist/cli/{config-doctor-zdvaq4nb.js → config-doctor-zbqfp0v6.js} +2 -2
  3. package/dist/cli/{core-j7f118a5.js → core-pz9gwatq.js} +1 -1
  4. package/dist/cli/{curator-llm-factory-eny079d1.js → curator-llm-factory-3nq3p02z.js} +19 -19
  5. package/dist/cli/{curator-97sm8wn0.js → curator-sk0dyvke.js} +19 -19
  6. package/dist/cli/{evidence-summary-service-kwtb2d14.js → evidence-summary-service-abwrjqd0.js} +7 -7
  7. package/dist/cli/{gate-evidence-rk9j0hc4.js → gate-evidence-aa7vvtcd.js} +2 -2
  8. package/dist/cli/{guardrail-explain-8gggptqj.js → guardrail-explain-hvtyr2fz.js} +20 -20
  9. package/dist/cli/{guardrail-log-zbqf4ws6.js → guardrail-log-jw5mzs0d.js} +3 -3
  10. package/dist/cli/{hive-promoter-qzvtp5wx.js → hive-promoter-m20j63yg.js} +19 -19
  11. package/dist/cli/{index-bx20cv1v.js → index-0v1f2sdb.js} +2 -2
  12. package/dist/cli/{index-b44qqqt2.js → index-3g0xk6tk.js} +1 -1
  13. package/dist/cli/{index-77h4xjn5.js → index-3k3nbs52.js} +4 -4
  14. package/dist/cli/{index-zq9gs0yk.js → index-7qb0hn8n.js} +1 -1
  15. package/dist/cli/{index-zy7f84cs.js → index-85gkedsf.js} +14 -5
  16. package/dist/cli/{index-c1cfsg9y.js → index-8dbzaf0m.js} +1 -1
  17. package/dist/cli/{index-xjgwr4c6.js → index-bv44950t.js} +1 -1
  18. package/dist/cli/{index-x4q96ejx.js → index-c2rpht77.js} +50 -47
  19. package/dist/cli/{index-qm0mz7rj.js → index-cx51wy0c.js} +3 -3
  20. package/dist/cli/{index-d879g58v.js → index-d1dbpxxk.js} +1 -1
  21. package/dist/cli/{index-x4eqd82b.js → index-gfvkttvd.js} +1 -1
  22. package/dist/cli/{index-grkev1g6.js → index-jdxnzbah.js} +1 -1
  23. package/dist/cli/{index-jszgrk71.js → index-k7fk9fjs.js} +2 -2
  24. package/dist/cli/{index-gmdgap01.js → index-nmy6rss1.js} +1 -1
  25. package/dist/cli/{index-00fk9c3b.js → index-r14qx363.js} +1 -1
  26. package/dist/cli/{index-yz0hfa4g.js → index-r2rkwvzq.js} +2 -2
  27. package/dist/cli/{index-w9bnt74s.js → index-sxe5nyq4.js} +3 -3
  28. package/dist/cli/{index-r2q0nd0a.js → index-t2ntgzts.js} +3 -3
  29. package/dist/cli/{index-39jbnhar.js → index-t72g4a7y.js} +21 -21
  30. package/dist/cli/{index-7bvd5nh2.js → index-tffg4mwr.js} +1 -1
  31. package/dist/cli/{index-q7zy6dej.js → index-xp5g9eps.js} +1 -1
  32. package/dist/cli/{index-pzsezhek.js → index-xx8tm58n.js} +5 -5
  33. package/dist/cli/{index-s1xefrx7.js → index-z4fssj97.js} +7 -4
  34. package/dist/cli/index.js +19 -19
  35. package/dist/cli/{knowledge-escalator-fhc6ecbv.js → knowledge-escalator-mg8qb7tm.js} +6 -6
  36. package/dist/cli/{knowledge-events-31g69mx2.js → knowledge-events-3zxf8xpb.js} +4 -4
  37. package/dist/cli/{knowledge-store-g389c1cy.js → knowledge-store-awnm8s6c.js} +1 -1
  38. package/dist/cli/{knowledge-validator-sng5xt5a.js → knowledge-validator-3ke5scx3.js} +2 -2
  39. package/dist/cli/{scan-cursor-qm3tsvvw.js → scan-cursor-00rbxkb4.js} +2 -2
  40. package/dist/cli/{schema-vnghba3d.js → schema-5nmkp1pc.js} +1 -1
  41. package/dist/cli/{scope-persistence-k9mqd414.js → scope-persistence-6m79atw9.js} +4 -4
  42. package/dist/cli/{skill-generator-v1wdh3ne.js → skill-generator-gv70s796.js} +7 -7
  43. package/dist/cli/{worktree-isolation-bxt3rftm.js → worktree-isolation-bne0p54w.js} +19 -19
  44. package/dist/git/branch.d.ts +9 -0
  45. package/dist/hooks/delegation-gate/worktree-isolation.d.ts +5 -0
  46. package/dist/index.js +4 -4
  47. package/dist/sandbox/executor.d.ts +6 -0
  48. 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.144.7",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"},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/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/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","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},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"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},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)",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"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, 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. 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"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){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);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,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.144.8",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"},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/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/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","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},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"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},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)",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"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, 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. 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"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){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);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,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
 
@@ -478,8 +478,8 @@ try {
478
478
  } catch {
479
479
  [Console]::Error.WriteLine($_.Exception.Message);
480
480
  exit 1;
481
- }`,encodedScript=Buffer2.from(psScript,"utf16le").toString("base64");return`& '${psSingleQuoteEscape(powerShellExe)}' -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ${encodedScript}; exit $LASTEXITCODE`}getEnvOverrides(){return{PATH:getSafeWindowsPath(),TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null}}}var SANDBOX_UNAVAILABLE_CODES2,DEFAULT_SYSTEM_ROOT="C:\\Windows",UNSAFE_PATH_CHARACTERS,_internals25;var init_restricted_environment_executor=__esm(()=>{init_logger();init_executor();SANDBOX_UNAVAILABLE_CODES2=new Set(["ENOENT","EACCES","EPERM","ENOSPC"]),UNSAFE_PATH_CHARACTERS=new Set([":",'"',"'",";","&","|","<",">","^","%","!","?","*","`","$"]);_internals25={probeWindowsSandbox}});import*as crypto4 from"node:crypto";import*as fs21 from"node:fs";import*as os10 from"node:os";import*as path31 from"node:path";class NativeWindowsSandboxExecutor{mechanism;_probeResult;_fallbackExecutor;_strength;_disabled;_disabledReason;constructor(scopePaths=[],tempDir){if(this._disabled=!1,this._disabledReason=null,this._fallbackExecutor=new WindowsSandboxExecutor(scopePaths,tempDir),this._probeResult=probe(),this._probeResult.available)this._strength="strong",this.mechanism=`native-runner/${this._probeResult.mode}`;else if(this._fallbackExecutor.isAvailable())this._strength="weak",this.mechanism="powershell-wrapper",warn(`Native sandbox runner unavailable (${this._probeResult.error??"unknown"}); falling back to PowerShell environment restrictions (weak sandbox)`);else this._strength="none",this.mechanism="none"}get strength(){if(this._disabled)return"none";return this._strength}isAvailable(){return!this._disabled&&this._strength!=="none"}disable(reason){this._disabled=!0,this._disabledReason=reason,warn(`Sandbox disabled: ${reason}. Falling through to tool-layer enforcement.`)}wrapCommand(command,scopePaths,tempDir,envOverrides){if(!this.isAvailable())throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");if(this._strength==="strong")return this._wrapWithRunner(command,scopePaths,tempDir,envOverrides);return this._fallbackExecutor.wrapCommand(command,scopePaths,tempDir,envOverrides)}_wrapWithRunner(command,scopePaths,tempDir,_envOverrides){let binary=_internals23.findRunnerBinary();if(!binary)throw new SandboxError("Runner binary not found","RUNNER_NOT_FOUND");let workspaceRoot=scopePaths[0]??process.cwd(),runId=`swarm-${crypto4.randomUUID?.()??Date.now()}`,policy=buildDefaultPolicy(workspaceRoot,runId);if(tempDir)policy.temp_root=tempDir;if(policy.workspace_roots=scopePaths.length>0?scopePaths:[workspaceRoot],policy.writable_roots=policy.workspace_roots,_envOverrides)for(let[key,value]of Object.entries(_envOverrides)){if(!isValidEnvKey(key))continue;if(typeof value==="string")policy.env_overrides[key]=value}let policyJson=JSON.stringify(policy),policyDir=path31.join(os10.tmpdir(),"swarm-sandbox-policies");try{fs21.mkdirSync(policyDir,{recursive:!0})}catch{}let policyFile=path31.join(policyDir,`${runId}.json`);fs21.writeFileSync(policyFile,policyJson,"utf-8");let mode=this._probeResult.mode==="none"?"auto":this._probeResult.mode,escapedBinary=binary.includes(" ")?`"${binary}"`:binary,escapedPolicyFile=policyFile.includes(" ")?`"${policyFile}"`:policyFile,escapedCommand=command.replace(/"/g,"\\\"");return`cmd /c "type ${escapedPolicyFile} | ${escapedBinary} --policy-stdin --mode ${mode} -- ${escapedCommand} & del ${escapedPolicyFile} 2>nul"`}getEnvOverrides(){if(this._strength==="strong")return{PATH:null,TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null};return this._fallbackExecutor.getEnvOverrides()}async executeNative(command,workspaceRoot,runId){if(this._strength!=="strong")throw new SandboxError("Native execution requires strong sandbox (runner binary)","NATIVE_UNAVAILABLE");let policy=buildDefaultPolicy(workspaceRoot,runId);return execute(command,policy)}get hasNativeRunner(){return this._strength==="strong"}get disabledReason(){return this._disabledReason}get probeResult(){return this._probeResult}}var init_native_sandbox_executor=__esm(()=>{init_logger();init_executor();init_restricted_environment_executor();init_runner_client()});var exports_windows={};__export(exports_windows,{WindowsSandboxExecutor:()=>NativeWindowsSandboxExecutor,LegacyWindowsSandboxExecutor:()=>WindowsSandboxExecutor});var init_windows=__esm(()=>{init_native_sandbox_executor();init_restricted_environment_executor()});function isValidEnvKey(key){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)}async function getExecutor(){if(_cachedExecutorPromise!==void 0)return _cachedExecutorPromise;return _cachedExecutorPromise=_createExecutor(),_cachedExecutorPromise}async function _createExecutor(){let platform=process.platform;if(platform==="linux")return _createLinuxExecutor();if(platform==="darwin")return _createMacOSExecutor();if(platform==="win32")return _createWindowsExecutor();return null}async function _createLinuxExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isBubblewrapAvailable:isBubblewrapAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isBubblewrapAvailable2())return null;try{let{BubblewrapSandboxExecutor:BubblewrapSandboxExecutor2}=(init_bubblewrap(),__toCommonJS(exports_bubblewrap));return new BubblewrapSandboxExecutor2([])}catch{return null}}function setMacOSSandboxPolicy(enabled){_macosSandboxEnabled=enabled}async function _createMacOSExecutor(){if(!_macosSandboxEnabled){if(!_hasWarnedMacOSSandboxDisabledByConfig)_hasWarnedMacOSSandboxDisabledByConfig=!0,warn("[sandbox] macOS sandbox-exec is disabled by config (guardrails.sandbox_macos_enabled=false). "+"Enable it only after verifying the production SBPL profile on a real macOS host — see docs/configuration.md.");return null}let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isSandboxExecAvailable:isSandboxExecAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isSandboxExecAvailable2())return null;try{let{MacOSSandboxExecutor:MacOSSandboxExecutor2}=(init_macos(),__toCommonJS(exports_macos));return new MacOSSandboxExecutor2([])}catch{return null}}async function _createWindowsExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isWindowsSandboxAvailable:isWindowsSandboxAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isWindowsSandboxAvailable2())return null;try{let{WindowsSandboxExecutor:WindowsSandboxExecutor2}=(init_windows(),__toCommonJS(exports_windows));return new WindowsSandboxExecutor2([])}catch{return null}}var SandboxError,_cachedExecutorPromise,_macosSandboxEnabled=!1,_hasWarnedMacOSSandboxDisabledByConfig=!1;var init_executor=__esm(()=>{init_logger();SandboxError=class SandboxError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="SandboxError"}}});function isTransientSpawnError(error49){if(!error49||typeof error49!=="object")return!1;return error49.code==="ETIMEDOUT"}function transientBackoff(attempt){let delay=200*2**attempt;try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,delay)}catch{let start=Date.now();while(Date.now()-start<delay);}}var MAX_TRANSIENT_RETRIES=5;import*as child_process2 from"node:child_process";import*as fsSync3 from"node:fs";import path32 from"node:path";function errorMessage(err){return err instanceof Error?err.message:String(err)}function isNotGitRepositoryMessage(message){let lower=message.toLowerCase();return lower.includes("not a git repository")||lower.includes("not a git repo")}function getChildProcessSpawnSync(){return child_process2.spawnSync}function readLaneEnvFileFromDiskSync(worktreePath,laneIndex){let envPath=path32.join(worktreePath,".swarm","lanes",`${laneIndex}.env`),content;try{content=fsSync3.readFileSync(envPath,"utf-8")}catch{return{}}let result={};for(let rawLine of content.split(`
482
- `)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;result[k]=v}return result}function gitBinaryMissingMessage(cwd){let resolution=describeGitResolution(),lines=[`git executable is not available: spawning "${resolution.resolvedPath??"git"}" failed, and the working directory ${cwd} exists and is a directory.`];if(resolution.attempts.length>0){lines.push("Candidates tried:");let shown=resolution.attempts.slice(0,MAX_RENDERED_GIT_CANDIDATES);for(let attempt of shown)lines.push(` - [${attempt.source}] ${attempt.candidate}: ${attempt.accepted?"accepted":attempt.reason??"rejected"}`);let omitted=resolution.attempts.length-shown.length;if(omitted>0)lines.push(` ... and ${omitted} more`)}else lines.push("No candidate probe results are recorded for this process (the resolver was pre-seeded or has not probed yet).");return lines.push(resolution.overrideValue?`The configured override (${resolution.overrideSource??"unknown"}) "${resolution.overrideValue}" did not work — point the ${GIT_BINARY_ENV_VAR} environment variable, or the "git.binary" value in your USER config (a project .opencode config is ignored for this key), at a working git executable.`:`No override is configured. Set the ${GIT_BINARY_ENV_VAR} environment variable, or the "git.binary" value in your USER config (a project .opencode config is ignored for this key), to point at a working git executable.`),lines.join(`
481
+ }`,encodedScript=Buffer2.from(psScript,"utf16le").toString("base64");return`& '${psSingleQuoteEscape(powerShellExe)}' -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ${encodedScript}; exit $LASTEXITCODE`}getEnvOverrides(){return{PATH:getSafeWindowsPath(),TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null}}}var SANDBOX_UNAVAILABLE_CODES2,DEFAULT_SYSTEM_ROOT="C:\\Windows",UNSAFE_PATH_CHARACTERS,_internals25;var init_restricted_environment_executor=__esm(()=>{init_logger();init_executor();SANDBOX_UNAVAILABLE_CODES2=new Set(["ENOENT","EACCES","EPERM","ENOSPC"]),UNSAFE_PATH_CHARACTERS=new Set([":",'"',"'",";","&","|","<",">","^","%","!","?","*","`","$"]);_internals25={probeWindowsSandbox}});import*as crypto4 from"node:crypto";import*as fs21 from"node:fs";import*as os10 from"node:os";import*as path31 from"node:path";class NativeWindowsSandboxExecutor{mechanism;_probeResult;_fallbackExecutor;_strength;_disabled;_disabledReason;constructor(scopePaths=[],tempDir){if(this._disabled=!1,this._disabledReason=null,this._fallbackExecutor=new WindowsSandboxExecutor(scopePaths,tempDir),this._probeResult=probe(),this._probeResult.available)this._strength="strong",this.mechanism=`native-runner/${this._probeResult.mode}`;else if(this._fallbackExecutor.isAvailable())this._strength="weak",this.mechanism="powershell-wrapper",warn(`Native sandbox runner unavailable (${this._probeResult.error??"unknown"}); falling back to PowerShell environment restrictions (weak sandbox)`);else this._strength="none",this.mechanism="none"}get strength(){if(this._disabled)return"none";return this._strength}isAvailable(){return!this._disabled&&this._strength!=="none"}disable(reason){this._disabled=!0,this._disabledReason=reason,warn(`Sandbox disabled: ${reason}. Falling through to tool-layer enforcement.`)}wrapCommand(command,scopePaths,tempDir,envOverrides){if(!this.isAvailable())throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");if(this._strength==="strong")return this._wrapWithRunner(command,scopePaths,tempDir,envOverrides);return this._fallbackExecutor.wrapCommand(command,scopePaths,tempDir,envOverrides)}_wrapWithRunner(command,scopePaths,tempDir,_envOverrides){let binary=_internals23.findRunnerBinary();if(!binary)throw new SandboxError("Runner binary not found","RUNNER_NOT_FOUND");let workspaceRoot=scopePaths[0]??process.cwd(),runId=`swarm-${crypto4.randomUUID?.()??Date.now()}`,policy=buildDefaultPolicy(workspaceRoot,runId);if(tempDir)policy.temp_root=tempDir;if(policy.workspace_roots=scopePaths.length>0?scopePaths:[workspaceRoot],policy.writable_roots=policy.workspace_roots,_envOverrides)for(let[key,value]of Object.entries(_envOverrides)){if(!isValidEnvKey(key))continue;if(typeof value==="string")policy.env_overrides[key]=value}let policyJson=JSON.stringify(policy),policyDir=path31.join(os10.tmpdir(),"swarm-sandbox-policies");try{fs21.mkdirSync(policyDir,{recursive:!0})}catch{}let policyFile=path31.join(policyDir,`${runId}.json`);fs21.writeFileSync(policyFile,policyJson,"utf-8");let mode=this._probeResult.mode==="none"?"auto":this._probeResult.mode,escapedBinary=binary.includes(" ")?`"${binary}"`:binary,escapedPolicyFile=policyFile.includes(" ")?`"${policyFile}"`:policyFile,escapedCommand=command.replace(/"/g,"\\\"");return`cmd /c "type ${escapedPolicyFile} | ${escapedBinary} --policy-stdin --mode ${mode} -- ${escapedCommand} & del ${escapedPolicyFile} 2>nul"`}getEnvOverrides(){if(this._strength==="strong")return{PATH:null,TEMP:null,TMP:null,LD_PRELOAD:null,DYLD_INSERT_LIBRARIES:null,DYLD_LIBRARY_PATH:null,DYLD_FRAMEWORK_PATH:null,DYLD_ROOT_PATH:null,DYLD_FORCE_FLAT_NAMESPACE:null};return this._fallbackExecutor.getEnvOverrides()}async executeNative(command,workspaceRoot,runId){if(this._strength!=="strong")throw new SandboxError("Native execution requires strong sandbox (runner binary)","NATIVE_UNAVAILABLE");let policy=buildDefaultPolicy(workspaceRoot,runId);return execute(command,policy)}get hasNativeRunner(){return this._strength==="strong"}get disabledReason(){return this._disabledReason}get probeResult(){return this._probeResult}}var init_native_sandbox_executor=__esm(()=>{init_logger();init_executor();init_restricted_environment_executor();init_runner_client()});var exports_windows={};__export(exports_windows,{WindowsSandboxExecutor:()=>NativeWindowsSandboxExecutor,LegacyWindowsSandboxExecutor:()=>WindowsSandboxExecutor});var init_windows=__esm(()=>{init_native_sandbox_executor();init_restricted_environment_executor()});function isValidEnvKey(key){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)}function isUntrustedEnvKey(key){let upper=key.toUpperCase();for(let prefix of UNTRUSTED_ENV_KEY_PREFIXES)if(upper.startsWith(prefix))return!0;return!1}async function getExecutor(){if(_cachedExecutorPromise!==void 0)return _cachedExecutorPromise;return _cachedExecutorPromise=_createExecutor(),_cachedExecutorPromise}async function _createExecutor(){let platform=process.platform;if(platform==="linux")return _createLinuxExecutor();if(platform==="darwin")return _createMacOSExecutor();if(platform==="win32")return _createWindowsExecutor();return null}async function _createLinuxExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isBubblewrapAvailable:isBubblewrapAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isBubblewrapAvailable2())return null;try{let{BubblewrapSandboxExecutor:BubblewrapSandboxExecutor2}=(init_bubblewrap(),__toCommonJS(exports_bubblewrap));return new BubblewrapSandboxExecutor2([])}catch{return null}}function setMacOSSandboxPolicy(enabled){_macosSandboxEnabled=enabled}async function _createMacOSExecutor(){if(!_macosSandboxEnabled){if(!_hasWarnedMacOSSandboxDisabledByConfig)_hasWarnedMacOSSandboxDisabledByConfig=!0,warn("[sandbox] macOS sandbox-exec is disabled by config (guardrails.sandbox_macos_enabled=false). "+"Enable it only after verifying the production SBPL profile on a real macOS host — see docs/configuration.md.");return null}let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isSandboxExecAvailable:isSandboxExecAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isSandboxExecAvailable2())return null;try{let{MacOSSandboxExecutor:MacOSSandboxExecutor2}=(init_macos(),__toCommonJS(exports_macos));return new MacOSSandboxExecutor2([])}catch{return null}}async function _createWindowsExecutor(){let{SandboxCapabilityProbe:SandboxCapabilityProbe2,isWindowsSandboxAvailable:isWindowsSandboxAvailable2}=await Promise.resolve().then(() => (init_capability_probe(),exports_capability_probe));if(await new SandboxCapabilityProbe2().detect(),!isWindowsSandboxAvailable2())return null;try{let{WindowsSandboxExecutor:WindowsSandboxExecutor2}=(init_windows(),__toCommonJS(exports_windows));return new WindowsSandboxExecutor2([])}catch{return null}}var SandboxError,UNTRUSTED_ENV_KEY_PREFIXES,_cachedExecutorPromise,_macosSandboxEnabled=!1,_hasWarnedMacOSSandboxDisabledByConfig=!1;var init_executor=__esm(()=>{init_logger();SandboxError=class SandboxError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="SandboxError"}};UNTRUSTED_ENV_KEY_PREFIXES=["GIT_","LD_","DYLD_"]});function isTransientSpawnError(error49){if(!error49||typeof error49!=="object")return!1;return error49.code==="ETIMEDOUT"}function transientBackoff(attempt){let delay=200*2**attempt;try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,delay)}catch{let start=Date.now();while(Date.now()-start<delay);}}var MAX_TRANSIENT_RETRIES=5;import*as child_process2 from"node:child_process";import*as fsSync3 from"node:fs";import path32 from"node:path";function errorMessage(err){return err instanceof Error?err.message:String(err)}function isNotGitRepositoryMessage(message){let lower=message.toLowerCase();return lower.includes("not a git repository")||lower.includes("not a git repo")}function getChildProcessSpawnSync(){return child_process2.spawnSync}function readLaneEnvFileFromDiskSync(worktreePath,laneIndex){let envPath=path32.join(worktreePath,".swarm","lanes",`${laneIndex}.env`),content;try{content=fsSync3.readFileSync(envPath,"utf-8")}catch{return{}}let result={};for(let rawLine of content.split(`
482
+ `)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}function gitBinaryMissingMessage(cwd){let resolution=describeGitResolution(),lines=[`git executable is not available: spawning "${resolution.resolvedPath??"git"}" failed, and the working directory ${cwd} exists and is a directory.`];if(resolution.attempts.length>0){lines.push("Candidates tried:");let shown=resolution.attempts.slice(0,MAX_RENDERED_GIT_CANDIDATES);for(let attempt of shown)lines.push(` - [${attempt.source}] ${attempt.candidate}: ${attempt.accepted?"accepted":attempt.reason??"rejected"}`);let omitted=resolution.attempts.length-shown.length;if(omitted>0)lines.push(` ... and ${omitted} more`)}else lines.push("No candidate probe results are recorded for this process (the resolver was pre-seeded or has not probed yet).");return lines.push(resolution.overrideValue?`The configured override (${resolution.overrideSource??"unknown"}) "${resolution.overrideValue}" did not work — point the ${GIT_BINARY_ENV_VAR} environment variable, or the "git.binary" value in your USER config (a project .opencode config is ignored for this key), at a working git executable.`:`No override is configured. Set the ${GIT_BINARY_ENV_VAR} environment variable, or the "git.binary" value in your USER config (a project .opencode config is ignored for this key), to point at a working git executable.`),lines.join(`
483
483
  `)}function gitExec(args2,cwd,laneEnv,laneIndex){let resolvedLaneEnv=laneEnv??(laneIndex!==void 0?readLaneEnvFileFromDiskSync(cwd,laneIndex):void 0),subcommand=args2[0],hardenedArgs=subcommand==="commit"||subcommand==="tag"?["-c","commit.gpgsign=false","-c","tag.gpgsign=false",...args2]:args2,command=_internals26.resolveGitExecutable();for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=_internals26.spawnSync(command,hardenedArgs,{cwd,encoding:"utf-8",timeout:GIT_TIMEOUT_MS2,windowsHide:!0,maxBuffer:GIT_MAX_BUFFER_BYTES,stdio:["ignore","pipe","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"},envOverrides:resolvedLaneEnv});if(!result.error&&result.status===0)return result.stdout;if(result.error){if(isSpawnCwdMissing(result.error,cwd))throw new GitSpawnCwdError(cwd,"missing",{cause:result.error});if(isSpawnCwdUnreadable(result.error,cwd))throw new GitSpawnCwdError(cwd,"unreadable",{cause:result.error});if(isGitBinaryMissing(result.error,cwd))throw new GitBinaryMissingError(gitBinaryMissingMessage(cwd),{cause:result.error});if(isTransientSpawnError(result.error)&&attempt<MAX_TRANSIENT_RETRIES-1){transientBackoff(attempt);continue}throw Error(errorMessage(result.error))}if(result.status!==0)throw Error(result.stderr||result.stdout||`git exited with ${result.status}`)}throw new GitBinaryMissingError(process.platform==="win32"?"git executable is not available on PATH or common Windows install locations":"git executable is not available on PATH")}function getGitRepositoryStatus(cwd){try{return gitExec(["rev-parse","--git-dir"],cwd),{isRepo:!0}}catch(err){if(err instanceof GitBinaryMissingError)return{isRepo:!1,reason:"git_unavailable",message:err.message};let message=errorMessage(err);return{isRepo:!1,reason:isNotGitRepositoryMessage(message)?"not_git_repo":"git_error",message}}}function isGitRepo(cwd){return getGitRepositoryStatus(cwd).isRepo}function getCurrentBranch(cwd,laneEnv,laneIndex){return gitExec(["rev-parse","--abbrev-ref","HEAD"],cwd,laneEnv,laneIndex).trim()}function getDefaultBaseBranch(cwd){try{return gitExec(["rev-parse","--verify","origin/main"],cwd),"origin/main"}catch{try{return gitExec(["rev-parse","--verify","origin/master"],cwd),"origin/master"}catch{return"origin/main"}}}function hasUncommittedChanges(cwd,laneEnv,laneIndex){return gitExec(["status","--porcelain"],cwd,laneEnv,laneIndex).trim().length>0}function detectDefaultRemoteBranch(cwd){try{let trimmed=gitExec(["symbolic-ref","refs/remotes/origin/HEAD"],cwd).trim();if(trimmed.startsWith("refs/remotes/origin/"))return trimmed.slice(20)}catch{}try{let branch=gitExec(["config","init.defaultBranch"],cwd).trim();if(branch)return branch}catch{}try{return gitExec(["rev-parse","--verify","origin/main"],cwd),"main"}catch{}try{return gitExec(["rev-parse","--verify","origin/master"],cwd),"master"}catch{return null}}async function resetToRemoteBranch(cwd,options){let warnings=[],prunedBranches=[];try{let currentBranch=getCurrentBranch(cwd),defaultRemoteBranch=_internals26.detectDefaultRemoteBranch(cwd);if(!defaultRemoteBranch)return{success:!1,targetBranch:"",localBranch:currentBranch,message:"Could not detect default remote branch",alreadyAligned:!1,prunedBranches:[],warnings:[]};let targetBranch=`origin/${defaultRemoteBranch}`;if(currentBranch==="HEAD")return{success:!1,targetBranch,localBranch:"HEAD",message:"Cannot reset: detached HEAD state",alreadyAligned:!1,prunedBranches:[],warnings:[]};if(hasUncommittedChanges(cwd))return{success:!1,targetBranch,localBranch:currentBranch,message:"Cannot reset: uncommitted changes in working tree",alreadyAligned:!1,prunedBranches:[],warnings:[]};try{if(gitExec(["log",`${targetBranch}..HEAD`,"--oneline"],cwd).trim().length>0)return{success:!1,targetBranch,localBranch:currentBranch,message:"Cannot reset: unpushed commits",alreadyAligned:!1,prunedBranches:[],warnings:[]}}catch{}try{gitExec(["fetch","--prune","origin"],cwd)}catch(err){return{success:!1,targetBranch,localBranch:currentBranch,message:`Fetch failed: ${err instanceof Error?err.message:String(err)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]}}let headSha=gitExec(["rev-parse","HEAD"],cwd).trim(),remoteSha=gitExec(["rev-parse",`${targetBranch}`],cwd).trim();if(headSha===remoteSha)return{success:!0,targetBranch,localBranch:currentBranch,message:"Already aligned with remote",alreadyAligned:!0,prunedBranches:[],warnings:[]};try{gitExec(["checkout",currentBranch],cwd)}catch(err){return{success:!1,targetBranch,localBranch:currentBranch,message:`Checkout failed: ${err instanceof Error?err.message:String(err)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]}}let resetSucceeded=!1,lastError;for(let retry=0;retry<4;retry++){if(retry>0&&process.platform==="win32")await new Promise((resolve16)=>setTimeout(resolve16,500));try{gitExec(["reset","--hard",targetBranch],cwd),resetSucceeded=!0;break}catch(err){lastError=err}}if(!resetSucceeded)return{success:!1,targetBranch,localBranch:currentBranch,message:`Reset failed: ${lastError instanceof Error?lastError.message:String(lastError)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]};if(options?.pruneBranches){try{let mergedLines=gitExec(["branch","--merged",targetBranch],cwd).split(`
484
484
  `);for(let line of mergedLines){let trimmedLine=line.trim();if(!trimmedLine||trimmedLine.startsWith("*"))continue;try{gitExec(["branch","-d",trimmedLine],cwd),prunedBranches.push(trimmedLine)}catch{warnings.push(`Could not safely delete branch: ${trimmedLine}`)}}}catch(err){warnings.push(`Failed to get merged branches: ${err instanceof Error?err.message:String(err)}`)}try{let vvLines=gitExec(["branch","-vv"],cwd).split(`
485
485
  `);for(let line of vvLines){let trimmedLine=line.trim();if(!trimmedLine||trimmedLine.startsWith("*"))continue;if(trimmedLine.includes(": gone]")){let branchName=trimmedLine.split(/\s+/)[0];try{gitExec(["branch","-d",branchName],cwd),prunedBranches.push(branchName)}catch{warnings.push(`Could not delete gone branch: ${branchName}`)}}}}catch(err){warnings.push(`Failed to prune gone branches: ${err instanceof Error?err.message:String(err)}`)}}return{success:!0,targetBranch,localBranch:currentBranch,message:"Successfully reset to remote branch",alreadyAligned:!1,prunedBranches,warnings}}catch(err){return{success:!1,targetBranch:"",localBranch:"",message:`Unexpected error: ${err instanceof Error?err.message:String(err)}`,alreadyAligned:!1,prunedBranches:[],warnings:[]}}}async function resetToMainAfterMerge(cwd,options){let warnings=[];try{let defaultBranch=_internals26.detectDefaultRemoteBranch(cwd);if(!defaultBranch)return{success:!1,targetBranch:"",previousBranch:"",message:"Could not detect default remote branch",branchDeleted:!1,changesDiscarded:!1,warnings};let currentBranch=getCurrentBranch(cwd),targetBranch=`origin/${defaultBranch}`;if(currentBranch==="HEAD")return{success:!1,targetBranch,previousBranch:"HEAD",message:"Cannot reset: detached HEAD state",branchDeleted:!1,changesDiscarded:!1,warnings};if(currentBranch===defaultBranch)try{if(_internals26.gitExec(["log",`${targetBranch}..HEAD`,"--oneline"],cwd).trim().length>0)return{success:!1,targetBranch,previousBranch:currentBranch,message:`Cannot reset: ${defaultBranch} has unpushed commits. Push them first.`,branchDeleted:!1,changesDiscarded:!1,warnings}}catch{}else try{_internals26.gitExec(["rev-parse","--abbrev-ref",`${currentBranch}@{upstream}`],cwd)}catch{try{let localSha=_internals26.gitExec(["rev-parse","HEAD"],cwd).trim(),remoteSha=_internals26.gitExec(["rev-parse",targetBranch],cwd).trim();if(localSha!==remoteSha)return{success:!1,targetBranch,previousBranch:currentBranch,message:`Cannot reset: branch ${currentBranch} is local-only and diverges from ${defaultBranch}. Push or check manually.`,branchDeleted:!1,changesDiscarded:!1,warnings}}catch{return{success:!1,targetBranch,previousBranch:currentBranch,message:`Cannot reset: unable to compare ${currentBranch} with ${defaultBranch}`,branchDeleted:!1,changesDiscarded:!1,warnings}}}try{_internals26.gitExec(["fetch","--prune","origin"],cwd)}catch(err){return{success:!1,targetBranch,previousBranch:currentBranch,message:`Cannot reset: fetch failed — ${err instanceof Error?err.message:String(err)}`,branchDeleted:!1,changesDiscarded:!1,warnings}}let previousBranch=currentBranch,switchedBranch=!1;if(currentBranch!==defaultBranch)try{_internals26.gitExec(["checkout",defaultBranch],cwd),switchedBranch=!0}catch(err){return{success:!1,targetBranch,previousBranch,message:`Checkout to ${defaultBranch} failed: ${err instanceof Error?err.message:String(err)}`,branchDeleted:!1,changesDiscarded:!1,warnings}}try{_internals26.gitExec(["reset","--hard",targetBranch],cwd)}catch(err){return{success:!1,targetBranch,previousBranch,message:`Reset to ${targetBranch} failed: ${err instanceof Error?err.message:String(err)}`,branchDeleted:!1,changesDiscarded:!1,warnings}}let changesDiscarded=!1;if(hasUncommittedChanges(cwd)){let discardSucceeded=!1;for(let retry=0;retry<4;retry++){if(retry>0&&process.platform==="win32")await new Promise((resolve16)=>setTimeout(resolve16,500));try{_internals26.gitExec(["checkout","--","."],cwd),discardSucceeded=!0;break}catch{}}if(!discardSucceeded)warnings.push("Could not discard all uncommitted changes after reset");changesDiscarded=discardSucceeded}try{_internals26.gitExec(["clean","-fdX","--",...GITIGNORED_BUILD_ARTIFACTS],cwd)}catch{warnings.push("Could not clean build artifacts")}let branchDeleted=!1;if(switchedBranch&&previousBranch!==defaultBranch)try{if(_internals26.gitExec(["branch","--merged",defaultBranch],cwd).split(`
@@ -650,7 +650,7 @@ ${transcriptTail}`].join(`
650
650
  `,{encoding:"utf8",flag:"wx"}),fs38.renameSync(tempPath,absolutePath)}catch(error49){try{fs38.unlinkSync(tempPath)}catch{}throw error49}return owner}function removeWorktreeProvisioningOwner(directory,callID){try{return fs38.unlinkSync(ownerPath(directory,callID)),!0}catch(error49){return error49.code==="ENOENT"}}function scanWorktreeProvisioningOwnersForRecovery(directory){let directoryPath,entries;try{directoryPath=ownerDirectory(directory),entries=fs38.readdirSync(directoryPath,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`worktree provisioning-owner directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_PROVISIONING_OWNERS)return{status:"uncertain",reason:`worktree provisioning-owner count exceeds the ${MAX_PROVISIONING_OWNERS}-marker safety bound`};let owners=[];for(let entry of entries){let absolutePath=path60.join(directoryPath,entry.name);try{if(fs38.statSync(absolutePath).size>MAX_PROVISIONING_OWNER_BYTES)return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" exceeds the recovery size bound`};let raw=fs38.readFileSync(absolutePath,"utf8");if(Buffer.byteLength(raw,"utf8")>MAX_PROVISIONING_OWNER_BYTES)return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" changed beyond the recovery size bound`};let parsed=JSON.parse(raw);if(!isOwner(parsed))return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" is invalid`};owners.push(parsed)}catch(error49){return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" is unreadable or malformed: ${error49 instanceof Error?error49.message:String(error49)}`}}}return{status:"ok",owners}}var PROVISIONING_OWNER_DIR="worktree-provisioning-owners",MAX_PROVISIONING_OWNERS=512,MAX_PROVISIONING_OWNER_BYTES=16384,WORKTREE_PROVISIONING_OWNER_LEASE_MS=300000,WORKTREE_LIFECYCLE_LOCK_FILE=".swarm/locks/init-orphan-recovery.lock";var init_worktree_provisioning_owner=__esm(()=>{init_utils2()});import*as fs39 from"node:fs";import*as path61 from"node:path";function decodeTagPart(value){if(!value||!/^[A-Za-z0-9_-]+$/.test(value))return null;let decoded=Buffer.from(value,"base64url").toString("utf8");return decoded&&Buffer.from(decoded,"utf8").toString("base64url")===value?decoded:null}async function scanBackgroundWorktreeOwnershipTagsForRecovery(directory){try{fs39.statSync(path61.join(directory,".git"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`Git metadata could not be inspected: ${error49 instanceof Error?error49.message:String(error49)}`}}let proc;try{proc=bunSpawn([resolveGitExecutable(),"-C",directory,"for-each-ref",`--count=${MAX_OWNERSHIP_TAGS+1}`,"--format=%(refname:strip=2)%00%(objectname)","refs/tags/swarm-preserved-owner/"],{stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:OWNERSHIP_TAG_SCAN_TIMEOUT_MS});let exitCode=await proc.exited;if(exitCode!==0)return{status:"uncertain",reason:`ownership tag scan exited ${exitCode}`};let lines=(await proc.stdout.text()).split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);if(lines.length>MAX_OWNERSHIP_TAGS)return{status:"uncertain",reason:`ownership tag scan exceeded the ${MAX_OWNERSHIP_TAGS}-tag safety bound`};let owners=[];for(let line of lines){let[tag,ref,...extra]=line.split("\x00"),segments=tag?.split("/")??[],sessionId=decodeTagPart(segments[1]??""),laneId=decodeTagPart(segments[2]??""),callDigest=segments[3];if(extra.length>0||segments.length!==4||segments[0]!=="swarm-preserved-owner"||!sessionId||!laneId||!callDigest||!/^[0-9a-f]{12}$/.test(callDigest)||!ref||!/^[0-9a-f]{40,64}$/i.test(ref))return{status:"uncertain",reason:`malformed background ownership tag entry "${tag??""}"`};owners.push({sessionId,laneId,callDigest,ref})}return{status:"ok",owners}}catch(error49){return{status:"uncertain",reason:`ownership tag scan failed: ${error49 instanceof Error?error49.message:String(error49)}`}}finally{try{proc?.kill()}catch{}}}var OWNERSHIP_TAG_SCAN_TIMEOUT_MS=2000,MAX_OWNERSHIP_TAGS=512;var init_worktree_ownership_tag=__esm(()=>{init_bun_compat();init_git_executable()});var exports_worktree_collision_ownership={};__export(exports_worktree_collision_ownership,{inspectStandardWorktreeCollisionOwnership:()=>inspectStandardWorktreeCollisionOwnership,_internals:()=>_internals52});import*as fs40 from"node:fs";import*as path62 from"node:path";function normalizedPath(value){let resolved=path62.normalize(path62.resolve(value));return process.platform==="win32"?resolved.toLowerCase():resolved}function descriptorCoordinateMatch(descriptor,identity){let branchMatches=descriptor.branchName===identity.branchName,pathMatches2=normalizedPath(descriptor.worktreePath)===normalizedPath(identity.worktreePath);if(!branchMatches&&!pathMatches2)return"none";if(!branchMatches||!pathMatches2||descriptor.parentSessionId!==identity.parentSessionId||descriptor.taskId!==identity.taskId)return"uncertain";return"exact"}function isProvenSettled(record2){let settlement=record2.coderSettlement;return settlement?.state==="settled"&&settlement.outcome?.kind==="standard-worktree"&&(settlement.outcome.result==="merged"||settlement.outcome.result==="unchanged")}function classifyRecord(record2,identity,ownerKind){if(!record2.worktree)return null;let coordinates=descriptorCoordinateMatch(record2.worktree,identity);if(coordinates==="none")return null;if(coordinates==="uncertain")return{status:"uncertain",reason:`${ownerKind} background owner has conflicting identity for branch "${identity.branchName}"`};if(isProvenSettled(record2))return null;let lifecycle=record2.coderSettlement?.state==="preserved"?"preserved":"active";return{status:"protected",ownerKind,lifecycle,reason:`${ownerKind} background owner ${record2.correlationId} is ${record2.status}`+(record2.coderSettlement?` with coder settlement ${record2.coderSettlement.state}`:" without a settled workspace outcome")}}async function inspectStandardWorktreeCollisionOwnership(identity){let provisioning=scanWorktreeProvisioningOwnersForRecovery(identity.directory);if(provisioning.status==="uncertain")return provisioning;let now=Date.now();for(let owner of provisioning.owners){if(!(owner.parentSessionId===identity.parentSessionId||owner.worktreeSessionId===identity.parentSessionId))continue;if(owner.schemaVersion===1||owner.taskId===identity.taskId){let leaseIsLive=now-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS;if(!leaseIsLive)try{_internals52.statSync(identity.worktreePath)}catch(error49){let code=error49.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} lane liveness is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`};if(!_internals52.removeWorktreeProvisioningOwner(identity.directory,owner.callID))return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} could not be removed`};continue}return{status:"protected",ownerKind:"provisioning",lifecycle:"active",reason:!leaseIsLive?`provisioning owner ${owner.callID} lease expired, but its exact lane path still exists`:owner.schemaVersion===1?`legacy provisioning owner ${owner.callID} cannot disprove ownership of this same-session lane`:`provisioning owner ${owner.callID} is active for task ${identity.taskId}`}}}let fallback=await scanDelegationFallbacksForRecovery(identity.directory);if(fallback.status==="uncertain")return fallback;for(let artifact of fallback.owners){let classified=classifyRecord(artifact.record,identity,"fallback");if(classified)return classified}let primary=scanDelegationsForRecovery(identity.directory);if(primary.status==="uncertain")return primary;for(let record2 of primary.owners){let classified=classifyRecord(record2,identity,"primary");if(classified)return classified}let tags=await scanBackgroundWorktreeOwnershipTagsForRecovery(identity.directory);if(tags.status==="uncertain")return tags;for(let owner of tags.owners)if(owner.sessionId===identity.parentSessionId&&owner.laneId===identity.taskId)return{status:"protected",ownerKind:"ownership-tag",lifecycle:"preserved",reason:`durable ownership tag ${owner.callDigest} preserves this same-session lane`};let mergeStatus=scanWorktreeMergeFailuresForRecovery(identity.directory);if(mergeStatus.status==="uncertain")return mergeStatus;for(let[,failure]of mergeStatus.failures){let branchMatches=failure.branch===identity.branchName,pathMatches2=typeof failure.worktreePath==="string"&&normalizedPath(failure.worktreePath)===normalizedPath(identity.worktreePath);if(!branchMatches&&!pathMatches2)continue;if(!branchMatches||!pathMatches2)return{status:"uncertain",reason:`merge-status owner has conflicting identity for branch "${identity.branchName}"`};return{status:"protected",ownerKind:"merge-status",lifecycle:"preserved",reason:`merge-status records ${failure.outcome} at stage ${failure.stage}`}}return{status:"unowned"}}var _internals52;var init_worktree_collision_ownership=__esm(()=>{init_pending_delegations();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();_internals52={statSync:fs40.statSync,removeWorktreeProvisioningOwner}});var exports_worktree_isolation={};__export(exports_worktree_isolation,{standardWorktreeSerializationSessions:()=>standardWorktreeSerializationSessions,standardWorktreeByCallID:()=>standardWorktreeByCallID,sanitizeWorktreeTaskId:()=>sanitizeWorktreeTaskId,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resetStandardWorktreeIsolationState:()=>resetStandardWorktreeIsolationState,readLaneEnvFileFromDisk:()=>readLaneEnvFileFromDisk,preserveDirtyWorktreeForCallId:()=>preserveDirtyWorktreeForCallId,preserveDirtyWorktreeAtPath:()=>preserveDirtyWorktreeAtPath,preserveBackgroundWorktreeOwnershipForCallId:()=>preserveBackgroundWorktreeOwnershipForCallId,precreateStandardWorktreeSession:()=>precreateStandardWorktreeSession,preProvisionCollisionCheck:()=>preProvisionCollisionCheck,parseLeanLaneIndex:()=>parseLeanLaneIndex,isLaneOwnedByCurrentSession:()=>isLaneOwnedByCurrentSession,finishStandardWorktreeDispatch:()=>finishStandardWorktreeDispatch,computeLaneRuntimeProfile:()=>computeLaneRuntimeProfile,cleanupStandardWorktreeForCallId:()=>cleanupStandardWorktreeForCallId,checkStandardWorktreeSerializationRelease:()=>checkStandardWorktreeSerializationRelease,awaitingMergeByCallID:()=>awaitingMergeByCallID,abortStandardWorktreeDispatch:()=>abortStandardWorktreeDispatch,_internals:()=>_internals53,MAX_TRACKED_STANDARD_WORKTREE_CALLS:()=>MAX_TRACKED_STANDARD_WORKTREE_CALLS});import{createHash as createHash23}from"node:crypto";import*as fs41 from"node:fs/promises";import*as path63 from"node:path";function parseLeanLaneIndex(laneId){let match=/^lane-(\d+)$/.exec(laneId);if(match){let n=parseInt(match[1],10);return Number.isNaN(n)?0:n-1}return 0}function computeLaneRuntimeProfile(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects)){let laneSuffix=path63.join(basePath,`lane-${laneIndex}`);envOverrides[envName]=laneSuffix}return{laneIndex,worktreePath,envOverrides}}function allocateStandardLaneIndex(parentSessionID){let current=standardWorktreeLaneIndexBySession.get(parentSessionID)??0;return standardWorktreeLaneIndexBySession.set(parentSessionID,current+1),current}function rememberStandardWorktreeDispatch(dispatch){standardWorktreeByCallID.set(dispatch.callID,dispatch)}function hasStandardWorktreeDispatchCapacity(){return standardWorktreeByCallID.size<MAX_TRACKED_STANDARD_WORKTREE_CALLS}function hasInFlightStandardWorktreeDispatch(parentSessionID){for(let dispatch of standardWorktreeByCallID.values())if(dispatch.parentSessionID===parentSessionID)return!0;for(let record2 of awaitingMergeByCallID.values())if(record2.parentSessionID===parentSessionID)return!0;return!1}function handleStandardWorktreeFailure(parentSessionID,policy,message){if(policy==="required")throw Error(message);if(hasInFlightStandardWorktreeDispatch(parentSessionID))throw Error(`STANDARD_WORKTREE_ISOLATION_UNSAFE: ${message} Sibling coder task(s) are isolated in worktrees for this session, so dispatching this coder un-isolated in the main tree would risk a merge-back collision. Wait for in-flight coder task(s) to be reviewed and merged, then retry.`);serializeStandardWorktreeDispatches(parentSessionID,message)}function hardStopStandardWorktreeLifecycle(parentSessionID,message){let session=ensureAgentSession(parentSessionID);throw pushAdvisory(session,message),Error(message)}function serializeStandardWorktreeDispatches(sessionID,message){if(!rememberStandardWorktreeSerializationSession(sessionID)){let session2=ensureAgentSession(sessionID);pushAdvisory(session2,`${message} Serialization tracking is at capacity (256 sessions active); continuing in normal parallel mode.`);return}let session=ensureAgentSession(sessionID);session.maxConcurrencyOverride=1,pushAdvisory(session,`${message} Serializing standard coder dispatches for this session.`)}function resetStandardWorktreeIsolationState(){standardWorktreeByCallID.clear(),standardWorktreeSerializationSessions.clear(),serializationStateBySessionID.clear(),awaitingMergeByCallID.clear(),standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession.clear()}function releaseStandardWorktreeSerialization(sessionID){if(!standardWorktreeSerializationSessions.has(sessionID))return!1;standardWorktreeSerializationSessions.delete(sessionID),serializationStateBySessionID.delete(sessionID);let session=ensureAgentSession(sessionID);return session.maxConcurrencyOverride=void 0,pushAdvisory(session,`WORKTREE_SERIALIZATION_RELEASED: ${sessionID} regains parallel dispatch eligibility (release-after-dispatches or TTL).`),!0}function checkStandardWorktreeSerializationRelease(sessionID,config2){let state=serializationStateBySessionID.get(sessionID);if(!state)return;let count=config2.serialization_release_after_dispatches??5,ttl=config2.serialization_release_after_ms??60000;if(state.successfulDispatchesSince>=count){releaseStandardWorktreeSerialization(sessionID);return}if(Date.now()-state.serializedAt>=ttl)releaseStandardWorktreeSerialization(sessionID)}function rememberStandardWorktreeSerializationSession(sessionID){if(standardWorktreeSerializationSessions.size>=MAX_TRACKED_STANDARD_WORKTREE_CALLS){let evicted=!1;for(let key of serializationStateBySessionID.keys())if(!hasInFlightStandardWorktreeDispatch(key)){standardWorktreeSerializationSessions.delete(key),serializationStateBySessionID.delete(key),evicted=!0;break}if(!evicted)return log(`[worktree-isolation] serialization set at cap with all sessions active; refusing eviction for ${sessionID}`),!1}if(standardWorktreeSerializationSessions.add(sessionID),!serializationStateBySessionID.has(sessionID))serializationStateBySessionID.set(sessionID,{sessionID,serializedAt:Date.now(),successfulDispatchesSince:0});return!0}function sanitizeWorktreeTaskId(raw){return raw.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)||"task"}async function preProvisionCollisionCheck(taskId,directory,_sessionId){let proc;try{proc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",directory,"worktree","list","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:WORKTREE_LIST_TIMEOUT_MS})}catch(error49){let detail=`git worktree list could not start in ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`;return log(`[swarm] preProvisionCollisionCheck: ${detail}`),{collision:!1,uncertainty:detail}}let stdout="",stderr="";try{let exitCode=await proc.exited;if(stdout=await proc.stdout.text(),stderr=await proc.stderr.text(),exitCode!==0){if(stderr.toLowerCase().includes("not a git repository"))return{collision:!1};return log(`[swarm] preProvisionCollisionCheck: git worktree list failed (exit ${exitCode}): ${stderr}`),{collision:!1,uncertainty:stderr.trim()||`git worktree list exited ${exitCode}`}}}finally{try{proc.kill()}catch{}}let entries=[],current={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
651
651
  `)){let line=rawLine.trim();if(line.startsWith("worktree ")){if(current.path)entries.push(current);current={path:line.slice(9),branch:void 0,prunable:!1}}else if(line.startsWith("branch "))current.branch=line.slice(7);else if(line==="prunable"||line.startsWith("prunable "))current.prunable=!0}if(current.path)entries.push(current);for(let entry of entries){if(!entry.branch)continue;if(entry.prunable)continue;let branchName=entry.branch.startsWith("refs/heads/")?entry.branch.slice(11):entry.branch,segments=branchName.split("/");if(segments.length>=4&&segments[0]==="swarm"&&segments[1]==="lane"){if(segments[3]===taskId){let ownerSessionId=segments[2];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}if(segments.length>=3&&segments[0]==="swarm-lane"){if(segments[2]===taskId){let ownerSessionId=segments[1];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}}return{collision:!1}}function isLaneOwnedByCurrentSession(branchName,expectedSessionId){return _internals18.extractSessionId(branchName)===expectedSessionId}async function inspectStandardWorktreeCollisionOwnership2(identity){return(await Promise.resolve().then(() => (init_worktree_collision_ownership(),exports_worktree_collision_ownership))).inspectStandardWorktreeCollisionOwnership(identity)}async function precreateStandardWorktreeSession(args2){let worktreeConfig=resolveWorktreeIsolationConfig(args2.config);if(worktreeConfig.policy==="disabled")return;if(standardWorktreeSerializationSessions.has(args2.parentSessionID)){if(checkStandardWorktreeSerializationRelease(args2.parentSessionID,worktreeConfig),!standardWorktreeSerializationSessions.has(args2.parentSessionID))return}if(!hasStandardWorktreeDispatchCapacity()){if(worktreeConfig.policy==="required")throw Error("STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");serializeStandardWorktreeDispatches(args2.parentSessionID,"STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");return}let client=swarmState.opencodeClient;if(!client){handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,"STANDARD_WORKTREE_ISOLATION_UNAVAILABLE: OpenCode SDK client is unavailable; standard parallel coder work cannot be isolated.");return}let laneIndex=allocateStandardLaneIndex(args2.parentSessionID),lifecycleLock=await _internals53.tryAcquireWorktreeLifecycleLock(args2.directory,WORKTREE_LIFECYCLE_LOCK_FILE,"worktree-provisioning",args2.taskId);if(!lifecycleLock.acquired)hardStopStandardWorktreeLifecycle(args2.parentSessionID,"STANDARD_WORKTREE_LIFECYCLE_BUSY: init orphan recovery is active; retry this coder dispatch after recovery completes.");try{let collision=await _internals53.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(collision.uncertainty)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_SCAN_UNCERTAIN: ${collision.uncertainty}. Destructive cleanup and provisioning were blocked.`);if(collision.collision){if(!collision.existingBranch||!collision.worktreePath||!isLaneOwnedByCurrentSession(collision.existingBranch,args2.parentSessionID)){let ownerInfo=collision.ownerSessionId?` owned by session ${collision.ownerSessionId}`:" with uncertain ownership";hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION: task ${args2.taskId} already has a lane on branch ${collision.existingBranch??"unknown"}${ownerInfo}; cleanup and provisioning were blocked.`)}for(let dispatch of _internals53.standardWorktreeByCallID.values())if(dispatch.handle.branchName===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_ACTIVE: branch ${collision.existingBranch} is still tracked by an active standard-worktree dispatch.`);for(let record2 of _internals53.awaitingMergeByCallID.values())if(record2.branch===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_AWAITING_MERGE: branch ${collision.existingBranch} is still awaiting merge-back.`);let ownership=await _internals53.inspectStandardWorktreeCollisionOwnership({directory:args2.directory,parentSessionId:args2.parentSessionID,taskId:args2.taskId,branchName:collision.existingBranch,worktreePath:collision.worktreePath});if(ownership.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNERSHIP_UNCERTAIN: ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);if(ownership.status==="protected")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PROTECTED: ${ownership.ownerKind} owner is ${ownership.lifecycle}; ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);let collisionPathExists=!0;try{await fs41.stat(collision.worktreePath)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ENOTDIR")collisionPathExists=!1;else hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PATH_STAT_FAILED: ${error49 instanceof Error?error49.message:String(error49)}. Destructive cleanup and provisioning were blocked.`)}if(collisionPathExists){let preserveResult=await _internals53.preserveDirtyWorktreeAtPath(collision.worktreePath,collision.existingBranch,"denied",args2.directory,worktreeConfig.worktree_dir);if(preserveResult.outcome==="preserve-failed")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: pre-provision collision for task ${args2.taskId} could not be preserved (${preserveResult.error}). Cleanup and provisioning were blocked.`);let removeResult=await _internals53.removeWorktree(collision.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir});if("error"in removeResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_REMOVE_FAILED: ${removeResult.error}. Provisioning was blocked.`);let cleanupResult=await _internals53.postMergeCleanup(args2.directory,collision.existingBranch);if("error"in cleanupResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_BRANCH_CLEANUP_FAILED: ${cleanupResult.error}. Provisioning was blocked.`)}else{let pruneResult=await _internals53.pruneStaleWorktreeMetadata(args2.directory);if("error"in pruneResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PRUNE_FAILED: ${pruneResult.error}. Provisioning was blocked without deleting the lane branch.`)}let verification=await _internals53.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(verification.uncertainty||verification.collision)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_CLEANUP_UNVERIFIED: ${verification.uncertainty??"git still reports the colliding lane after cleanup"}. Provisioning was blocked.`)}_internals53.recordWorktreeProvisioningOwner(args2.directory,{callID:args2.callID,parentSessionId:args2.parentSessionID,worktreeSessionId:args2.parentSessionID,taskId:args2.taskId})}catch(error49){if(error49 instanceof Error&&(error49.message.startsWith("STANDARD_WORKTREE_")||error49.message.startsWith("PREPROVISION_COLLISION")))throw error49;hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PERSIST_FAILED: ${error49 instanceof Error?error49.message:String(error49)}.`)}finally{try{await lifecycleLock.lock._release?.()}catch{}}let provisionResult;try{provisionResult=await _internals53.provisionWorktree(args2.directory,args2.taskId,args2.parentSessionID,{purpose:"lane",worktreeDir:worktreeConfig.worktree_dir,mergeStrategy:worktreeConfig.merge_strategy,depsStrategy:worktreeConfig.deps_strategy,scope:args2.scope})}catch(error49){throw _internals53.removeWorktreeProvisioningOwner(args2.directory,args2.callID),error49}if("error"in provisionResult){_internals53.removeWorktreeProvisioningOwner(args2.directory,args2.callID);let message=`STANDARD_WORKTREE_PROVISION_FAILED: ${provisionResult.error}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}let originalPrompt=typeof args2.outputArgs.prompt==="string"?args2.outputArgs.prompt:"";args2.outputArgs.prompt=["<worktree_lane_context>",`authoritative_lane_root: ${JSON.stringify(provisionResult.worktreePath)}`,"All FILE declarations and scope-bound edit/write paths must be workspace-relative to authoritative_lane_root.","Do not declare project-root absolute paths; resolve and operate inside this lane root.","</worktree_lane_context>","",originalPrompt].join(`
652
652
  `);let laneProfile=computeLaneRuntimeProfile(worktreeConfig.runtime_isolation,laneIndex,provisionResult.worktreePath);if(laneProfile)try{let{writeLaneProfileToDiskReal:writeLaneProfileToDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await writeLaneProfileToDiskReal2(provisionResult.worktreePath,laneProfile.laneIndex,laneProfile.envOverrides)}catch{}if((worktreeConfig.deps_strategy??"skip")==="skip"){let desc=(args2.description??args2.taskId??"").toLowerCase();if(/\btests?\b/.test(desc)||/\bbuild(ing|s)?\b/.test(desc)||/\blint(ing|er)?\b/.test(desc)||/\bchecks?\b/.test(desc)){let session=ensureAgentSession(args2.parentSessionID);pushAdvisory(session,`WORKTREE_DEPS_SKIP: task ${args2.taskId} was provisioned with deps_strategy: 'skip' (default). This task's gates appear to include test/build commands; the lane may lack node_modules. Set worktree.deps_strategy to 'copy' or 'link' (or use a non-worktree lane) if the task requires host dependencies.`)}}let createResult=await client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree lane)`},query:{directory:provisionResult.worktreePath}});if(!createResult.data?.id){await _internals53.removeWorktree(provisionResult.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch(()=>{}),_internals53.removeWorktreeProvisioningOwner(args2.directory,args2.callID);let createError=createResult.error,message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${typeof createError==="string"?createError:JSON.stringify(createError??"missing session id")}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}args2.outputArgs.task_id=createResult.data.id,ensureAgentSession(createResult.data.id,"coder",provisionResult.worktreePath),recordSessionWorkspaceRoot(createResult.data.id,provisionResult.worktreePath),rememberStandardWorktreeDispatch({callID:args2.callID,parentSessionID:args2.parentSessionID,taskId:args2.taskId,planTaskId:args2.planTaskId,handle:provisionResult,mergeStrategy:worktreeConfig.merge_strategy,laneIndex,worktree_dir:worktreeConfig.worktree_dir})}async function preserveBackgroundWorktreeOwnershipForCallId(callID){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch)return{outcome:"not-found"};let refProc;try{refProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",error:`git rev-parse could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let ref="";try{let exitCode=await refProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await refProc.stderr.text()||`git rev-parse exited ${exitCode}`};ref=(await refProc.stdout.text()).trim()}finally{try{refProc.kill()}catch{}}if(!ref)return{outcome:"preserve-failed",error:"git rev-parse returned empty"};let session=Buffer.from(dispatch.handle.sessionId,"utf8").toString("base64url"),lane=Buffer.from(dispatch.handle.id,"utf8").toString("base64url"),callDigest=createHash23("sha256").update(callID).digest("hex").slice(0,12),tag=`swarm-preserved-owner/${session}/${lane}/${callDigest}`,tagProc;try{tagProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"tag",tag,ref],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",error:`git tag could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let exitCode=await tagProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await tagProc.stderr.text()||`git tag exited ${exitCode}`}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",tag,ref}}async function preserveDirtyWorktreeForCallId(callID,reason,_directory,_worktree_dir){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{outcome:"clean",preserved:!1};worktreePath=awaiting.worktreePath,parentSessionID=awaiting.parentSessionID}let statusProc;try{statusProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeForCallId: git status failed for ${callID}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git add failed for ${callID}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedCallID=callID.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for callID ${sanitizedCallID} at ${isoDate}`,commitProc;try{commitProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git commit failed for ${callID}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git rev-parse failed for ${callID}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-${sanitizedCallID}-${shortHash}`,tagProc;try{tagProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git tag failed for ${callID}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_PRESERVED: dispatch ${callID} dirty work preserved as commit ${commitHash} (tag: ${tagName}; reason: ${reason}); worktree will be cleaned.`),{outcome:"preserved",preserved:!0,ref:commitHash}}async function preserveDirtyWorktreeAtPath(worktreePath,branchName,reason,_directory,_worktree_dir){let statusProc;try{statusProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeAtPath: git status failed for ${worktreePath}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git add failed for ${worktreePath}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedPath=worktreePath.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),sanitizedBranch=branchName.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for worktree ${sanitizedPath} at ${isoDate}`,commitProc;try{commitProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git commit failed for ${worktreePath}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git rev-parse failed for ${worktreePath}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-worktree-${sanitizedBranch}-${shortHash}`,tagProc;try{tagProc=_internals53.bunSpawn([_internals53.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git tag failed for ${worktreePath}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",preserved:!0,ref:commitHash}}async function cleanupStandardWorktreeForCallId(callID,reason,directory,worktree_dir){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,branchName,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,branchName=dispatch.handle.branchName,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return;worktreePath=awaiting.worktreePath,branchName=awaiting.branch,parentSessionID=awaiting.parentSessionID}let preserveResult;if(reason==="denied"||reason==="cancelled"){try{preserveResult=await _internals53.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: preserveDirtyWorktreeForCallId threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}if(preserveResult.outcome==="clean")try{preserveResult=await _internals53.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: final preservation check threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}}if(preserveResult&&preserveResult.outcome==="preserve-failed"){standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);pushAdvisory(session2,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: dispatch ${callID} has dirty uncommitted work but preservation failed (${preserveResult.error}). Cleanup aborted to protect uncommitted work. Investigate and resolve manually. Worktree=${worktreePath}; branch=${branchName}.`);return}await _internals53.removeWorktree(worktreePath,directory,{force:!0,worktreeDir:worktree_dir}).catch((err)=>log(`[swarm] cleanupStandardWorktreeForCallId: removeWorktree failed for ${callID}: ${err}`)),await _internals53.postMergeCleanup(directory,branchName).catch((err)=>log(`[swarm] cleanupStandardWorktreeForCallId: postMergeCleanup failed for ${callID}: ${err}`)),standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session=ensureAgentSession(parentSessionID);pushAdvisory(session,`STANDARD_WORKTREE_CLEANUP: dispatch ${callID} cleaned up (reason: ${reason}); worktree=${worktreePath}; branch=${branchName}.`)}async function abortStandardWorktreeDispatch(callID,reason,directory){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch){let session=ensureAgentSession("unknown");pushAdvisory(session,`STANDARD_WORKTREE_ABORT_NOOP: dispatch ${callID} has no tracked worktree to abort (reason: ${reason}).`);return}await cleanupStandardWorktreeForCallId(callID,reason,directory,dispatch.worktree_dir)}async function finishStandardWorktreeDispatch(directory,dispatch,config2,callID,settlement={}){let wtConfig=config2?resolveWorktreeIsolationConfig(config2):DEFAULT_WORKTREE_ISOLATION_CONFIG,resolvedCallID=callID??dispatch.callID,run=async()=>{let mergeResult=await _internals53.attemptMergeBackFromDirty(dispatch.handle.worktreePath,dispatch.handle.branchName,directory,getMergeStrategy({merge_strategy:dispatch.mergeStrategy}),{operationId:settlement.operationId,resume:settlement.resume,onBeforeMerge:settlement.onBeforeMerge}),statusKey=dispatch.planTaskId??dispatch.taskId;if("merged"in mergeResult&&mergeResult.merged){let mergedSettlement={outcome:"merged",strategy:mergeResult.strategy,autoCommitted:mergeResult.autoCommitted,cleaned:mergeResult.cleaned,reconciled:mergeResult.reconciled??!1,provenance:mergeResult.provenance};if(settlement.onMerged)try{await settlement.onMerged(mergedSettlement)}catch(error49){let failedSettlement={outcome:"failed",stage:"settlement-persist",message:`Git merge-back succeeded but settlement persistence failed: ${String(error49)}`,provenance:mergeResult.provenance};recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:failedSettlement.stage,message:failedSettlement.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_PERSIST_FAILED: task ${dispatch.taskId} landed in ${directory}, but settlement persistence failed; worktree and branch preserved at ${dispatch.handle.worktreePath} (${dispatch.handle.branchName}).`),failedSettlement}clearWorktreeMergeStatus(statusKey);try{let{removeLaneProfileFromDiskReal:removeLaneProfileFromDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await removeLaneProfileFromDiskReal2(dispatch.handle.worktreePath,dispatch.laneIndex)}catch{}let state=serializationStateBySessionID.get(dispatch.parentSessionID);if(state)state.successfulDispatchesSince++,checkStandardWorktreeSerializationRelease(dispatch.parentSessionID,wtConfig);try{verifyReviewerScopeGenerationMergeBack({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID,primaryDirectory:directory})}catch{}return await cleanupStandardWorktreeForCallId(resolvedCallID,"success",directory,dispatch.worktree_dir),mergedSettlement}if("partial"in mergeResult){recordWorktreeMergeFailure(statusKey,{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);pushAdvisory(session,`STANDARD_WORKTREE_MERGE_PARTIAL: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; stage: ${mergeResult.stage}; ${mergeResult.message}`);try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,autoCommitted:mergeResult.autoCommitted,cleaned:mergeResult.cleaned,conflictFiles:mergeResult.conflictFiles,provenance:mergeResult.provenance}}if("failed"in mergeResult){recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID),location=mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE||mergeResult.stage===SOURCE_WORKTREE_UNCERTAIN_STAGE?`lane worktree ${dispatch.handle.worktreePath} no longer exists`:`preserved at ${dispatch.handle.worktreePath}`;pushAdvisory(session,`STANDARD_WORKTREE_MERGE_FAILED: task ${dispatch.taskId} ${location}; stage: ${mergeResult.stage}; ${mergeResult.message}.`);try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,provenance:mergeResult.provenance}}return{outcome:"failed",stage:"merge",message:"Merge-back returned an unexpected result"}},queuedRun=standardWorktreeMergeQueue.then(run,run);standardWorktreeMergeQueue=queuedRun;let result=await queuedRun;if(resolvedCallID)awaitingMergeByCallID.delete(resolvedCallID);return result}async function readLaneEnvFileFromDisk(worktreePath,laneIndex){let envPath=path63.join(worktreePath,".swarm","lanes",`${laneIndex}.env`),content;try{content=await fs41.readFile(envPath,"utf-8")}catch(err){if(err.code==="ENOENT")return{};return log(`[worktree-isolation] failed to read lane env file ${envPath}: ${err.message}`),{}}let result={};for(let rawLine of content.split(`
653
- `)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals53;var init_worktree_isolation=__esm(()=>{init_constants();init_file_locks();init_executor();init_state2();init_bun_compat();init_git_executable();init_logger();init_worktree();init_merge();init_reviewer_scope_mergeback();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;_internals53={provisionWorktree,removeWorktree,attemptMergeBackFromDirty,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,preserveDirtyWorktreeAtPath,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});import{spawnSync as spawnSync9}from"node:child_process";import{randomUUID as randomUUID11}from"node:crypto";import{existsSync as existsSync31}from"node:fs";import{appendFile as appendFile8,mkdir as mkdir14,readdir as readdir5}from"node:fs/promises";import{dirname as dirname32}from"node:path";function dispatchKey(directory,taskId,transitionId){return`${directory}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){let line=`${JSON.stringify({type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}
653
+ `)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals53;var init_worktree_isolation=__esm(()=>{init_constants();init_file_locks();init_executor();init_state2();init_bun_compat();init_git_executable();init_logger();init_worktree();init_merge();init_reviewer_scope_mergeback();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;_internals53={provisionWorktree,removeWorktree,attemptMergeBackFromDirty,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,preserveDirtyWorktreeAtPath,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});import{spawnSync as spawnSync9}from"node:child_process";import{randomUUID as randomUUID11}from"node:crypto";import{existsSync as existsSync31}from"node:fs";import{appendFile as appendFile8,mkdir as mkdir14,readdir as readdir5}from"node:fs/promises";import{dirname as dirname32}from"node:path";function dispatchKey(directory,taskId,transitionId){return`${directory}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){let line=`${JSON.stringify({type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}
654
654
  `;try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await mkdir14(dirname32(eventsPath),{recursive:!0}),await appendFile8(eventsPath,line,"utf-8")}catch(error49){let code=error49.code;if(code==="EBUSY"||code==="EPERM")try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await appendFile8(eventsPath,line,"utf-8");return}catch(retryError){criticalWarn(`[coder-settlement] lifecycle event write failed after retry (${action} ${wal.taskId}): ${retryError instanceof Error?retryError.message:String(retryError)}`);return}criticalWarn(`[coder-settlement] lifecycle event write failed (${action} ${wal.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}}function baselineAttributionDoomed(baseline){if(baseline.gitHead===null)return!0;return Array.isArray(baseline.changedFiles)&&baseline.changedFiles.length>0}function doomedReason(baseline){if(baseline.gitHead===null)return"launch workspace has no git baseline (not a git repository, or git unavailable at dispatch)";return`launch baseline was dirty with ${String(baseline.changedFiles?.length??0)} pre-existing uncommitted/untracked change(s)`}function isProcessAlive2(processId){if(processId===process.pid)return!0;try{return process.kill(processId,0),!0}catch(error49){return error49.code==="EPERM"}}function scopedObservedFiles(directory,context){let baseline={...context.baseline,directory},observed=changedFilesSinceSnapshot(directory,baseline);if(!observed||!context.declaredFiles)return null;return observed.filter((filePath)=>isPathWithinDeclaredScope(filePath,context.declaredFiles??[],directory))}async function commitPrepared(directory,wal){return withTaskEvidenceTransaction(directory,wal.taskId,wal.actor,async(transaction)=>{let lockedWal=await readWal(walPath(directory,wal.taskId),wal.taskId);if(lockedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(lockedWal.transitionId!==wal.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let snapshot=getTaskWorkflowSnapshot(transaction.read());if(lockedWal.accepted===!0?snapshot.authoritative&&snapshot.state===(lockedWal.settlementFailed===!0?"rework_required":"coder_delegated")&&snapshot.generation===lockedWal.expectedGeneration+1&&snapshot.lastOutcome===(lockedWal.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation")&&snapshot.lastTransitionId===lockedWal.transitionId:snapshot.generation===lockedWal.expectedGeneration&&snapshot.lastOutcome==="dispatch_no_mutation"&&snapshot.lastTransitionId===lockedWal.transitionId){if(lockedWal.state!=="COMMITTED")lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0},await writeWal(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal,{resumed:!0});return{evidence:transaction.read(),accepted:lockedWal.accepted===!0,alreadyApplied:!0}}if(lockedWal.state!=="PREPARED")throw Error("CODER_SETTLEMENT_NOT_PREPARED");let evidence2=await transaction.transition(lockedWal.accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:lockedWal.testEngineerExempt===!0,settlementFailed:lockedWal.settlementFailed===!0},expectedGeneration:lockedWal.expectedGeneration,transitionId:lockedWal.transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:lockedWal.expectedGeneration,transitionId:lockedWal.transitionId});return lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0},await writeWal(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal),{evidence:evidence2,accepted:lockedWal.accepted===!0,alreadyApplied:!1}})}async function beginCoderSettlement(options){let filePath=walPath(options.directory,options.taskId),ownsActiveDispatch=!1;if(await withSettlementLock(options.directory,options.taskId,options.actor,()=>withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{let snapshot=getTaskWorkflowSnapshot(transaction.read());if(snapshot.generation!==options.expectedGeneration)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${options.expectedGeneration}, found ${snapshot.generation}`);let existing=await readWal(filePath,options.taskId);if(existing!==null){if((existing.state==="DISPATCHED"||existing.state==="PREPARED")&&existing.transitionId!==options.transitionId)throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${existing.transitionId} owns task ${options.taskId}, so transition ${options.transitionId} cannot dispatch it (${filePath}, state ${existing.state}). Wait for the owning transition to settle or run /swarm recover ${options.taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(existing.transitionId===options.transitionId){if(!(existing.actor===options.actor&&existing.expectedGeneration===options.expectedGeneration&&JSON.stringify(existing.context)===JSON.stringify(options.context)&&JSON.stringify(existing.worktree)===JSON.stringify(options.worktree)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(existing.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");ownsActiveDispatch=existing.state==="DISPATCHED"&&existing.runtimeId===runtimeId;return}}await transaction.transition({type:"dispatch_attempted",agentType:"coder",expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),await writeWal(filePath,{version:1,state:"DISPATCHED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,processId:process.pid,runtimeId,expectedGeneration:options.expectedGeneration,context:options.context,...options.worktree?{worktree:options.worktree}:{},recordedAt:new Date().toISOString()}),ownsActiveDispatch=!0,await appendSettlementEvent(options.directory,"dispatched",{taskId:options.taskId,transitionId:options.transitionId,actor:options.actor})})),ownsActiveDispatch){let key=dispatchKey(options.directory,options.taskId,options.transitionId);if(!liveDispatches.has(key)&&liveDispatches.size>=MAX_LIVE_DISPATCHES)throw Error("CODER_SETTLEMENT_CAPACITY_EXCEEDED");liveDispatches.add(key)}}async function settleCoderDispatch(options){return withSettlementLock(options.directory,options.taskId,"coder-settlement",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="COMMITTED"){if(wal.accepted!==options.accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==(options.settlementFailed===!0))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return commitPrepared(options.directory,wal)}if(wal.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(wal.state==="PREPARED"&&(wal.accepted!==options.accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==(options.settlementFailed===!0)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");let prepared={...wal,state:"PREPARED",accepted:options.accepted,testEngineerExempt:options.testEngineerExempt,settlementFailed:options.settlementFailed===!0};if(wal.state!=="PREPARED")await writeWal(filePath,prepared);liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId));try{return await commitPrepared(options.directory,prepared)}finally{let finalWal=await readWal(filePath,options.taskId);if(finalWal!==null&&finalWal.state==="COMMITTED")liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId))}})}async function abortCoderSettlement(options){let{outcome,worktree}=await withSettlementLock(options.directory,options.taskId,"coder-abort",async()=>abortDispatchedWalUnderLock(options.directory,options.taskId,options.transitionId,options.reason));if(worktree&&outcome!=="not-dispatched")try{await completeCoderSettlementCleanup(options.directory,options.taskId,options.transitionId)}catch(error49){criticalWarn(`[coder-settlement] aborted settlement worktree cleanup failed for task ${options.taskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}return outcome}async function abortDispatchedWalUnderLock(directory,taskId,transitionId,reason){let filePath=walPath(directory,taskId),wal=await readWal(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="ABORTED")return{outcome:"already-aborted",worktree:wal.worktree!==void 0};if(wal.state!=="DISPATCHED")return{outcome:"not-dispatched",worktree:!1};return await writeWal(filePath,{...wal,state:"ABORTED",abortReason:reason}),liveDispatches.delete(dispatchKey(directory,taskId,transitionId)),await appendSettlementEvent(directory,"aborted",wal,{reason}),{outcome:"aborted",worktree:wal.worktree!==void 0}}async function abortCoderSettlementIfDoomed(options){let filePath=walPath(options.directory,options.taskId),wal;try{wal=await readWal(filePath,options.taskId)}catch{return"not-doomed"}if(wal===null)return"not-doomed";if(wal.state==="ABORTED")return"already-aborted";if(wal.transitionId!==options.transitionId||wal.state!=="DISPATCHED")return"not-doomed";if(!baselineAttributionDoomed(wal.context.baseline))return"not-doomed";let outcome=await abortCoderSettlement({directory:options.directory,taskId:options.taskId,transitionId:options.transitionId,reason:doomedReason(wal.context.baseline)});return outcome==="aborted"||outcome==="already-aborted"?outcome:"not-doomed"}async function recordCoderMergeProvenance(options){await withSettlementLock(options.directory,options.taskId,"coder-merge-provenance",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="DISPATCHED"){if(!(JSON.stringify(wal.mergeProvenance)===JSON.stringify(options.provenance)&&JSON.stringify(wal.observedFiles)===JSON.stringify(options.observedFiles)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return}await writeWal(filePath,{...wal,mergeProvenance:options.provenance,observedFiles:[...options.observedFiles]})})}function probeBranchExists(directory,branchName){let result=spawnSync9(resolveGitExecutable(),["-C",directory,"show-ref","--verify","--quiet",`refs/heads/${branchName}`],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:5000,windowsHide:!0});if(result.error)throw result.error;if(result.status===0)return!0;if(result.status===1)return!1;throw Error(`CODER_SETTLEMENT_CLEANUP_UNCERTAIN: git show-ref exited with status ${String(result.status)}`)}async function cleanupRecoveredWorktree(directory,descriptor){let branchExists=()=>_internals54.branchExists(directory,descriptor.branchName),hasResidue=existsSync31(descriptor.worktreePath)||branchExists(),{awaitingMergeByCallID:awaitingMergeByCallID2,cleanupStandardWorktreeForCallId:cleanupStandardWorktreeForCallId2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation));if(standardWorktreeByCallID2.delete(descriptor.callID),hasResidue)awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});if(hasResidue)await cleanupStandardWorktreeForCallId2(descriptor.callID,"success",directory,descriptor.worktreeDir??void 0);if(existsSync31(descriptor.worktreePath)||branchExists())throw Error("CODER_SETTLEMENT_WORKTREE_CLEANUP_UNVERIFIED");let{removeWorktreeProvisioningOwner:removeWorktreeProvisioningOwner2}=await Promise.resolve().then(() => (init_worktree_provisioning_owner(),exports_worktree_provisioning_owner));if(!removeWorktreeProvisioningOwner2(directory,descriptor.callID))throw Error("CODER_SETTLEMENT_OWNER_CLEANUP_FAILED")}async function completeCoderSettlementCleanup(directory,taskId,transitionId){await withSettlementLock(directory,taskId,"coder-cleanup",async()=>{let filePath=walPath(directory,taskId),wal=await readWal(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==taskId||wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="COMMITTED"&&wal.state!=="ABORTED")throw Error("CODER_SETTLEMENT_NOT_COMMITTED");if(!wal.worktree||wal.cleanupComplete===!0)return;await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal(filePath,{...wal,cleanupComplete:!0})})}async function selfHealMissingLaneWorktree(directory,filePath,taskId,transitionId,descriptor,detail){if(existsSync31(descriptor.worktreePath))return!1;if(_internals54.branchExists(directory,descriptor.branchName))return!1;let reason=`CODER_SETTLEMENT_SELF_HEALED_MISSING_WORKTREE: ${detail}`;if((await abortDispatchedWalUnderLock(directory,taskId,transitionId,reason)).outcome==="not-dispatched")return!1;try{await cleanupRecoveredWorktree(directory,descriptor);let healedWal=await readWal(filePath,taskId);if(healedWal!==null)await writeWal(filePath,{...healedWal,cleanupComplete:!0})}catch(error49){criticalWarn(`[coder-settlement] self-healed task ${taskId} but residual cleanup failed: ${error49 instanceof Error?error49.message:String(error49)}`)}let message=`STALE_CODER_SETTLEMENT_SELF_HEALED: task ${taskId} was blocked by a coder settlement whose lane worktree "${descriptor.worktreePath}" and lane branch "${descriptor.branchName}" no longer exist. Nothing was recoverable, so the write-ahead log at "${filePath}" was marked terminal (ABORTED) and the task was unblocked. Re-dispatch the task if its work still needs doing.`;return criticalWarn(message),advisoryWarn(message),!0}async function recoverCoderSettlement(directory,taskId){return withSettlementLock(directory,taskId,"coder-recovery",async()=>{let filePath=walPath(directory,taskId),existingWal=await readWal(filePath,taskId);if(existingWal===null)return null;let wal=existingWal;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED"){if(wal.worktree&&wal.cleanupComplete!==!0)await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal(filePath,{...wal,cleanupComplete:!0});return null}let key=dispatchKey(directory,taskId,wal.transitionId);if(liveDispatches.has(key)||wal.processId!==process.pid&&isProcessAlive2(wal.processId))throw Error(`CODER_DISPATCH_IN_PROGRESS: transition ${wal.transitionId} still owns task ${taskId} (${filePath}, state ${wal.state}, pid ${wal.processId}). Wait for that dispatch to settle or run /swarm recover ${taskId} (or /swarm reset-session) to unwedge it; do not remove the WAL by hand.`);if(wal.state==="DISPATCHED"){if(wal.worktree){let worktree=wal.worktree,observed2=wal.observedFiles??scopedObservedFiles(worktree.worktreePath,wal.context);if(observed2===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: isolated task ${taskId} changes could not be attributed safely`);if(wal.mergeProvenance){let landed=await reconcileLandedMerge(directory,wal.mergeProvenance);if(landed.landed){wal={...wal,state:"PREPARED",observedFiles:observed2,accepted:observed2.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal(filePath,wal);let committed2=await commitPrepared(directory,wal);return await cleanupRecoveredWorktree(directory,worktree),await writeWal(filePath,{...wal,state:"COMMITTED",cleanupComplete:!0}),committed2}if(landed.error)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: ${landed.error}`)}let{awaitingMergeByCallID:awaitingMergeByCallID2,finishStandardWorktreeDispatch:finishStandardWorktreeDispatch2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation)),descriptor=wal.worktree,reconstructedDispatch={callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID2.delete(descriptor.callID),awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let recovered=null,mergeResult=await finishStandardWorktreeDispatch2(directory,reconstructedDispatch,void 0,descriptor.callID,{operationId:wal.transitionId,...wal.mergeProvenance?{resume:wal.mergeProvenance}:{},onBeforeMerge:async(provenance)=>{wal={...wal,mergeProvenance:provenance,observedFiles:observed2},await writeWal(filePath,wal)},onMerged:async()=>{wal={...wal,state:"PREPARED",accepted:observed2.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal(filePath,wal),recovered=await commitPrepared(directory,wal)}});if(mergeResult.outcome!=="merged"||recovered===null){if(mergeResult.outcome==="failed"&&mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE&&await selfHealMissingLaneWorktree(directory,filePath,taskId,wal.transitionId,descriptor,mergeResult.message))return null;throw Error(`CODER_SETTLEMENT_MERGE_RECOVERY_REQUIRED: ${mergeResult.outcome==="failed"?mergeResult.message:mergeResult.outcome}`)}await cleanupRecoveredWorktree(directory,descriptor);let committedWal=await readWal(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal(filePath,{...committedWal,cleanupComplete:!0}),recovered}let rawObserved=changedFilesSinceSnapshot(directory,wal.context.baseline),observed;if(rawObserved===null){if(baselineAttributionDoomed(wal.context.baseline)){let aborted2=await abortDispatchedWalUnderLock(directory,taskId,wal.transitionId,doomedReason(wal.context.baseline));if(aborted2.outcome==="aborted"||aborted2.outcome==="already-aborted")return null}observed=null}else if(wal.context.declaredFiles===null)observed=[];else observed=rawObserved.filter((filePath2)=>isPathWithinDeclaredScope(filePath2,wal.context.declaredFiles??[],directory));if(observed===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: task ${taskId} workspace changes could not be attributed safely`);wal={...wal,state:"PREPARED",accepted:observed.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed)},await writeWal(filePath,wal)}let committed=await commitPrepared(directory,wal);if(wal.worktree){await cleanupRecoveredWorktree(directory,wal.worktree);let committedWal=await readWal(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");await writeWal(filePath,{...committedWal,cleanupComplete:!0})}return committed})}function releaseCoderDispatchOwnership(directory,taskId,transitionId){liveDispatches.delete(dispatchKey(directory,taskId,transitionId))}async function assertNoUnsettledCoderDispatch(directory,taskId){let filePath=walPath(directory,taskId),wal=await readWal(filePath,taskId);if(wal===null)return;if(wal.state==="DISPATCHED"||wal.state==="PREPARED")throw Error(`CODER_SETTLEMENT_RECOVERY_REQUIRED: transition ${wal.transitionId} must settle before task ${taskId} can change plan status (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry.`)}async function listCoderSettlementWalStates(directory){let entries;try{let dirPath=validateSwarmPath(directory,"coder-settlements");entries=await readdir5(dirPath)}catch{return{states:[],truncated:!1}}let matching=entries.filter((entry)=>SETTLEMENT_WAL_FILE_PATTERN.test(entry)),states=[];for(let entry of matching.sort().slice(0,MAX_SETTLEMENT_WAL_SCAN)){let taskId=entry.slice(0,-5);try{let wal=await readWal(walPath(directory,taskId),taskId);if(wal===null)continue;states.push({taskId,state:wal.state,transitionId:wal.transitionId,processId:wal.processId,recordedAt:wal.recordedAt,ownedInProcess:liveDispatches.has(dispatchKey(directory,taskId,wal.transitionId)),ownedByLiveForeignPid:wal.processId!==process.pid&&isProcessAlive2(wal.processId)})}catch{states.push({taskId,state:"unreadable",ownedInProcess:!1,ownedByLiveForeignPid:!1})}}return{states,truncated:matching.length>MAX_SETTLEMENT_WAL_SCAN}}async function recoverStaleCoderSettlements(directory,options){let{states:listed,truncated}=await listCoderSettlementWalStates(directory),filter=options?.taskIds?new Set(options.taskIds):void 0,results=[];for(let entry of listed){if(filter&&!filter.has(entry.taskId))continue;if(entry.state==="unreadable"){results.push({taskId:entry.taskId,outcome:"unreadable_wal"});continue}if(entry.state==="ABORTED"||entry.state==="COMMITTED"){try{await _internals54.recoverCoderSettlement(directory,entry.taskId),results.push({taskId:entry.taskId,outcome:"already_terminal",state:entry.state})}catch(error49){results.push({taskId:entry.taskId,outcome:"error",message:error49 instanceof Error?error49.message:String(error49)})}continue}if(entry.ownedInProcess&&options?.force!==!0){results.push({taskId:entry.taskId,outcome:"owned_in_process",transitionId:entry.transitionId??""});continue}if(entry.ownedByLiveForeignPid){results.push({taskId:entry.taskId,outcome:"owned_by_live_foreign_pid",processId:entry.processId??-1});continue}let forced=entry.ownedInProcess&&options?.force===!0;if(forced&&entry.transitionId)releaseCoderDispatchOwnership(directory,entry.taskId,entry.transitionId),await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId,actor:"swarm-recovery"},{forced:!0,stage:"ownership-release"});try{let recovered=await _internals54.recoverCoderSettlement(directory,entry.taskId);if(recovered===null){let current=null;try{current=await readWal(walPath(directory,entry.taskId),entry.taskId)}catch{current=null}if(current&&(current.state==="COMMITTED"||current.state==="ABORTED")){results.push({taskId:entry.taskId,outcome:"already_terminal",state:current.state});continue}results.push({taskId:entry.taskId,outcome:"error",message:"settlement WAL disappeared during recovery"});continue}await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,accepted:recovered.accepted}),results.push({taskId:entry.taskId,outcome:"recovered",accepted:recovered.accepted,forced})}catch(error49){let message=error49 instanceof Error?error49.message:String(error49);await appendSettlementEvent(directory,"recovery-failed",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,error:message}),results.push({taskId:entry.taskId,outcome:"error",message})}}return{results,truncated}}var LIVE_DISPATCHES_SYMBOL,globalRegistry2,liveDispatches,runtimeId,MAX_LIVE_DISPATCHES=512,MAX_SETTLEMENT_WAL_SCAN=200,SETTLEMENT_WAL_FILE_PATTERN,_internals54;var init_coder_settlement=__esm(()=>{init_workspace_snapshot();init_gate_evidence();init_gate_evidence_classification();init_utils2();init_file_locks();init_path_identity();init_warning_buffer();init_git_executable();init_logger();init_merge();init_workflow_wal_file();LIVE_DISPATCHES_SYMBOL=Symbol.for("opencode-swarm.workflow.coder-settlement.live-dispatches"),globalRegistry2=globalThis;if(!globalRegistry2[LIVE_DISPATCHES_SYMBOL])globalRegistry2[LIVE_DISPATCHES_SYMBOL]=new Set;liveDispatches=globalRegistry2[LIVE_DISPATCHES_SYMBOL],runtimeId=randomUUID11();SETTLEMENT_WAL_FILE_PATTERN=/^[\w.\-:]+\.json$/;_internals54={liveDispatches,branchExists:probeBranchExists,recoverCoderSettlement}});import{appendFile as appendFile9,readFile as readFile17}from"node:fs/promises";async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath2=validateSwarmPath(directory,`task-repairs/${taskId}.json`),eventsPath=validateSwarmPath(directory,"events.jsonl"),wal=await readWal2(walPath2,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,eventsPath,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal2(walPath2,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath2=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal2(walPath2,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,validateSwarmPath(directory,"events.jsonl"),observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal2(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function readText(filePath){try{return await readFile17(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeWal2(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}function parseAuditEventLine(line){try{return JSON.parse(line)}catch{return null}}function findRepairEvent(content,taskId,transitionId){if(!content)return!1;let transitionNeedle=JSON.stringify(transitionId).slice(1,-1),taskNeedle=JSON.stringify(taskId).slice(1,-1);if(!content.includes(transitionNeedle)||!content.includes(taskNeedle))return!1;for(let line of content.split(`
655
655
  `)){if(!line.trim())continue;let event=parseAuditEventLine(line);if(!event)continue;if(event.type==="task_workflow_repaired"&&event.taskId===taskId&&event.transitionId===transitionId)return!0}return!1}async function ensureAuditEvent(directory,eventsPath,wal){if(findRepairEvent(await readText(eventsPath),wal.taskId,wal.transitionId))return;let lock=await tryAcquireLock(directory,"events.jsonl","task-repair-audit",`task-repair:${wal.taskId}:${wal.transitionId}`);if(!lock.acquired)throw Error("TASK_REPAIR_AUDIT_LOCKED");try{let existing=await readText(eventsPath);if(findRepairEvent(existing,wal.taskId,wal.transitionId))return;await appendFile9(eventsPath,`${JSON.stringify({type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation})}
656
656
  `,"utf-8");let verified=await readText(eventsPath);if(!findRepairEvent(verified,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}function workflowMatchesCommittedRepair(evidence2,wal){let snapshot=getTaskWorkflowSnapshot(evidence2);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath2=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`),eventsPath=validateSwarmPath(options.directory,"events.jsonl");return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence2=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence2),existingWal=await readWal2(walPath2,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath2}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence2,existingWal))return await ensureAuditEvent(options.directory,eventsPath,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence2,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal2(walPath2,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence2=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence2),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal2(walPath2,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,eventsPath,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence2,wal){let workflow=getTaskWorkflowSnapshot(evidence2);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath2){try{return await _internals55.applyTerminalEvidence(transaction,wal)}catch(error49){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath2} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error49 instanceof Error?error49.message:String(error49)}`,{cause:error49})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath2=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath2,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath2,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath2} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence2=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence2),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence2,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal3(walPath2,{...wal,state:"ABORTED"}),null;if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence2:await applyTerminalEvidenceOrExplain(transaction,wal,walPath2);return await writeWal3(walPath2,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath2=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath2,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath2=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence2=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence2);await options.validateEvidence?.(evidence2);let terminal=options.resolveTerminal?.(evidence2)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath2,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath2}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath2} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&evidenceMatchesTerminal(evidence2,existingWal))return{plan:options.currentPlan,evidence:evidence2,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence2||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath2}); found ${evidence2?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence:evidence2,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath2}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal3(walPath2,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath2);return await writeWal3(walPath2,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal3=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals55;var init_task_terminal=__esm(()=>{init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals55={applyTerminalEvidence}});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win327){return win327===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state.prefix="./";return output};exports.wrapOutput=(input,state={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path64,{windows}={})=>{let segs=path64.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state.maxDepth=0,!isPathSeparator(code))tokens.push(token);state.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state.maxDepth+=tokens[tokens.length-1].depth}state.slashes=slashes,state.parts=parts}return state};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants4=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants4,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants4.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse5=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants4.globChars(opts.windows),EXTGLOB_CHARS=constants4.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state.index===len-1,peek=state.peek=(n=1)=>input[state.index+n],advance=state.advance=()=>input[++state.index]||"",remaining=()=>input.slice(state.index+1),consume=(value2="",num=0)=>{state.consumed+=value2,state.index+=num},append=(token)=>{state.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state.start++,count++;if(count%2===0)return!1;return state.negated=!0,state.start++,!0},increment=(type)=>{state[type]++,stack.push(type)},decrement=(type)=>{state[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state.output=state.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state.parens,token.output=state.output,token.startIndex=state.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal2=input.slice(token.startIndex,state.index+1),body=input.slice(token.startIndex+2,state.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open4=tokens[token.tokensIndex];open4.type="text",open4.value=literal2,open4.output=safeOutput||utils.escapeRegex(literal2);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state.output=token.output+open4.output,state.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse5(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc2,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc2)return esc2+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc2)return esc2+first+(rest?star:"");return star}return esc2?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state.output=input,state;return state.output=utils.wrapOutput(output,state,options),state}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state.brackets===0){push({type:"text",value});continue}}if(state.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix9=POSIX_REGEX_SOURCE[rest2];if(posix9){if(prev.value=pre+posix9,state.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state.quotes=state.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state.output=state.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open4={type:"brace",value,output:"(",outputIndex:state.output.length,tokensIndex:state.tokens.length};braces.push(open4),push(open4);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state.output.slice(0,brace.outputIndex),toks=state.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state.output=out;for(let t of toks)state.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state.index===state.start+1){state.start=state.index+1,state.consumed="",state.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state.braces+state.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state.backtrack=!0,state.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state.output=prev.output,state.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state.output=state.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state.globstar=!0,state.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state.output=state.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state.output+=prior.output+prev.output,state.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state.output=prev.output,state.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state.output=state.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state.output+=prev.output,state.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state.index===state.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state.output+=nodot,prev.output+=nodot;if(peek()!=="*")state.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state.output=utils.escapeLast(state.output,"["),decrement("brackets")}while(state.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state.output=utils.escapeLast(state.output,"("),decrement("parens")}while(state.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state.output=utils.escapeLast(state.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state.backtrack===!0){state.output="";for(let token of state.tokens)if(state.output+=token.output!=null?token.output:token.value,token.suffix)state.output+=token.suffix}return state};parse5.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants4.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse5});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse5=require_parse(),utils=require_utils(),constants4=require_constants(),isObject2=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state2=isMatch(str);if(state2)return state2}return!1}}let isState=isObject2(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix9=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix9}),result={glob,state,regex,posix:posix9,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix9}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix9?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix9);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse5(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state.output})${append}`;if(state&&state.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse5.fastpaths(input,options);if(!parsed.output)parsed=parse5(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants4;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count=1){let requested=Number(count);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import*as fsSync5 from"node:fs";import*as path64 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error49){return log("[Guardrails] hashArgs failed",{error:error49 instanceof Error?error49.message:String(error49)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached2=pathNormalizationCache.get(cacheKey);if(cached2!==void 0)return cached2;try{let absolutePath=path64.isAbsolute(filePath)?filePath:path64.resolve(cwd,filePath),normalized=fsSync5.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path64.isAbsolute(filePath)?filePath:path64.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached2=globMatcherCache.get(cacheKey);if(cached2!==void 0)return cached2;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path64.resolve(cwd),normalizedTarget=path64.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path64.relative(normalizedCwd,current);if(rel===""||rel===".."||rel.startsWith(`..${path64.sep}`)||path64.isAbsolute(rel))break;ancestors.push(current);let parent=path64.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat10=null;try{stat10=fsSync5.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat10.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink/junction — writing through a symlink or junction could redirect the write outside the working directory`}return null}function matchesAuthorityDenyPrefix(candidate,prefix,cwd,flavor=getPathFlavor()){let pathImpl=flavor==="win32"?path64.win32:path64.posix,normalizeInput=(value)=>flavor==="win32"?value.replace(/\//g,"\\"):value,normalizedPrefixInput=normalizeInput(prefix),requiresComponentBoundary=normalizedPrefixInput.endsWith(pathImpl.sep),root=pathImpl.resolve(normalizeInput(cwd)),target=pathImpl.resolve(root,normalizeInput(candidate)),denied=pathImpl.resolve(root,normalizedPrefixInput);if(!isPathIdentityWithin(target,root,flavor)||!isPathIdentityWithin(denied,root,flavor))return!1;let identity=(value)=>flavor==="win32"?value.toLowerCase():value,targetIdentity=identity(target),deniedIdentity=identity(denied);return requiresComponentBoundary?targetIdentity===deniedIdentity||targetIdentity.startsWith(`${deniedIdentity}${pathImpl.sep}`):targetIdentity.startsWith(deniedIdentity)}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path64){let flavor=pathLib===path64.win32||pathLib.parse("C:\\probe").root!==""?"win32":"posix";return isOnDifferentPathRoot(targetAbsolute,cwdAbsolute,flavor)}function denyAuthority(agent,normalizedPath2,input){let safeAgent=sanitizeDiagnosticText(agent,96),safePath=sanitizeDiagnosticText(normalizedPath2,320),safeDetail=sanitizeDiagnosticText(input.detail,640);return{allowed:!1,code:input.code,layer:input.layer,rule:sanitizeDiagnosticText(input.rule,128),path:safePath,agent:safeAgent,reason:sanitizeDiagnosticText(`${input.code}: Path blocked: ${safeDetail} [agent=${safeAgent}; path=${safePath}]`,1024),recovery:input.recovery,zone:input.zone}}function formatAllowedHints(rules){let fmt=(items)=>{if(!items||items.length===0)return"(none)";if(items.length<=MAX_ALLOWED_HINT_ENTRIES)return items.join(", ");let omitted=items.length-MAX_ALLOWED_HINT_ENTRIES;return`${items.slice(0,MAX_ALLOWED_HINT_ENTRIES).join(", ")}, … (+${omitted} more)`},parts=[];if(rules.allowedExact&&rules.allowedExact.length>0)parts.push(`Allowed exact paths: ${fmt(rules.allowedExact)}`);if(parts.push(`Allowed prefixes: ${fmt(rules.allowedPrefix)}`),parts.push(`Allowed globs: ${fmt(rules.allowedGlobs)}`),rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0)parts.push(`Allowed case-sensitive globs: ${fmt(rules.allowedCaseSensitiveGlobs)}`);return parts.push("Block rules (blocked zones/prefixes/globs/exact) and universal deny paths still apply."),parts.join(" ")}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options={}){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),unsafePathReason=unsafePathTextReason(filePath);if(unsafePathReason)return denyAuthority(agentName,filePath,{code:"AUTHORITY_INVALID_PATH",layer:"path-validation",rule:"safe-path-text",detail:unsafePathReason});let normalizedPath2,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path64.resolve(dir,normalizedWithSymlinks),normalizedPath2=path64.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path64.resolve(dir,filePath),normalizedPath2=path64.relative(dir,resolvedTarget).replace(/\\/g,"/")}if(isOnDifferentFilesystemRoot(resolvedTarget,dir))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"same-filesystem-root",detail:"target is on a different drive or filesystem root"});if(normalizedPath2===".."||normalizedPath2.startsWith("../"))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:"target resolves outside the working directory"});let rules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent];if(!rules)return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_UNKNOWN_AGENT",layer:"role-capability",rule:"known-agent-role",detail:"Unknown agent: no authority classification exists"});let flavor=getPathFlavor(),matchesPathPrefix=(candidate,prefix)=>isPathIdentityWithin(path64.resolve(dir,candidate),path64.resolve(dir,prefix),flavor),matchesGlob=(glob)=>getGlobMatcher(glob)(normalizedPath2);for(let prefix of options.universalDenyPrefixes??[])if(matchesAuthorityDenyPrefix(normalizedPath2,prefix,dir,flavor))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_UNIVERSAL_DENY",layer:"universal-deny",rule:`universal:${prefix}`,detail:`target is under universal deny prefix ${prefix}`});let isCoderAgent=normalizedAgent==="coder"||strippedAgent==="coder";if(isCoderAgent&&matchesPathPrefix(normalizedPath2,".swarm"))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"coder-swarm-state-protection",detail:"coder writes to .swarm are always protected"});if(Object.hasOwn(AUTHORITY_ROLE_CAPABILITIES,strippedAgent)){let matchedVerifier=[...BUILT_IN_VERIFIER_CONFIG_GLOBS,...options.verifierConfigPaths??[]].find(matchesGlob);if(matchedVerifier)return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_VERIFIER_CONFIG",layer:"protected-path",rule:`verifier-config:${matchedVerifier}`,detail:`Path blocked (glob ${matchedVerifier}): swarm roles cannot write verifier-owned configuration in the config zone`})}let canonicalCapability=AUTHORITY_ROLE_CAPABILITIES[strippedAgent];if(canonicalCapability==="read-only"||canonicalCapability==="dedicated-tool-only")return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:`role-capability:${canonicalCapability}`,detail:canonicalCapability==="dedicated-tool-only"?"role may mutate state only through dedicated tools":"agent role is read-only"});if(rules.readOnly)return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:"role-policy:read-only",detail:"agent role is read-only"});if(isCoderAgent&&options.declaredScope!=null&&options.declaredScope.length>0&&isPathWithinDeclaredScope(normalizedPath2,options.declaredScope,dir))return{allowed:!0,layer:"declared-scope",path:sanitizeDiagnosticText(normalizedPath2,320),agent:sanitizeDiagnosticText(agentName,96)};if(options.authorityEnabled===!1)return{allowed:!0,layer:"role-policy",path:sanitizeDiagnosticText(normalizedPath2,320),agent:sanitizeDiagnosticText(agentName,96)};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(pathIdentitiesEqual(normalizedPath2,blocked,flavor))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedExact:${blocked}`,detail:`path is blocked by exact role policy ${blocked}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(matchesGlob(glob))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedGlob:${glob}`,detail:`Path blocked (glob ${glob}) by role policy`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>pathIdentitiesEqual(normalizedPath2,allowed,flavor)))return{allowed:!0,layer:"role-policy",path:normalizedPath2,agent:agentName}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath2);if(rules.blockedZones.includes(zone))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedZone:${zone}`,detail:`path is in ${zone} zone`,recovery:isCoderAgent?"declare_scope":void 0,zone})}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some(matchesGlob))return{allowed:!0,layer:"role-policy",path:normalizedPath2,agent:agentName}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath2)}))return{allowed:!0,layer:"role-policy",path:normalizedPath2,agent:agentName}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(matchesPathPrefix(normalizedPath2,prefix))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedPrefix:${prefix}`,detail:`path is under blocked role prefix ${prefix}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>matchesPathPrefix(normalizedPath2,prefix)))return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix",detail:`path is not in allowed list for this role. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0})}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return denyAuthority(agentName,normalizedPath2,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix:empty",detail:`path is not in allowed list because the role allowlist is empty. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0});return{allowed:!0,layer:"role-policy",path:normalizedPath2,agent:agentName}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options={}){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),{...options,authorityEnabled:authorityConfig?.enabled??options.authorityEnabled,universalDenyPrefixes:authorityConfig?.universal_deny_prefixes??options.universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths??options.verifierConfigPaths})}var import_picomatch,pathNormalizationCache,globMatcherCache,AUTHORITY_ROLE_CAPABILITIES,NON_WRITING_SWARM_RULES,DEFAULT_AGENT_AUTHORITY_RULES,BUILT_IN_VERIFIER_CONFIG_GLOBS,MAX_ALLOWED_HINT_ENTRIES=20;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_path_identity();init_utils();init_arg_hash();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200});AUTHORITY_ROLE_CAPABILITIES={architect:"direct-write",coder:"direct-write",reviewer:"direct-write",critic:"direct-write",critic_oversight:"dedicated-tool-only",critic_finding_validator:"dedicated-tool-only",explorer:"read-only",sme:"read-only",researcher:"read-only",test_engineer:"direct-write",docs:"direct-write",docs_design:"direct-write",designer:"direct-write",critic_sounding_board:"read-only",critic_drift_verifier:"read-only",critic_hallucination_verifier:"read-only",critic_architecture_supervisor:"read-only",curator_init:"dedicated-tool-only",curator_phase:"dedicated-tool-only",curator_postmortem:"dedicated-tool-only",curator_consolidation:"dedicated-tool-only",council_generalist:"read-only",council_skeptic:"read-only",council_domain_expert:"read-only",skill_improver:"dedicated-tool-only",spec_writer:"dedicated-tool-only"},NON_WRITING_SWARM_RULES=Object.fromEntries(Object.entries(AUTHORITY_ROLE_CAPABILITIES).filter(([,capability])=>capability==="read-only"||capability==="dedicated-tool-only").map(([agent])=>[agent,{readOnly:!0}])),DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},...NON_WRITING_SWARM_RULES,architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}};BUILT_IN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.json","**/biome.jsonc","**/tsconfig*.json","**/.secretscanignore","**/.golangci*"]});import{createHash as createHash24}from"node:crypto";import*as fs42 from"node:fs";import*as path65 from"node:path";function fingerprint(filePath,budget){try{let stat10=fs42.lstatSync(filePath);if(stat10.isSymbolicLink())return{kind:"unsafe"};if(!stat10.isFile())return{kind:"unsafe"};if(stat10.size>MAX_HASH_BYTES||stat10.size>budget.remaining)return{kind:"unsafe"};budget.remaining-=stat10.size;let result={kind:"file",size:stat10.size,mtimeMs:stat10.mtimeMs};return result.hash=createHash24("sha256").update(fs42.readFileSync(filePath)).digest("hex"),result}catch(error49){return error49.code==="ENOENT"?{kind:"missing"}:{kind:"unsafe"}}}function changed(before,after){if(before.kind==="unsafe"||after.kind==="unsafe")return!1;if(before.kind!==after.kind)return!0;if(before.kind==="missing")return!1;if(before.hash!==void 0||after.hash!==void 0)return before.hash!==after.hash;return before.size!==after.size||before.mtimeMs!==after.mtimeMs}function effectFor(tool,args2,targetCount){if(targetCount!==1||!args2||typeof args2!=="object")return{};let record2=args2;if(tool==="write"||tool==="create_file"){for(let key of["content","file_text","text"])if(typeof record2[key]==="string")return{exactContent:record2[key]}}if(tool==="edit"||tool==="replace"){for(let key of["newString","new_string","replacement"])if(typeof record2[key]==="string"&&record2[key]!=="")return{containsText:record2[key]}}return{}}function matchesExpected(filePath,expected,budget){if(expected.exactContent===void 0&&expected.containsText===void 0)return!0;try{let stat10=fs42.statSync(filePath);if(!stat10.isFile()||stat10.size>MAX_HASH_BYTES||stat10.size>budget.remaining)return!1;budget.remaining-=stat10.size;let content=fs42.readFileSync(filePath,"utf8");if(expected.exactContent!==void 0)return content===expected.exactContent;return content.includes(expected.containsText??"")}catch{return!1}}function numericExitCodes(metadata){if(!metadata||typeof metadata!=="object")return[];let record2=metadata;return["exitCode","exit_code","exit"].map((key)=>record2[key]).filter((value)=>typeof value==="number")}function directSuccess(output){let text=typeof output.output==="string"?output.output.trim():"",metadata=output.metadata&&typeof output.metadata==="object"?output.metadata:null;if(numericExitCodes(output.metadata).some((code)=>code!==0))return!1;if(metadata?.success===!0)return!0;if(metadata&&typeof metadata.status==="string"&&["success","completed","ok","applied"].includes(metadata.status.toLowerCase()))return!0;try{let parsed=JSON.parse(text);if(parsed.success===!0&&parsed.dryRun!==!0)return!0}catch{}return/^(?:Wrote file successfully\.|Edit applied successfully\.|Done!|Patch applied successfully\.|File (?:created|updated) successfully\.)/i.test(text)}function successful(tool,output){if(tool==="bash"||tool==="shell"){let exitCodes=numericExitCodes(output.metadata);return exitCodes.length>0&&exitCodes.every((code)=>code===0)}return directSuccess(output)}function createScopeLeaseRenewalTracker(refresh=refreshScopeBindingLease,now=Date.now){let candidates=new Map,candidateKey=(sessionID,callID)=>`${sessionID}\x00${callID}`,sweep=()=>{let cutoff=now()-CANDIDATE_TTL_MS;for(let[key,candidate]of candidates)if(candidate.createdAt<cutoff)candidates.delete(key);while(candidates.size>=MAX_CANDIDATES2){let oldest=candidates.keys().next().value;if(oldest===void 0)break;candidates.delete(oldest)}};return{remember(input){sweep();let binding=input.binding;if(binding.activation!=="active"||binding.lifecycleState!=="live"||binding.expiresAt<=now()||binding.ownerSessionId!==input.sessionID||input.targets.length===0||input.targets.length>MAX_TARGETS)return;let uniqueTargets=[...new Set(input.targets.map((target)=>path65.resolve(target)))];if(uniqueTargets.length===0||uniqueTargets.length>MAX_TARGETS)return;let expected=effectFor(input.tool,input.args,uniqueTargets.length),hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},targets=uniqueTargets.map((target)=>({path:target,before:fingerprint(target,hashBudget),expected}));if(targets.some((target)=>target.before.kind==="unsafe"))return;candidates.set(candidateKey(input.sessionID,input.callID),{createdAt:now(),callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:input.directory,bindingId:binding.bindingId,generationId:binding.generationId,expectedRevision:binding.revision,taskId:binding.taskId,targets})},async consume(input){let key=candidateKey(input.sessionID,input.callID),candidate=candidates.get(key);if(candidates.delete(key),!candidate||candidate.sessionID!==input.sessionID||candidate.tool!==input.tool||now()-candidate.createdAt>CANDIDATE_TTL_MS||!input.output||!successful(candidate.tool,input.output))return null;let hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},contentBudget={remaining:MAX_AGGREGATE_HASH_BYTES};for(let target of candidate.targets){let after=fingerprint(target.path,hashBudget);if(!changed(target.before,after)||!matchesExpected(target.path,target.expected,contentBudget))return null}return refresh({directory:candidate.directory,bindingId:candidate.bindingId,generationId:candidate.generationId,expectedRevision:candidate.expectedRevision,activeSessionId:candidate.sessionID,taskId:candidate.taskId})}}}var MAX_CANDIDATES2=256,MAX_TARGETS=256,MAX_HASH_BYTES=4194304,MAX_AGGREGATE_HASH_BYTES=8388608,CANDIDATE_TTL_MS=600000;var init_scope_lease_renewal=__esm(()=>{init_scope_persistence()});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&&QUOTA_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;let rejections=input.rejectionCount??0,resolutionPath,taskId=input.taskId??"unknown",conflictDedupeKey=`conflict:${taskId}:${rejections}`;if(rejections>=3)resolutionPath="soundingboard",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT ESCALATION (rejections=${rejections}): ${input.sourceAgent} vs ${input.targetAgent} on task ${taskId}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`,{dedupeKey:conflictDedupeKey});else resolutionPath="self_resolve",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT DETECTED (rejections=${rejections}): ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${taskId}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`,{dedupeKey:conflictDedupeKey});let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state2();init_telemetry()});function extractCurrentPhase(planContent){if(!planContent)return null;let lines=planContent.split(`