opencode-swarm 7.200.7 → 7.200.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{attest-task-rp4xn5wh.js → attest-task-79gp34gf.js} +25 -25
- package/dist/cli/{auto-checkpoint-a6x7bw5k.js → auto-checkpoint-kt9mr7ma.js} +4 -4
- package/dist/cli/{checkpoint-kpgmse11.js → checkpoint-e7t1zbz2.js} +8 -8
- package/dist/cli/{coder-settlement-f54sfmaj.js → coder-settlement-rehndcey.js} +3 -3
- package/dist/cli/{config-doctor-hpakt9zz.js → config-doctor-hcemxnra.js} +7 -7
- package/dist/cli/{core-m2x9w49f.js → core-k8mvhsty.js} +1 -1
- package/dist/cli/{curator-ghjq55v7.js → curator-ayenbz0y.js} +25 -25
- package/dist/cli/{curator-drift-hxfzkkhg.js → curator-drift-fwzrv9tw.js} +5 -5
- package/dist/cli/{curator-llm-factory-b3hk73vd.js → curator-llm-factory-kja1c81k.js} +25 -25
- package/dist/cli/{doctor-knowledge-receipt-phase-id-wk9vry5a.js → doctor-knowledge-receipt-phase-id-jdy6651j.js} +4 -4
- package/dist/cli/{evidence-summary-service-gf50zpwx.js → evidence-summary-service-4jm1hd1r.js} +9 -9
- package/dist/cli/{gate-evidence-7my0f82h.js → gate-evidence-anef2bqv.js} +2 -2
- package/dist/cli/{guardrail-explain-e1ck0csp.js → guardrail-explain-agaet7r5.js} +26 -26
- package/dist/cli/{guardrail-log-hkkkwmj1.js → guardrail-log-pv3bq9hj.js} +3 -3
- package/dist/cli/{guardrail-reset-wwnbcexb.js → guardrail-reset-k8b9yrec.js} +25 -25
- package/dist/cli/{hive-promoter-4nzbfwcd.js → hive-promoter-zqscx6pb.js} +25 -25
- package/dist/cli/{index-h9hgxbsw.js → index-02vgzrpg.js} +1 -1
- package/dist/cli/{index-q8fy8cxa.js → index-08jd4gz2.js} +3 -3
- package/dist/cli/{index-k69vjyfm.js → index-2c4hjeea.js} +1 -1
- package/dist/cli/{index-vhkk8grb.js → index-2k5348b6.js} +27 -27
- package/dist/cli/{index-39pge60a.js → index-4fr3r8k5.js} +1 -1
- package/dist/cli/{index-wkz6w3yy.js → index-4tpzdegx.js} +3 -3
- package/dist/cli/{index-rjtf507t.js → index-4ya4krts.js} +1 -1
- package/dist/cli/{index-p61vaebj.js → index-6901y99d.js} +2 -2
- package/dist/cli/{index-6phyfsvn.js → index-6q2s7r67.js} +3 -3
- package/dist/cli/{index-vsqc38a0.js → index-7c4gckzq.js} +1 -1
- package/dist/cli/{index-bgcanr26.js → index-94s844qn.js} +1 -1
- package/dist/cli/{index-g5hghxgw.js → index-9jty56xr.js} +1 -1
- package/dist/cli/{index-kmnyh4r1.js → index-9ws7m02r.js} +2 -2
- package/dist/cli/{index-87kk5dqm.js → index-casbh4y7.js} +75 -62
- package/dist/cli/{index-0fbtnkyw.js → index-czsx86m5.js} +25 -25
- package/dist/cli/{index-mkkwhrtn.js → index-f8nb470m.js} +2 -2
- package/dist/cli/{index-c0dbzf9v.js → index-hh87yny7.js} +3 -3
- package/dist/cli/{index-6e75mvmn.js → index-hhq5f82z.js} +1 -1
- package/dist/cli/{index-ramxwbtt.js → index-hzy6n59p.js} +6 -6
- package/dist/cli/{index-223g5dj9.js → index-kxp43wbw.js} +5 -5
- package/dist/cli/{index-8k6jd7a9.js → index-qawbxp81.js} +3 -3
- package/dist/cli/{index-jfkzhyqs.js → index-qw2wfz92.js} +3 -3
- package/dist/cli/{index-f4tht67a.js → index-rdyfrdcp.js} +1 -1
- package/dist/cli/{index-y76sev7j.js → index-ss8nfrbb.js} +2 -2
- package/dist/cli/{index-mnpcwcqf.js → index-tvdn9gr0.js} +2 -2
- package/dist/cli/{index-f3ed5wde.js → index-x3rxa3sh.js} +1 -1
- package/dist/cli/{index-5djd4vrn.js → index-xh50xsgf.js} +1 -1
- package/dist/cli/{index-qc3qqknb.js → index-xhxbv7mz.js} +4 -4
- package/dist/cli/{index-7r9yg7h1.js → index-y16v2q1x.js} +1 -1
- package/dist/cli/{index-sy15gtjr.js → index-zy943kpp.js} +3 -3
- package/dist/cli/index.js +26 -26
- package/dist/cli/{knowledge-escalator-cx03qhmc.js → knowledge-escalator-m4b4q218.js} +7 -7
- package/dist/cli/{knowledge-events-cfdd3syn.js → knowledge-events-wwg0cc7m.js} +5 -5
- package/dist/cli/{knowledge-store-fgwc40g2.js → knowledge-store-07fwtdzy.js} +1 -1
- package/dist/cli/{knowledge-validator-hvah3jxx.js → knowledge-validator-8492vmn3.js} +2 -2
- package/dist/cli/{mcp-1crekab3.js → mcp-b1wyrebx.js} +1 -1
- package/dist/cli/{model-preflight-knjgtnwb.js → model-preflight-315wr8nt.js} +25 -25
- package/dist/cli/{pending-delegations-3a2tgmgq.js → pending-delegations-tpa7wpny.js} +2 -2
- package/dist/cli/{pr-subscriptions-8yprtmt7.js → pr-subscriptions-ev2bkbrz.js} +1 -1
- package/dist/cli/{pr-workflow-gate-fcpvkwg8.js → pr-workflow-gate-3cg64r61.js} +25 -25
- package/dist/cli/{scan-cursor-a776c7b6.js → scan-cursor-3pfx6mbh.js} +2 -2
- package/dist/cli/{schema-evj1vbxz.js → schema-km0fywpx.js} +1 -1
- package/dist/cli/{scope-persistence-s1e120ba.js → scope-persistence-xctbs0aj.js} +5 -5
- package/dist/cli/{server-exd3q95h.js → server-d1mcxa8s.js} +25 -25
- package/dist/cli/{skill-generator-6r8pxx5z.js → skill-generator-tce30v8g.js} +8 -8
- package/dist/cli/{snapshot-coordination-init-z8b9twvf.js → snapshot-coordination-init-t7vfaqhw.js} +25 -25
- package/dist/cli/{speckit-checkoff-hhbcq87w.js → speckit-checkoff-tcn1dqt0.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-waf8d48d.js → worktree-collision-ownership-5jb0p5aa.js} +2 -2
- package/dist/cli/{worktree-isolation-ea4qe5f5.js → worktree-isolation-cxg8fgba.js} +25 -25
- package/dist/full-auto/policy.d.ts +19 -0
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.200.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",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run; reviewer verdicts marked `UNVERIFIED` persist to the findings ledger as `PENDING` records routed back to the reviewer — do not resubmit a row whose verdict is already recorded",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},prepare_pr_feedback_commit_message:{description:"author a PR_FEEDBACK commit message that cannot go inline (e.g. a Co-Authored-By trailer) into a file OUTSIDE the repository; returns the path for git commit -F",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,EPIC_TOOL_NAMES,EPIC_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.200.9",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run; reviewer verdicts marked `UNVERIFIED` persist to the findings ledger as `PENDING` records routed back to the reviewer — do not resubmit a row whose verdict is already recorded",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},prepare_pr_feedback_commit_message:{description:"author a PR_FEEDBACK commit message that cannot go inline (e.g. a Co-Authored-By trailer) into a file OUTSIDE the repository; returns the path for git commit -F",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,EPIC_TOOL_NAMES,EPIC_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -705,7 +705,7 @@ ${formatSwarmPlanTrailer(planKey)}`}function cacheRootTimestamp(key,value){if(ro
|
|
|
705
705
|
`)}function warnOnce(key,message){if(warnedKeys.has(key))return;if(warnedKeys.size>=MAX_WARNED_KEYS){let oldest=warnedKeys.values().next().value;if(oldest!==void 0)warnedKeys.delete(oldest)}warnedKeys.add(key),criticalWarn(message)}function decayedPriorStats(prior,settings,nowMs){return scaleEpicLearning(prior.stats,epicTimeDecayFactor(prior.updatedAt,nowMs,settings.halfLifeDays))}function loadEpicLearningView(directory,epic,settings,nowMs){if(!settings.enabled)return{source:"none",stats:emptyEpicLearning()};if(epic!==null){let posterior=readEpicPosterior(directory);if(posterior&&posterior.epicKey===epic.epicKey&&posterior.token===epic.token){let base=scaleEpicLearning(posterior.base.stats,epicTimeDecayFactor(posterior.base.updatedAt,nowMs,settings.halfLifeDays));return{source:"posterior",stats:boundEpicLearning(mergeEpicLearning(base,posterior.increments))}}}let read=readEpicPrior(directory);if(read.status==="unreadable")return warnOnce(`prior\x00${directory}`,`[epic/learning] the project prior is unreadable (${read.reason}); epics plan without learned signals until \`/swarm epic prior reset\` clears it.`),{source:"prior-unreadable",stats:emptyEpicLearning()};if(read.status==="absent")return{source:"none",stats:emptyEpicLearning()};return{source:"prior",stats:decayedPriorStats(read.prior,settings,nowMs)}}function initEpicPosterior(directory,record2,snapshot){writeEpicPosterior(directory,{epicKey:record2.epicKey,token:record2.token,priorDigest:record2.priorDigest,createdAt:record2.startedAt,lastAppliedWaveSeq:0,base:snapshot.status==="ok"?{updatedAt:snapshot.prior.updatedAt,stats:snapshot.prior.stats}:{updatedAt:record2.startedAt,stats:emptyEpicLearning()},increments:emptyEpicLearning()})}function posteriorFor(directory,record2){let existing=readEpicPosterior(directory);if(existing&&existing.epicKey===record2.epicKey&&existing.token===record2.token)return existing;let prior=readEpicPrior(directory);return{epicKey:record2.epicKey,token:record2.token,priorDigest:prior.digest,createdAt:record2.startedAt,lastAppliedWaveSeq:0,base:prior.status==="ok"?{updatedAt:prior.prior.updatedAt,stats:prior.prior.stats}:{updatedAt:record2.startedAt,stats:emptyEpicLearning()},increments:emptyEpicLearning()}}function applyClosedWavesToPosterior(directory,record2,settings){if(!settings.enabled)return{appliedWaves:[]};let posterior=posteriorFor(directory,record2),pending=record2.waves.filter((wave)=>wave.status==="closed"&&wave.seq>posterior.lastAppliedWaveSeq).map((wave)=>wave.seq).sort((a,b)=>a-b);if(pending.length===0)return{appliedWaves:[]};let applied=new Set(pending),outcomes=Object.values(record2.tasks??{}).filter((outcome)=>applied.has(outcome.waveSeq));return writeEpicPosterior(directory,{...posterior,lastAppliedWaveSeq:pending[pending.length-1],increments:boundEpicLearning(mergeEpicLearning(posterior.increments,epicLearningFromOutcomes(outcomes,{isDirectory:directoryProbe(directory),learnedThroughWaveSeq:posterior.lastAppliedWaveSeq})))}),{appliedWaves:pending}}function mergeEpicPosteriorIntoPrior(directory,record2,reportKey,settings,nowMs){let none={learnedFiles:0,learnedEdges:0,hotFiles:[]};if(!settings.enabled)return{status:"disabled",...none,detail:"learning is disabled (epic.learning.enabled: false)"};try{try{applyClosedWavesToPosterior(directory,record2,settings)}catch(error49){warn(`[epic/learning] posterior catch-up failed; merging from the epic record: ${errorText3(error49)}`)}let posterior=readEpicPosterior(directory),increments=posterior&&posterior.epicKey===record2.epicKey&&posterior.token===record2.token?posterior.increments:boundEpicLearning(epicLearningFromOutcomes(Object.values(record2.tasks??{}),{isDirectory:directoryProbe(directory)})),learnedEdges=0;for(let targets of increments.edges.values())learnedEdges+=targets.size;let learned={learnedFiles:increments.files.size,learnedEdges},read=readEpicPrior(directory);if(read.status==="unreadable")return{status:"prior-unreadable",...learned,hotFiles:[],detail:`the project prior is unreadable (${read.reason}); this epic's observations were not merged — clear it with \`/swarm epic prior reset\``};let prior=read.status==="ok"?read.prior:null;if(prior?.mergedEpics.includes(reportKey))return removePosterior(directory,record2),{status:"already-merged",...learned,hotFiles:epicHotFiles(prior.stats,settings.hotExcess).slice(0,10),detail:"already merged into the project prior"};if(isEpicLearningEmpty(increments)){if(prior)writeEpicPrior(directory,{...prior,mergedEpics:[...prior.mergedEpics,reportKey]});return removePosterior(directory,record2),{status:"nothing-to-learn",...learned,hotFiles:prior?epicHotFiles(prior.stats,settings.hotExcess).slice(0,10):[],detail:"no outcomes to learn from"}}let decayed=prior?scaleEpicLearning(decayedPriorStats(prior,settings,nowMs),settings.decayPerEpic):emptyEpicLearning(),stats2=boundEpicLearning(mergeEpicLearning(decayed,increments));return writeEpicPrior(directory,{updatedAt:new Date(nowMs).toISOString(),importedFrom:prior?.importedFrom??null,mergedEpics:[...prior?.mergedEpics??[],reportKey],stats:stats2}),removePosterior(directory,record2),{status:"merged",...learned,hotFiles:epicHotFiles(stats2,settings.hotExcess).slice(0,10),detail:"merged into the project prior"}}catch(error49){return{status:"failed",...none,detail:`merging into the project prior failed: ${errorText3(error49)}`}}}function removePosterior(directory,record2){let existing=readEpicPosterior(directory);if(existing&&existing.epicKey!==record2.epicKey)return;try{fs31.rmSync(posteriorPath(directory),{force:!0})}catch{}}function resetEpicPrior(directory,nowMs){let read=readEpicPrior(directory),nowIso2=new Date(nowMs).toISOString();try{return writeEpicPrior(directory,{updatedAt:nowIso2,importedFrom:read.status==="ok"&&read.prior.importedFrom?read.prior.importedFrom:{source:"reset",at:nowIso2,calibrationHotModules:0,divergenceRecords:0},mergedEpics:read.status==="ok"?read.prior.mergedEpics:[],stats:emptyEpicLearning()}),{status:"reset",hadPrior:read.status!=="absent"}}catch(error49){return{status:"failed",detail:errorText3(error49)}}}function readLegacyHotModules(directory){let raw=readBounded(path55.join(directory,LEGACY_CALIBRATION_RELATIVE_PATH));if(raw===null)return null;let parsed=JSON.parse(raw);if(!Array.isArray(parsed?.hotModuleAdditions))return[];return parsed.hotModuleAdditions.filter((entry)=>typeof entry==="string").slice(0,MAX_LEGACY_HOT_MODULES)}function readLegacyDivergence(directory){let filePath=path55.join(directory,LEGACY_DIVERGENCE_RELATIVE_PATH),size;try{size=fs31.statSync(filePath).size}catch(error49){if(error49?.code==="ENOENT")return null;throw error49}let text,truncated=!1;if(size>MAX_LEGACY_DIVERGENCE_BYTES){let fd=fs31.openSync(filePath,"r");try{let buffer=Buffer.alloc(MAX_LEGACY_DIVERGENCE_BYTES);fs31.readSync(fd,buffer,0,MAX_LEGACY_DIVERGENCE_BYTES,size-MAX_LEGACY_DIVERGENCE_BYTES),text=buffer.toString("utf-8"),truncated=!0}finally{fs31.closeSync(fd)}}else text=fs31.readFileSync(filePath,"utf-8");let tail=text.split(`
|
|
706
706
|
`).filter((line)=>line.trim().length>0).slice(truncated?1:0).slice(-MAX_LEGACY_DIVERGENCE_RECORDS),records=[];for(let line of tail)try{let parsed=JSON.parse(line);if(parsed&&typeof parsed==="object")records.push(parsed)}catch{}let last=new Map;records.forEach((record2,index)=>{if(typeof record2.planId==="string"&&typeof record2.taskId==="string")last.set(`${record2.planId}\x00${record2.taskId}`,index)});let strings=(value)=>Array.isArray(value)?value.filter((entry)=>typeof entry==="string"):[];return records.filter((record2,index)=>typeof record2.planId!=="string"||typeof record2.taskId!=="string"||last.get(`${record2.planId}\x00${record2.taskId}`)===index).map((record2)=>({declared:strings(record2.declaredScope),undeclared:strings(record2.undeclared)}))}function importLegacyEpicCalibrationOnce(directory,nowMs){try{let read=readEpicPrior(directory);if(read.status==="unreadable")return{status:"prior-unreadable"};if(read.status==="ok"&&read.prior.importedFrom!==null)return{status:"already-imported"};let hotModules=null;try{hotModules=readLegacyHotModules(directory)}catch(error49){warn(`[epic/learning] Epic v1 calibration.json unreadable; not imported: ${errorText3(error49)}`)}let divergence=null;try{divergence=readLegacyDivergence(directory)}catch(error49){warn(`[epic/learning] Epic v1 divergence.jsonl unreadable; not imported: ${errorText3(error49)}`)}if(hotModules===null&&divergence===null)return{status:"nothing-to-import"};let increments=epicLearningFromOutcomes((divergence??[]).map((record2,index)=>({taskId:`legacy-${index}`,phase:0,waveSeq:0,resolution:"completed",resolvedAt:"",generation:0,stageAFailures:0,stageBFailures:0,mergeFailure:null,declared:record2.declared,undeclared:record2.undeclared,attribution:"session",reopened:0,marker:null})),{isDirectory:directoryProbe(directory)}),base=read.status==="ok"?read.prior.stats:emptyEpicLearning(),stats2=mergeEpicLearning(base,increments);for(let file2 of learnablePaths(hotModules??[])){let current=stats2.files.get(file2)??{alpha:0,beta:0};stats2.files.set(file2,{alpha:Math.max(current.alpha,EPIC_LEGACY_HOT_MODULE_ALPHA),beta:current.beta})}let nowIso2=new Date(nowMs).toISOString(),importedFrom={source:"epic-v1-import",at:nowIso2,calibrationHotModules:hotModules?.length??0,divergenceRecords:divergence?.length??0};return writeEpicPrior(directory,{updatedAt:nowIso2,importedFrom,mergedEpics:read.status==="ok"?read.prior.mergedEpics:[],stats:boundEpicLearning(stats2)}),{status:"imported",calibrationHotModules:importedFrom.calibrationHotModules,divergenceRecords:importedFrom.divergenceRecords}}catch(error49){return{status:"failed",detail:errorText3(error49)}}}function describeEpicPriorMerge(result){switch(result.status){case"merged":return`Learning: merged ${result.learnedFiles} file statistic(s) and ${result.learnedEdges} learned co-write(s) into the project prior (\`${EPIC_PRIOR_LEARNING_DISPLAY_PATH}\`)${result.hotFiles.length>0?`; hot files: ${result.hotFiles.slice(0,5).join(", ")}${result.hotFiles.length>5?", …":""}`:"; no hot files"}. Project prior kept (it survives /swarm close; \`/swarm epic prior reset\` clears it).`;case"already-merged":return"Learning: already merged into the project prior. Project prior kept.";case"nothing-to-learn":return"Learning: this epic recorded no outcomes to learn from. Project prior kept.";case"disabled":return"Learning: disabled (`epic.learning.enabled: false`). Project prior kept unchanged.";default:return`Learning: ⚠️ ${result.detail}. Project prior kept unchanged.`}}var EPIC_PRIOR_LEARNING_RELATIVE_PATH,EPIC_PRIOR_LEARNING_DISPLAY_PATH=".swarm/epic-prior/learning.json",EPIC_POSTERIOR_RELATIVE_PATH,LEGACY_CALIBRATION_RELATIVE_PATH,LEGACY_DIVERGENCE_RELATIVE_PATH,EPIC_PRIOR_MERGED_EPICS_KEEP=50,MAX_LEARNING_FILE_BYTES=4194304,MAX_LEGACY_DIVERGENCE_BYTES=16777216,MAX_LEGACY_DIVERGENCE_RECORDS=1e4,MAX_LEGACY_HOT_MODULES=2000,EPIC_LEGACY_HOT_MODULE_ALPHA=2,MAX_WARNED_KEYS=64,fileEntrySchema,edgeEntrySchema,statsSchema,importedFromSchema,priorSchema,posteriorSchema,warnedKeys;var init_learning_store=__esm(()=>{init_zod();init_atomic_write();init_logger();init_learning();EPIC_PRIOR_LEARNING_RELATIVE_PATH=path55.join(".swarm","epic-prior","learning.json"),EPIC_POSTERIOR_RELATIVE_PATH=path55.join(".swarm","epic","posterior.json"),LEGACY_CALIBRATION_RELATIVE_PATH=path55.join(".swarm","epic","calibration.json"),LEGACY_DIVERGENCE_RELATIVE_PATH=path55.join(".swarm","epic","divergence.jsonl"),fileEntrySchema=exports_external.object({path:exports_external.string().min(1),alpha:exports_external.number().finite().min(0),beta:exports_external.number().finite().min(0)}).strict(),edgeEntrySchema=exports_external.object({from:exports_external.string().min(1),to:exports_external.string().min(1),weight:exports_external.number().finite().min(0)}).strict(),statsSchema=exports_external.object({files:exports_external.array(fileEntrySchema),edges:exports_external.array(edgeEntrySchema)}).strict(),importedFromSchema=exports_external.object({at:exports_external.string(),source:exports_external.enum(["epic-v1-import","reset"]),calibrationHotModules:exports_external.number().int().min(0),divergenceRecords:exports_external.number().int().min(0)}).strict(),priorSchema=statsSchema.extend({schema:exports_external.literal("epic-learning-v1"),updatedAt:exports_external.string(),importedFrom:importedFromSchema.nullable(),mergedEpics:exports_external.array(exports_external.string())}).strict(),posteriorSchema=exports_external.object({schema:exports_external.literal("epic-posterior-v1"),epicKey:exports_external.string().min(1),token:exports_external.string().min(1),priorDigest:exports_external.string().nullable(),createdAt:exports_external.string(),lastAppliedWaveSeq:exports_external.number().int().min(0),base:statsSchema.extend({updatedAt:exports_external.string()}).strict(),increments:statsSchema}).strict();warnedKeys=new Set});function isFullSha(value){return typeof value==="string"&&SHA_RE2.test(value)}function taskRefComponent(taskId){if(SAFE_COMPONENT_RE.test(taskId)&&!taskId.endsWith(".lock"))return taskId;return`_x${Buffer.from(taskId,"utf8").toString("hex")}`}function epicRefPrefix(epicKey){return assertSafeGitRefArg(`${EPIC_REFS_ROOT}/${epicKey}`,"epic ref prefix")}function epicBaseRef(epicKey){return`${epicRefPrefix(epicKey)}/base`}function epicWaveRef(epicKey,seq){return`${epicRefPrefix(epicKey)}/waves/${Math.trunc(seq)}`}function epicTaskRef(epicKey,taskId){return assertSafeGitRefArg(`${epicRefPrefix(epicKey)}/tasks/${taskRefComponent(taskId)}`,"epic task ref")}function readEpicRefs(directory,epicKey){let output=_internals54.gitExec(["for-each-ref",`--count=${MAX_EPIC_REFS}`,"--format=%(objectname) %(refname)",epicRefPrefix(epicKey)],directory),refs=new Map;for(let line of output.split(/\r?\n/)){let space=line.indexOf(" ");if(space<=0)continue;let sha=line.slice(0,space),name=line.slice(space+1).trim();if(isFullSha(sha)&&name.length>0)refs.set(name,sha)}return refs}function readOneRef(directory,ref){let sha=_internals54.gitExec(["for-each-ref","--count=1","--format=%(objectname)",ref],directory).trim().split(/\r?\n/)[0]??"";return isFullSha(sha)?sha:null}function writeEpicRef(directory,ref,sha,existing){if(!isFullSha(sha))throw Error(`not a full commit id: ${sha}`);if(assertSafeGitRefArg(ref,"epic ref write"),existing===sha)return"unchanged";try{return _internals54.gitExecOnce(["update-ref",ref,sha,existing??""],directory),existing===null?"created":"updated"}catch(error49){if(readOneRef(directory,ref)===sha)return existing===null?"created":"updated";throw error49}}function desiredEpicRefs(record2){let desired=new Map;if(!record2.git.isRepo)return desired;if(isFullSha(record2.git.baseCommit))desired.set(epicBaseRef(record2.epicKey),record2.git.baseCommit);for(let wave of record2.waves)if(wave.status==="closed"&&isFullSha(wave.closeHead))desired.set(epicWaveRef(record2.epicKey,wave.seq),wave.closeHead);for(let outcome of Object.values(record2.tasks)){let sha=outcome.marker?.sha;if(outcome.resolution==="completed"&&isFullSha(sha))desired.set(epicTaskRef(record2.epicKey,outcome.taskId),sha)}return desired}function syncEpicRefs(directory,record2){let existing=readEpicRefs(directory,record2.epicKey);for(let[ref,sha]of desiredEpicRefs(record2))writeEpicRef(directory,ref,sha,existing.get(ref)??null),existing.set(ref,sha);return existing}function isCommitAncestorOfHead(directory,sha){if(!isFullSha(sha))return!1;return _internals54.gitProbeExitCode(["merge-base","--is-ancestor",sha,"HEAD"],directory)===0}function deleteEpicRefs(directory,epicKey){let deleted=[],failed=[],refs;try{refs=readEpicRefs(directory,epicKey)}catch(error49){return{deleted,failed:[`${epicRefPrefix(epicKey)}/* (${error49 instanceof Error?error49.message:String(error49)})`]}}for(let[ref,sha]of refs)try{_internals54.gitExecOnce(["update-ref","-d",ref,sha],directory),deleted.push(ref)}catch{failed.push(ref)}return{deleted,failed}}function findTaskCommits(directory,range,planKey,taskIds){let wanted=new Map;for(let id of taskIds)wanted.set(scrubTaskIdForGitSubject(id),id);let found=new Map;if(wanted.size===0)return found;let output=_internals54.gitExec(["log","-z","--extended-regexp","--grep=^swarm\\(task [^)]+\\):",`--max-count=${MARKER_LOOKUP_MAX_COMMITS}`,MARKER_LOG_FORMAT,range,"--"],directory);for(let marker of parseTaskMarkerLog(output)){if(marker.planKey!==planKey)continue;let taskId=wanted.get(marker.taskId);if(taskId!==void 0&&!found.has(taskId))found.set(taskId,marker.sha)}return found}function epicCommitRange(record2){return isFullSha(record2.git.baseCommit)?`${record2.git.baseCommit}..HEAD`:"HEAD"}function planEpicTaskRefRepair(directory,record2,unrecorded){let repairs=[],recorded=new Map,adoptedUnrecorded=new Map,refs=readEpicRefs(directory,record2.epicKey),broken=[],reachable=(sha)=>isFullSha(sha)&&isCommitAncestorOfHead(directory,sha);for(let outcome of Object.values(record2.tasks)){if(outcome.resolution!=="completed")continue;let sha=outcome.marker?.sha??null;if(reachable(sha))repairs.push({taskId:outcome.taskId,status:"ok",sha,detail:"reachable from HEAD"});else broken.push(outcome.taskId)}let brokenUnrecorded=[];for(let taskId of unrecorded){if(record2.tasks[taskId])continue;let sha=refs.get(epicTaskRef(record2.epicKey,taskId));if(reachable(sha))repairs.push({taskId,status:"ok",sha,detail:"reachable from HEAD"});else brokenUnrecorded.push(taskId)}if(broken.length===0&&brokenUnrecorded.length===0)return{repairs,recorded,unrecorded:adoptedUnrecorded};let range=epicCommitRange(record2),markers=findTaskCommits(directory,range,record2.planKey,[...broken,...brokenUnrecorded]),needsAttention=(taskId)=>{repairs.push({taskId,status:"needs-attention",sha:null,detail:"no commit reachable from HEAD carries its work — commit it on the epic branch with the subject `swarm(task <id>): …` and the plan trailer, then rerun --repair-refs"})};for(let taskId of broken){let sha=markers.get(taskId)??null,how="its `swarm(task …)` commit for this plan",declared=(record2.tasks[taskId]?.declared??[]).filter((file2)=>file2.length>0&&!file2.startsWith(":"));if(!sha&&declared.length>0){let out=_internals54.gitExec(["log","--max-count=1","--format=%H",range,"--",...declared.slice(0,200).map((file2)=>`:(literal)${file2}`)],directory).trim();if(isFullSha(out))sha=out,how="the newest commit touching its declared files"}if(!sha){needsAttention(taskId);continue}recorded.set(taskId,sha),repairs.push({taskId,status:"repaired",sha,detail:`re-pointed to ${sha.slice(0,12)} (${how})`})}for(let taskId of brokenUnrecorded){let sha=markers.get(taskId);if(!sha){needsAttention(taskId);continue}adoptedUnrecorded.set(taskId,sha),repairs.push({taskId,status:"repaired",sha,detail:`adopted ${sha.slice(0,12)} (its \`swarm(task …)\` commit for this plan; completed outside a wave)`})}return{repairs,recorded,unrecorded:adoptedUnrecorded}}var EPIC_REFS_ROOT="refs/swarm/epics",MARKER_LOOKUP_MAX_COMMITS=2000,MAX_EPIC_REFS=20000,SHA_RE2,SAFE_COMPONENT_RE,_internals54;var init_markers=__esm(()=>{init_branch();init_safe_ref();init_git_once();init_plan_key();SHA_RE2=/^[0-9a-f]{40,64}$/,SAFE_COMPONENT_RE=/^[A-Za-z0-9][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)*$/,_internals54={gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),gitExecOnce,gitProbeExitCode}});function errorText4(error49){return error49 instanceof Error?error49.message:String(error49)}function readHead(directory){try{let head=_internals55.gitExec(["rev-parse","HEAD"],directory).trim();return SHA_RE3.test(head)?head:null}catch{return null}}function isSwarmPath(file2){return file2===".swarm"||file2.startsWith(".swarm/")}function changedFilesSinceBase(directory,baseHead){if(!baseHead||!SHA_RE3.test(baseHead))return null;try{let files=new Set,committed=_internals55.gitExec(["diff","--name-only","-z",baseHead,"HEAD"],directory);for(let file2 of committed.split("\x00"))if(file2.length>0)files.add(file2.replace(/\\/g,"/"));let records=_internals55.gitExec(["status","--porcelain=v1","-z","--untracked-files=all"],directory).split("\x00");for(let i=0;i<records.length;i+=1){let record2=records[i];if(record2.length<4)continue;let code=record2.slice(0,2);if(files.add(record2.slice(3).replace(/\\/g,"/")),code.includes("R")||code.includes("C"))i+=1}return[...files].filter((file2)=>!isSwarmPath(file2)).sort().slice(0,MAX_FALLBACK_FILES)}catch(error49){return warn(`[epic/wave-close] git fallback for divergence unavailable: ${errorText4(error49)}`),null}}function collectTaskAttribution(directory,callerSessionID,taskId){let collected=[],add=(session)=>{if(!session)return;try{collected.push(..._internals55.getModifiedFilesForTask(session,taskId))}catch{}},caller=callerSessionID?_internals55.getAgentSession(callerSessionID):void 0;add(caller);let projectKey=null;try{projectKey=_internals55.hydrationProjectKey(directory)}catch{projectKey=null}if(projectKey!==null)try{for(let[,session]of _internals55.listAgentSessions()){if(session===caller)continue;if(!session||!(session.modifiedFilesByTask instanceof Map))continue;if(session.owningProjectKey!==projectKey)continue;add(session)}}catch{}let canonical=new Set;for(let file2 of collected){let normalized=canonicalAttributionPath(file2,directory);if(normalized!==null)canonical.add(normalized)}return[...canonical].sort()}function lastTransitionAt(events,taskId,resolution){let at=null;for(let event of events){if(event.task_id!==taskId)continue;if(resolution==="removed"&&event.event_type==="task_removed"||event.event_type==="task_status_changed"&&event.to_status===resolution)at=event.timestamp}return at}function countReopens(events,taskId,sinceIso){let since=Date.parse(sinceIso);return events.filter((event)=>event.task_id===taskId&&event.event_type==="task_status_changed"&&event.from_status==="completed"&&event.to_status!=="completed"&&(!Number.isFinite(since)||Date.parse(event.timestamp)>=since)).length}async function readWorkflowCounts(directory,taskId){try{let workflow=(await _internals55.readTaskEvidence(directory,taskId))?.workflow;if(!workflow)return{generation:0,stageA:0,stageB:0};let history=Array.isArray(workflow.retryHistory)?workflow.retryHistory:[];return{generation:Number.isFinite(workflow.generation)?workflow.generation:0,stageA:history.filter((o)=>o==="stage_a_failed").length,stageB:history.filter((o)=>o==="stage_b_failed").length}}catch{return{generation:0,stageA:0,stageB:0}}}function resolutionOf(plan,taskId){for(let phase of plan.phases){let task=(phase.tasks??[]).find((t)=>t.id===taskId);if(!task)continue;if(task.status==="completed")return"completed";if(task.status==="closed")return"closed";return null}return"removed"}function markerFor(epic,taskId,resolution,closeHead,taskCommits){if(resolution!=="completed")return null;if(!epic.git.isRepo)return{ref:null,sha:null,provenance:"no-git"};let landed=taskCommits.get(taskId),sha=landed??closeHead;return{ref:isFullSha(sha)?epicTaskRef(epic.epicKey,taskId):null,sha,provenance:landed?"landing-commit":"wave-close-head"}}async function computeWaveClose(args2){let{directory,epic,wave,plan,sessionID,nowIso:nowIso2}=args2,isRepo=epic.git.isRepo,closeHead=isRepo?readHead(directory):null,events=[];try{events=await _internals55.readLedgerEvents(directory)}catch(error49){warn(`[epic/wave-close] plan ledger unreadable; outcome times fall back to now: ${errorText4(error49)}`)}let changed=isRepo?changedFilesSinceBase(directory,wave.baseHead):null,completedIds=wave.taskIds.filter((taskId)=>resolutionOf(plan,taskId)==="completed"),taskCommits=new Map;if(isRepo&&closeHead&&completedIds.length>0)try{taskCommits=_internals55.findTaskCommits(directory,isFullSha(wave.baseHead)?`${wave.baseHead}..HEAD`:epicCommitRange(epic),epic.planKey,completedIds)}catch(error49){warn(`[epic/wave-close] task commit lookup failed; markers fall back to the close HEAD: ${errorText4(error49)}`)}let outcomes=[],attributedAll=new Set;for(let taskId of wave.taskIds){let resolution=resolutionOf(plan,taskId)??"removed",declared=[...wave.files[taskId]??[]],counts=resolution==="removed"?{generation:0,stageA:0,stageB:0}:await readWorkflowCounts(directory,taskId),undeclared=[],attribution=isRepo?"unavailable":"no-git";if(resolution==="completed"){let attributed=collectTaskAttribution(directory,sessionID,taskId);for(let file2 of attributed)attributedAll.add(file2);let actual=null;if(attributed.length>0)actual=attributed,attribution="session";else if(changed!==null&&wave.taskIds.length===1)actual=changed,attribution="git-single-task";if(actual!==null)undeclared=undeclaredFiles(declared,actual)}let snapshot=wave.mergeFailures?.[taskId];outcomes.push({taskId,phase:wave.phase,waveSeq:wave.seq,resolution,resolvedAt:lastTransitionAt(events,taskId,resolution)??nowIso2,generation:counts.generation,stageAFailures:counts.stageA,stageBFailures:counts.stageB,mergeFailure:snapshot?{outcome:snapshot.outcome,stage:snapshot.stage}:null,declared,undeclared,attribution,reopened:countReopens(events,taskId,epic.startedAt),marker:markerFor(epic,taskId,resolution,closeHead,taskCommits)})}let waveUndeclared=[];if(changed!==null){let declaredAll=Object.values(wave.files).flat();waveUndeclared=undeclaredFiles(declaredAll,changed).filter((file2)=>!attributedAll.has(file2))}return{closeHead,outcomes,waveUndeclared}}function applyWaveClose(record2,seq,computation,nowIso2){let wave=record2.waves.find((w)=>w.seq===seq);if(!wave||wave.status!=="issued"||record2.activeWaveSeq!==seq)return record2;let tasks={...record2.tasks};for(let outcome of computation.outcomes){let before=Object.hasOwn(record2.tasks,outcome.taskId)?record2.tasks[outcome.taskId]:void 0;tasks[outcome.taskId]=before&&before.waveSeq!==outcome.waveSeq?{...outcome,previous:{waveSeq:before.waveSeq,generation:before.generation,stageBFailures:before.stageBFailures,reopened:before.reopened}}:outcome}return{...record2,activeWaveSeq:null,tasks,waves:record2.waves.map((w)=>w.seq===seq?{...w,status:"closed",closedAt:nowIso2,closeHead:computation.closeHead,undeclared:computation.waveUndeclared}:w)}}function recordEpicWaveLearning(args2){let settings=resolveEpicLearningSettings(args2.config);if(!settings.enabled)return[];try{return _internals55.applyClosedWavesToPosterior(args2.directory,args2.record,settings).appliedWaves}catch(error49){return criticalWarn(`[epic/wave-close] learning update failed (the wave flow continues; the next wave close catches it up): ${errorText4(error49)}`),[]}}function releaseWaveAttribution(directory,sessionID,taskIds){let sessions=new Set,caller=sessionID?_internals55.getAgentSession(sessionID):void 0;if(caller)sessions.add(caller);try{let projectKey=_internals55.hydrationProjectKey(directory);for(let[,session]of _internals55.listAgentSessions())if(session&&session.owningProjectKey===projectKey)sessions.add(session)}catch{}for(let session of sessions)for(let taskId of taskIds)try{_internals55.resetModifiedFilesForTask(session,taskId,{remove:!0})}catch{}}var MAX_FALLBACK_FILES=2000,SHA_RE3,_internals55;var init_wave_close=__esm(()=>{init_gate_evidence();init_branch();init_ledger();init_hydration_ownership();init_state();init_logger();init_path();init_learning();init_learning_store();init_markers();SHA_RE3=/^[0-9a-f]{7,64}$/,_internals55={gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),readTaskEvidence,readLedgerEvents,listAgentSessions:()=>swarmState.agentSessions.entries(),getAgentSession,getModifiedFilesForTask,resetModifiedFilesForTask,hydrationProjectKey,applyClosedWavesToPosterior,findTaskCommits}});import*as fs32 from"node:fs";import*as path56 from"node:path";function errorText5(error49){return error49 instanceof Error?error49.message:String(error49)}function isSwarmStatePath(file2){let normalized=file2.replace(/\\/g,"/");return normalized===".swarm"||normalized.startsWith(".swarm/")||normalized.includes("/.swarm/")||normalized.endsWith("/.swarm")}function caseKey(file2){return process.platform==="win32"?file2.toLowerCase():file2}function listDirtyEntries(directory){let output=_internals56.gitExec(["status","--porcelain=v1","-z","--untracked-files=all"],directory),entries=[],records=output.split("\x00");for(let i=0;i<records.length;i+=1){let record2=records[i];if(record2.length<4)continue;let code=record2.slice(0,2),file2=record2.slice(3).replace(/\\/g,"/"),origin;if(code.includes("R")||code.includes("C"))i+=1,origin=records[i]?.replace(/\\/g,"/");if(isSwarmStatePath(file2))continue;if(entries.push({path:file2,untracked:code==="??",needsAdd:code[1]!==" ",...origin?{origin}:{}}),entries.length>=MAX_DIRTY_ENTRIES)break}return entries}function coveredBy(file2,declared){let key=caseKey(file2);return declared.some((entry)=>{let d=caseKey(entry.replace(/\\/g,"/").replace(/\/+$/,""));return d.length>0&&(key===d||key.startsWith(`${d}/`))})}function literal2(file2){return`:(literal)${file2}`}function readIndexEntries(directory,files){let entries=new Map;for(let i=0;i<files.length;i+=PATHSPEC_CHUNK){let out=_internals56.gitExec(["ls-files","-s","-z","--",...files.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);for(let record2 of out.split("\x00")){let tab=record2.indexOf("\t");if(tab<0)continue;let[mode,sha,stage]=record2.slice(0,tab).split(" ");if(stage!=="0")continue;entries.set(record2.slice(tab+1),`${mode} ${sha}`)}}return entries}function restoreIndexEntries(directory,files,before){for(let i=0;i<files.length;i+=PATHSPEC_CHUNK)_internals56.gitExecOnce(["reset","-q","--",...files.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);let after=readIndexEntries(directory,files);for(let file2 of files){let wanted=before.get(file2),actual=after.get(file2);if(wanted===actual)continue;if(wanted){let[mode,sha]=wanted.split(" ");_internals56.gitExecOnce(["update-index","--cacheinfo",`${mode},${sha},${file2}`],directory)}else _internals56.gitExecOnce(["update-index","--force-remove","--",file2],directory)}}function commitPaths(directory,message,files,toAdd){let base=["-c","commit.gpgsign=false","commit","--only","--no-verify","-m",message],pathspecs=files.map(literal2),inlineBytes=pathspecs.reduce((sum,p)=>sum+Buffer.byteLength(p,"utf-8")+1,0),before=readIndexEntries(directory,files);try{for(let i=0;i<toAdd.length;i+=PATHSPEC_CHUNK)_internals56.gitExecOnce(["add","-A","--",...toAdd.slice(i,i+PATHSPEC_CHUNK).map(literal2)],directory);if(inlineBytes<=COMMIT_ARGV_PATHSPEC_BUDGET_BYTES)_internals56.gitExecOnce([...base,"--",...pathspecs],directory);else{let gitPath=_internals56.gitExec(["rev-parse","--git-path",`swarm-epic-residue-${process.pid}-${_internals56.now()}`],directory).trim(),specFile=path56.resolve(directory,gitPath);try{fs32.writeFileSync(specFile,`${pathspecs.join("\x00")}\x00`,"utf-8"),_internals56.gitExecOnce([...base,`--pathspec-from-file=${specFile}`,"--pathspec-file-nul"],directory)}finally{try{fs32.rmSync(specFile,{force:!0})}catch{}}}}catch(error49){try{restoreIndexEntries(directory,files,before)}catch(restoreError){criticalWarn(`[epic] could not restore the index after a failed residue commit (${errorText5(restoreError)}); check \`git status\` for: ${files.slice(0,10).join(", ")}`)}throw error49}try{let head=_internals56.gitExec(["rev-parse","HEAD"],directory).trim();return/^[0-9a-f]{40,64}$/.test(head)?head:null}catch{return null}}function commitTaskResidue(args2){let wanted=new Set;for(let candidate of args2.candidates)if(typeof candidate==="string"&&candidate.length>0&&!candidate.startsWith(":")&&!isSwarmStatePath(candidate))wanted.add(caseKey(candidate.replace(/\\/g,"/")));let files=new Set,toAdd=new Set,scopes=(args2.scopes??[]).filter((entry)=>entry.length>0&&!entry.startsWith(":")),globLike=scopes.filter((entry)=>/[*?]/.test(entry));if(globLike.length>0)warn(`[epic] task ${args2.taskId}: declared scope entries are literal files or directories, never globs; ${globLike.slice(0,5).join(", ")} only match a path spelled exactly like that.`);for(let entry of args2.dirty){if(!wanted.has(caseKey(entry.path))&&!(scopes.length>0&&coveredBy(entry.path,scopes)))continue;if(files.add(entry.path),entry.needsAdd!==!1)toAdd.add(entry.path);if(entry.origin&&!isSwarmStatePath(entry.origin))files.add(entry.origin)}if(files.size===0)return{status:"nothing"};let list2=[...files].sort();try{return{status:"committed",sha:commitPaths(args2.directory,formatEpicTaskCommitMessage(args2.taskId,args2.epic.planKey,args2.label),list2,[...toAdd].sort()),files:list2}}catch(error49){return{status:"failed",error:errorText5(error49),files:list2}}}function inFlightWriterFiles(directory,exclude){let files=new Set;for(let[id,session]of _internals56.listAgentSessions()){if(exclude.has(id)||!session?.delegationActive)continue;if(!(session.modifiedFilesByTask instanceof Map))continue;for(let entries of session.modifiedFilesByTask.values())for(let file2 of entries){let canonical=canonicalAttributionPath(file2,directory);if(canonical!==null)files.add(caseKey(canonical))}}return files}function childSessionFiles(directory,ids){let files=[];for(let id of new Set(ids)){if(typeof id!=="string"||id.length===0)continue;let session=_internals56.getAgentSession(id);if(!session||!(session.modifiedFilesByTask instanceof Map))continue;for(let entries of session.modifiedFilesByTask.values())for(let file2 of entries){let canonical=canonicalAttributionPath(file2,directory);if(canonical!==null)files.push(canonical)}}return files}function declaredScopeOf(epic,taskId){return[...epic.waves.find((w)=>w.seq===epic.activeWaveSeq&&w.status==="issued")?.files[taskId]??[]]}async function commitEpicResidueAfterDelegation(request){try{if(!_internals56.epicSentinelExists(request.directory))return;let agent=stripKnownSwarmPrefix(request.agent);if(agent==="coder"||agent==="architect")return;let epic=_internals56.getOpenEpic(request.directory);if(!epic||!epic.git.isRepo)return;let taskIds=(await request.resolveTaskIds()).filter((id)=>_internals56.readPlanTaskRef(request.directory,id)!==null);if(taskIds.length===0)return;let branch=_internals56.checkEpicBranch(request.directory,epic);if(!branch.ok){criticalWarn(`[epic] ${agent} residue for task ${taskIds.join(", ")} NOT committed: ${branch.message}`);return}let childIds=await request.childSessionIds(),childFiles=childSessionFiles(request.directory,childIds),exclude=new Set([...childIds,request.sessionID].filter((id)=>typeof id==="string"&&id.length>0)),inFlight=inFlightWriterFiles(request.directory,exclude);await _internals56.serializeWithMergeBacks(()=>commitResidueForTasks(request,epic,agent,taskIds,childFiles,inFlight))}catch(error49){criticalWarn(`[epic] residue commit after a ${request.agent} delegation failed (non-fatal; epic_next_wave retries): ${errorText5(error49)}`)}}function commitResidueForTasks(request,epic,agent,taskIds,childFiles,inFlight=new Set){try{let dirty=listDirtyEntries(request.directory).filter((entry)=>!inFlight.has(caseKey(entry.path)));if(dirty.length===0)return;let remaining=dirty,commitStep=(taskId,label,candidates,scopes)=>{let result=commitTaskResidue({directory:request.directory,epic,taskId,label,candidates,scopes,dirty:remaining});if(result.status==="failed")return criticalWarn(`[epic] ${label} for task ${taskId} could not be committed (${result.error}); epic_next_wave retries before the next wave. Files: ${result.files.slice(0,10).join(", ")}`),!1;if(result.status==="committed"){let done=new Set(result.files.map(caseKey));remaining=remaining.filter((entry)=>!done.has(caseKey(entry.path)))}return!0};for(let[index,taskId]of taskIds.entries()){if(index===0&&childFiles.length>0&&!commitStep(taskId,`${agent} residue`,childFiles,[]))return;if(!commitStep(taskId,"residue",_internals56.collectTaskAttribution(request.directory,request.sessionID,taskId),declaredScopeOf(epic,taskId)))return}}catch(error49){criticalWarn(`[epic] residue commit after a ${request.agent} delegation failed (non-fatal; epic_next_wave retries): ${errorText5(error49)}`)}}function classifyDirtyBaseline(dirty){let unattributedTracked=[],unattributedUntracked=[];for(let entry of dirty)(entry.untracked?unattributedUntracked:unattributedTracked).push(entry.path);return{unattributedTracked,unattributedUntracked}}var COMMIT_ARGV_PATHSPEC_BUDGET_BYTES=24576,PATHSPEC_CHUNK=200,MAX_DIRTY_ENTRIES=5000,_internals56;var init_residue_commit=__esm(()=>{init_schema();init_branch();init_worktree_isolation();init_state();init_logger();init_path();init_epic_branch();init_git_once();init_lifecycle();init_plan_key();init_wave_close();_internals56={epicSentinelExists,getOpenEpic,readPlanTaskRef,checkEpicBranch,collectTaskAttribution,getAgentSession,listAgentSessions:()=>swarmState.agentSessions.entries(),gitExec:(args2,cwd)=>_internals45.gitExec(args2,cwd),gitExecOnce,serializeWithMergeBacks:(task)=>runSerializedWithMergeBacks(task),now:()=>Date.now()}});function normalizeToolName(toolName){if(!toolName)return;return toolName.replace(NAMESPACE_PREFIX_PATTERN,"")}function normalizeToolNameLowerCase(toolName){return toolName.replace(NAMESPACE_PREFIX_PATTERN,"").toLowerCase()}function isTaskToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.task$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="task"}var NAMESPACE_PREFIX_PATTERN;var init_normalize_tool_name=__esm(()=>{NAMESPACE_PREFIX_PATTERN=/^[^:]+[:.]/});function declaresWindowsWrapper(command){return CMD_WRAPPER_DECLARATION.test(command)||PS_WRAPPER_DECLARATION.test(command)}function declaresWindowsWrapperLoose(command){return declaresWindowsWrapper(command)||PS_WRAPPER_LOOSE.test(command)}function recordObservedHostShell(shell){if(typeof shell!=="string"||shell.trim()==="")return;observedHostShell=shell}function getObservedHostShell(){return observedHostShell}function hostShellGrammarFamily(hostShell){let name=(hostShell.split(/[\\/]/).filter(Boolean).pop()??hostShell).replace(/\.exe$/i,"").toLowerCase();return name==="powershell"||name==="pwsh"||name==="cmd"?"windows":"posix"}var CMD_SWITCH,CMD_WRAPPER_DECLARATION,PS_WRAPPER_DECLARATION,PS_WRAPPER_LOOSE,CMD_BUILTIN_PREFIX,CMD_STRIP_PREFIX,PS_STRIP_PREFIX,observedHostShell;var init_shell_executor_context=__esm(()=>{CMD_SWITCH=String.raw`\/[a-z](?::(?:on|off))?`,CMD_WRAPPER_DECLARATION=new RegExp(String.raw`(?:^|[;|&\n])\s*cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/c(?:\s|$)`,"i"),PS_WRAPPER_DECLARATION=/(?:^|[;|&\n])\s*(?:powershell|pwsh)(?:\.exe)?\s+(?:-[A-Za-z]+\s+)*-command(?:\s|$)/i,PS_WRAPPER_LOOSE=/(?:^|\|)\s*(?:powershell|pwsh)(?:\.exe)?\s+-/i;CMD_BUILTIN_PREFIX=new RegExp(String.raw`(?:(?:^|\s)(?:if\s+(?:not\s+)?exist\s+(?:"[^"]*"|\S+)\s+)|(?:^|[;|&\n])\s*cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/c\s+|(?:^|\s)(?:call|start)\s+)*`,"i"),CMD_STRIP_PREFIX=new RegExp(String.raw`^cmd(?:\.exe)?\s+(?:${CMD_SWITCH}\s+)*\/[ck]\s+`,"i"),PS_STRIP_PREFIX=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-[A-Za-z]+\s+)*-(?:command|c)\s+/i});import*as fsSync6 from"node:fs";import*as path57 from"node:path";function dcNormalizeCommand(cmd){let s=cmd.normalize("NFKC");return s=s.replace(/`(.)/g,"$1"),s=s.replace(/\^([a-zA-Z0-9 ])/g,"$1"),s=s.replace(/""/g,""),s=s.replace(/''/g,""),s}function dcStripOneWrapper(cmd){let t=cmd.trim(),cmdExeMatch=new RegExp(`${CMD_STRIP_PREFIX.source}"?(.*?)"?\\s*$`,"is").exec(t);if(cmdExeMatch)return cmdExeMatch[1].trim();let psCommandMatch=new RegExp(`${PS_STRIP_PREFIX.source}(.+)$`,"is").exec(t);if(psCommandMatch)return psCommandMatch[1].replace(/^["']|["']$/g,"").trim();let psEncMatch=/^(?:powershell|pwsh)(?:\.exe)?\s+(?:-(?:EncodedCommand|encodedcommand|enc|e)\s+)([A-Za-z0-9+/=]+)\s*$/.exec(t);if(psEncMatch)try{return Buffer.from(psEncMatch[1],"base64").toString("utf16le").trim()}catch{return t}let shellMatch=/^(?:bash|sh|zsh|dash|fish)(?:\.exe)?\s+-c\s+"?(.*?)"?\s*$/is.exec(t);if(shellMatch)return shellMatch[1].trim();let evalMatch=/^eval\s+(.+)$/is.exec(t);if(evalMatch)return evalMatch[1].replace(/^["']|["']$/g,"").trim();let envPrefix=/^env(?:\s+(?:[A-Za-z_][A-Za-z0-9_]*=\S+|(?:-[i0vVh]*[uUCSaP]|--u(?:n(?:s(?:e(?:t)?)?)?)?|--c(?:h(?:d(?:i(?:r)?)?)?)?|--a(?:r(?:g(?:v(?:0)?)?)?)?|--s(?:p(?:l(?:i(?:t(?:-(?:s(?:t(?:r(?:i(?:n(?:g)?)?)?)?)?)?)?)?)?)?)?|--e(?:n(?:v(?:0(?:-(?:f(?:r(?:o(?:m)?)?)?)?)?)?)?)?)\s+\S+|-\S+|--[A-Za-z][A-Za-z0-9-]*))*\s+(.+)$/is,prefixMatch=/^(?:sudo|time|nohup)\s+(.+)$/is.exec(t)??envPrefix.exec(t)??/^nice\s+(?:-n\s+\d+\s+)?(.+)$/is.exec(t);if(prefixMatch)return prefixMatch[1].trim();let wslMatch=/^wsl(?:\.exe)?\s+(?:-e|--)\s+(.+)$/is.exec(t);if(wslMatch)return wslMatch[1].trim();let scriptBlockMatch=/^&\s*\{(.+)\}$/s.exec(t);if(scriptBlockMatch)return scriptBlockMatch[1].trim();let iexMatch=/^(?:Invoke-Expression|iex)\s+(.+)$/is.exec(t);if(iexMatch)return iexMatch[1].replace(/^["'`]|["'`]$/g,"").trim();let invokeCommandMatch=/^Invoke-Command\s+.*-ScriptBlock\s*\{(.+)\}$/is.exec(t);if(invokeCommandMatch)return invokeCommandMatch[1].trim();let callMatch=/^call\s+(.+)$/is.exec(t);if(callMatch)return callMatch[1].trim();return null}function dcUnwrapWrappers(cmd){let current=cmd.trim();for(let depth=0;depth<DC_MAX_UNWRAP_DEPTH;depth++){let inner=dcStripOneWrapper(current);if(inner===null||inner===current)break;current=inner.trim()}return current}function dcSplitSegments(cmd){let segments=[],current="",inDoubleQuote=!1,inSingleQuote=!1;for(let i=0;i<cmd.length;i++){let ch=cmd[i],next=cmd[i+1];if(ch==='"'&&!inSingleQuote){inDoubleQuote=!inDoubleQuote,current+=ch;continue}if(ch==="'"&&!inDoubleQuote){inSingleQuote=!inSingleQuote,current+=ch;continue}if(!inDoubleQuote&&!inSingleQuote){if(ch==="&"&&next==="&"||ch==="|"&&next==="|"){segments.push(current.trim()),current="",i++;continue}if(ch==="|"||ch===";"||ch===`
|
|
707
707
|
`||ch==="\r"){segments.push(current.trim()),current="";continue}if(ch==="&"&&next!=="&"){if(!(cmd[i-1]===">"||next===">")){segments.push(current.trim()),current="";continue}}}current+=ch}if(current.trim())segments.push(current.trim());return segments.filter((s)=>s.length>0)}function dcExtractRecursiveRmTargets(segment){let tokens=segment.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/g)??[];if(tokens.length<2||tokens[0]!=="rm")return null;let destructive=!1,index=1;for(;index<tokens.length;index++){let token=tokens[index];if(token==="--"){index++;break}if(!token.startsWith("-")||token==="-")break;if(token==="--recursive"||token==="--force")destructive=!0;if(!token.startsWith("--")&&/[rRfF]/.test(token.slice(1)))destructive=!0}if(!destructive)return null;return tokens.slice(index).map((target)=>target.replace(/^(["'])|(["'])$/g,""))}function dcHasUnresolvableVars(p){return/(%[A-Za-z_][A-Za-z0-9_]*%|\$\{?[A-Za-z_]|\$env:)/i.test(p)}function dcIsRemotePath(p){return DC_REMOTE_PREFIXES.some((pfx)=>p.startsWith(pfx))}function dcLstatAncestorWalk(targetPath,cwd){let normalizedTarget=path57.resolve(cwd,targetPath),normalizedCwd=path57.resolve(cwd),ancestors=[],current=normalizedTarget;while(!0){let rel=path57.relative(normalizedCwd,current);if(rel===".."||rel.startsWith(`..${path57.sep}`)||path57.isAbsolute(rel))break;if(ancestors.push(current),rel==="")break;let parent=path57.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat8=null;try{stat8=fsSync6.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`lstat failed on "${ancestor}": ${String(err)} — refusing to allow destructive operation on unverifiable path`}if(stat8.isSymbolicLink())return`BLOCKED: "${ancestor}" is a symlink/junction — deleting recursively through it would destroy the link target. Use platform-specific junction deletion (fsutil reparsepoint delete, Remove-Item without -Recurse) instead.`}return null}function dcValidateTargets(targets,cwd){for(let raw of targets){let t=raw.trim().replace(/^["']|["']$/g,"");if(!t||t===".")continue;if(dcHasUnresolvableVars(t))return`BLOCKED: Destructive command targets path with unexpanded variable "${t}" — cannot verify safety. Resolve variables before using destructive operations.`;if(dcIsRemotePath(t))return`BLOCKED: Destructive command targets remote/network filesystem path "${t}" — refusing to execute remote destructive operations.`;if(/^\\\\/.test(t))return`BLOCKED: Destructive command targets UNC path "${t}" — UNC paths in destructive operations are not allowed.`;let filesystemTarget=t.replace(/[\\/]+/g,path57.sep),lstatBlock=dcLstatAncestorWalk(filesystemTarget,cwd);if(lstatBlock)return lstatBlock;let basename11=path57.basename(filesystemTarget);if(dcPathComponents(t).length===1&&DC_SAFE_TARGETS.has(basename11))continue;if(DC_FS_ROOTS.has(t)||DC_FS_ROOTS.has(t.replace(/\//g,"\\")))return`BLOCKED: Destructive command targets filesystem root "${t}"`;if(path57.isAbsolute(t)||/^[A-Za-z]:/.test(t)){for(let blocked of DC_BLOCKED_ABSOLUTE_PREFIXES)if(t.startsWith(blocked))return`BLOCKED: Destructive command targets system path "${t}" which is under protected prefix "${blocked}"`}}return null}function dcIsUntrustedCodePoint(codePoint){return codePoint<=31||codePoint>=127&&codePoint<=159||codePoint>=8234&&codePoint<=8238||codePoint>=8294&&codePoint<=8297}function dcHasUntrustedText(value){return Array.from(value).some((character)=>dcIsUntrustedCodePoint(character.codePointAt(0)??0))}function dcSafeDiagnosticValue(value){return value.split("").map((character)=>dcIsUntrustedCodePoint(character.codePointAt(0)??0)?"?":character).join("").slice(0,512)}function dcPathComponents(value){return value.replace(/\\/g,"/").split("/").filter(Boolean)}function dcComponentEquals(left,right){return process.platform==="win32"?left.toLowerCase()===right.toLowerCase():left===right}function dcScopeContains(scopeEntry,target){let normalize8=(value)=>{let normalized=path57.posix.normalize(value.replace(/\\/g,"/")).replace(/^\.\//,"").replace(/\/$/,"");return process.platform==="win32"?normalized.toLowerCase():normalized},scope=normalize8(scopeEntry),candidate=normalize8(target);return candidate===scope||candidate.startsWith(`${scope}/`)}function dcEvaluateRecursiveDeleteTargets(input){if(input.targets.length===0)return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:"BLOCKED: Recursive delete has no statically verifiable target."};let commonBlock=dcValidateTargets(input.targets,input.cwd);if(commonBlock)return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:commonBlock};let normalizedTargets=[],hasNested=!1;for(let raw of input.targets){let target=raw.trim().replace(/^['"]|['"]$/g,""),safeTarget=dcSafeDiagnosticValue(target);if(!target||target==="."||dcHasUntrustedText(target)||dcPathComponents(target).includes(".."))return{allowed:!1,code:"DESTRUCTIVE_TARGET_INVALID",reason:`BLOCKED: Recursive delete target "${safeTarget}" is empty, the workspace root, contains traversal, or contains control characters.`};let components=dcPathComponents(target);if(components.some((component)=>dcComponentEquals(component,".git")||dcComponentEquals(component,".swarm")))return{allowed:!1,code:"DESTRUCTIVE_TARGET_PROTECTED",reason:`BLOCKED: Recursive delete target "${safeTarget}" contains protected .git or .swarm state.`};let filesystemTarget=target.replace(/[\\/]+/g,path57.sep),resolved=path57.resolve(input.cwd,filesystemTarget),relative13=path57.relative(path57.resolve(input.cwd),resolved);if(relative13===""||relative13===".."||relative13.startsWith(`..${path57.sep}`)||path57.isAbsolute(relative13))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUTSIDE_WORKSPACE",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not strictly contained by the workspace.`};let basename11=path57.basename(resolved);if(!DC_SAFE_TARGETS.has(basename11))return{allowed:!1,code:"DESTRUCTIVE_TARGET_NOT_SAFE_ARTIFACT",reason:`BLOCKED: Recursive delete target "${safeTarget}" is not an allowlisted build/cache artifact.`};let normalizedRelative=relative13.replace(/\\/g,"/");if(components.length!==1){if(hasNested=!0,!input.verifiedScope?.bindingId||!input.verifiedScope.generationId)return{allowed:!1,code:"DESTRUCTIVE_TARGET_SCOPE_REQUIRED",reason:`BLOCKED: Nested safe artifact "${safeTarget}" requires a verified active coder scope binding.`};if(!input.verifiedScope.files.some((entry)=>dcScopeContains(entry,normalizedRelative)))return{allowed:!1,code:"DESTRUCTIVE_TARGET_OUT_OF_SCOPE",reason:`BLOCKED: Nested safe artifact "${safeTarget}" is outside the verified active coder scope.`}}normalizedTargets.push(normalizedRelative)}return{allowed:!0,kind:hasNested?"scoped-nested-safe-artifact":"bare-safe-artifact",targets:normalizedTargets}}function dcCheckJunctionCreation(segment,cwd){let mklinkMatch=/^mklink(?:\.exe)?\s+\/[JjDd]\s+"?([^"\s]+)"?\s+"?([^"\s]+)"?/i.exec(segment);if(mklinkMatch){let target=mklinkMatch[2].trim();if(!dcHasUnresolvableVars(target)){let resolved=path57.resolve(cwd,target),rel=path57.relative(cwd,resolved);if(rel.startsWith("..")||path57.isAbsolute(rel))return`BLOCKED: Junction/symlink creation targeting path outside working directory: mklink target "${target}" resolves to "${resolved}" which is outside "${cwd}". Creating junctions to external paths and then deleting them recursively can destroy data.`}return null}let newItemTypeMatch=/New-Item\b.*-ItemType\s+(?:Junction|SymbolicLink|HardLink)\b/i.test(segment),newItemTargetMatch=/-Target\s+"?([^"\s;]+)"?/i.exec(segment),newItemMatch=newItemTypeMatch?newItemTargetMatch:null;if(newItemMatch){let target=newItemMatch[1].trim();if(!dcHasUnresolvableVars(target)){let resolved=path57.resolve(cwd,target),rel=path57.relative(cwd,resolved);if(rel.startsWith("..")||path57.isAbsolute(rel))return`BLOCKED: Junction/symlink creation targeting path outside working directory: New-Item target "${target}" resolves to "${resolved}" which is outside "${cwd}". This pattern caused the K2.6 data-loss incident.`}return null}let lnMatch=/^ln\s+(?:-[sfnv]*s[sfnv]*|-s)\s+"?([^"\s]+)"?(?:\s+"?[^"\s]+"?)?\s*$/.exec(segment);if(lnMatch){let target=lnMatch[1].trim();if(!dcHasUnresolvableVars(target)){let resolved=path57.resolve(cwd,target),rel=path57.relative(cwd,resolved);if(rel.startsWith("..")||path57.isAbsolute(rel))return`BLOCKED: Symlink creation targeting path outside working directory: ln -s target "${target}" resolves to "${resolved}" which is outside "${cwd}". Symlinks to external paths combined with recursive deletion can destroy data.`}return null}return null}function dcExtractWindowsCmdTargets(segment){let rmdirMatch=/^(?:rmdir|rd)(?:\.exe)?\s+(?:\/[sqSQ]\s+)*"?(.+?)"?\s*$/i.exec(segment);if(rmdirMatch)return[rmdirMatch[1].trim()];let delMatch=/^del(?:\.exe)?\s+(?:\/[sqfSQF]\s+)*"?(.+?)"?\s*$/i.exec(segment);if(delMatch)return[delMatch[1].trim()];return[]}function dcExtractPowerShellTargets(segment){let verbMatch=/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\s+/i.exec(segment);if(!verbMatch)return[];let tokens=segment.slice(verbMatch[0].length).match(/"[^"]*"|'[^']*'|[^\s]+/g)??[],targets=[],valueFlags=new Set(["-literalpath","-path","-filter","-include","-exclude","-lp"]),skipNext=!1;for(let tok of tokens){if(skipNext){skipNext=!1;continue}if(tok.startsWith("-")){if(valueFlags.has(tok.toLowerCase())){skipNext=!0;let idx=tokens.indexOf(tok);if(idx!==-1&&idx+1<tokens.length){let val=tokens[idx+1].replace(/^["']|["']$/g,"");if(val)targets.push(val);skipNext=!0}}}else{let cleaned=tok.replace(/^["']|["']$/g,"");if(cleaned)targets.push(cleaned)}}return targets}var DC_MAX_UNWRAP_DEPTH=5,DC_SAFE_TARGETS,DC_BLOCKED_ABSOLUTE_PREFIXES,DC_FS_ROOTS,DC_REMOTE_PREFIXES;var init_destructive_command=__esm(()=>{init_shell_executor_context();DC_SAFE_TARGETS=new Set(["node_modules","dist","build","coverage",".next",".turbo",".cache",".venv","venv","__pycache__","target","out",".parcel-cache",".svelte-kit",".nuxt",".output",".angular",".gradle","vendor"]),DC_BLOCKED_ABSOLUTE_PREFIXES=["/root","/home","/Users","/etc","/var","/usr","/opt","/bin","/sbin","/lib","/boot","/proc","/sys","/dev","/run","/System","/Library","/Applications","C:\\Windows","C:\\Users","C:\\Program Files","C:\\ProgramData","C:/Windows","C:/Users","C:/Program Files","C:/ProgramData"],DC_FS_ROOTS=new Set(["/","C:\\","C:/","D:\\","D:/","E:\\","E:/"]),DC_REMOTE_PREFIXES=["\\\\","/Volumes/","/net/","/nfs/","/smb/","/run/user/"]});import{createHash as createHash30}from"node:crypto";function digest2(value){return createHash30("sha256").update(value).digest("hex")}function hasAmbiguousSyntax(value){let single=!1,double=!1,escaped=!1;for(let character of value){if(escaped){escaped=!1;continue}if(character==="\\"){escaped=!0;continue}if(character==="'"&&!double)single=!single;if(character==='"'&&!single)double=!double}return single||double||escaped||/<<[-]?\s*\w+/.test(value)||/\$\(|`|\$\{?|\$IFS\b/i.test(value)}function matchRule(rules,segment){for(let rule of rules)if(rule.pattern.test(segment))return rule;return null}function classifySegment(segment,ambiguous){let bounded=segment.slice(0,MAX_EVIDENCE_CHARS),catastrophic=matchRule(CATASTROPHIC,segment);if(catastrophic)return{segment:bounded,category:"catastrophic",reason:catastrophic.reason??catastrophic.pattern.source,ruleId:catastrophic.id};let destructive=matchRule(DESTRUCTIVE,segment);if(destructive)return{segment:bounded,category:"destructive",reason:destructive.reason??destructive.pattern.source,ruleId:destructive.id};if(ambiguous||/[<>]|\|\s*(?:sh|bash|zsh|fish|pwsh|powershell|cmd)\b/i.test(segment))return{segment:bounded,category:"unknown",reason:"ambiguous shell syntax"};let escalate=matchRule(ESCALATE,segment);if(escalate)return{segment:bounded,category:"escalate",reason:escalate.reason??escalate.pattern.source,ruleId:escalate.id};let safe=matchRule(SAFE,segment);if(safe)return{segment:bounded,category:"safe",reason:safe.reason??safe.pattern.source,ruleId:safe.id};return{segment:bounded,category:"unknown",reason:"command is not in the bounded classifier corpus"}}function getSharedClassifierGuardrailBlock(classification){if(classification.aggregate!=="catastrophic"&&classification.aggregate!=="destructive")return null;for(let segment of classification.segments){if(segment.category!==classification.aggregate||typeof segment.ruleId!=="string")continue;let rule=BLOCK_RULES_BY_ID.get(segment.ruleId);if(!rule?.liveGuardrail||rule.liveGuardrail.mode!=="immediate-block")continue;return Object.freeze({ruleId:rule.id,category:classification.aggregate,destructiveCategory:rule.liveGuardrail.destructiveCategory,message:rule.liveGuardrail.message})}return null}function classifyCommand(original){let originalDigest=digest2(typeof original==="string"?original:String(original));if(typeof original!=="string"||original.length===0)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});if(Buffer.byteLength(original,"utf8")>MAX_COMMAND_BYTES)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});let normalized=dcNormalizeCommand(original),unwrapped=dcUnwrapWrappers(normalized),candidates=[...new Set([normalized,unwrapped,...dcSplitSegments(normalized),...dcSplitSegments(unwrapped),...dcSplitSegments(normalized).map(dcUnwrapWrappers)])];if(candidates.length===0||candidates.length>MAX_SEGMENTS)return Object.freeze({v:1,originalDigest,aggregate:"unknown",ambiguous:!0,segments:Object.freeze([])});let ambiguous=hasAmbiguousSyntax(normalized),segments=candidates.map((segment)=>classifySegment(segment.trim(),ambiguous)),aggregate=segments.reduce((highest,current)=>SEVERITY[current.category]>SEVERITY[highest]?current.category:highest,"safe"),frozenSegments=Object.freeze(segments.map((segment)=>Object.freeze(segment)));return Object.freeze({v:1,originalDigest,aggregate,ambiguous,segments:frozenSegments})}var MAX_COMMAND_BYTES=65536,MAX_SEGMENTS=128,MAX_EVIDENCE_CHARS=512,SEVERITY,CATASTROPHIC,DESTRUCTIVE,ESCALATE,SAFE,BLOCK_RULES_BY_ID;var init_command_classifier=__esm(()=>{init_destructive_command();SEVERITY={safe:0,escalate:1,unknown:2,destructive:3,catastrophic:4},CATASTROPHIC=[{id:"fork-bomb",pattern:/:\s*\(\s*\)\s*\{[^}]*\|[^}]*:/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"fork bomb",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"power-control",pattern:/\b(?:shutdown|reboot|halt|poweroff)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"system shutdown",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"mkfs-suffixed",pattern:/\bmkfs[./]/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"diskpart",pattern:/^diskpart(?:\.exe)?$/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"format-drive",pattern:/^format\s+[A-Za-z]:/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"disk format",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"vssadmin-delete",pattern:/^vssadmin(?:\.exe)?\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"wbadmin-delete",pattern:/^wbadmin(?:\.exe)?\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"bcdedit-delete",pattern:/^bcdedit(?:\.exe)?\s+\/delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"boot configuration delete",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}},{id:"dd-data-wipe",pattern:/\bdd\b[^\n]*(?:of=\s*(?:\/dev\/|[A-Za-z]:)|if=\s*\/dev\/(?:zero|random|urandom))/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "dd" with destructive data-wipe parameters detected by the shared command classifier; critic approval cannot waive this policy'}},{id:"git-push-force",pattern:/\bgit\s+push\b[^\n]*(?:--force(?!-with-lease)|\s-f\b)/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"force push",message:"BLOCKED: Force push detected — git push --force is not allowed (use --force-with-lease instead)"}},{id:"curl-pipe-shell",pattern:/\b(?:curl|wget)\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"script pipe execution",message:"BLOCKED: catastrophic shell operation detected by the shared command classifier; critic approval cannot waive this policy"}}],DESTRUCTIVE=[{id:"git-reset-hard",pattern:/\bgit\s+(?:-C\s+\S+\s+)?reset\s+--hard\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git reset",message:'BLOCKED: "git reset --hard" detected — use --soft or --mixed with caution'}},{id:"git-reset-mixed-target",pattern:/\bgit\s+(?:-C\s+\S+\s+)?reset\s+--mixed\s+\S+/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git reset",message:'BLOCKED: "git reset --mixed" with a target branch/commit is not allowed'}},{id:"git-clean-force",pattern:/\bgit\s+(?:-C\s+\S+\s+)?clean\s+-[^\s]*[fdx]/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"git clean",message:'BLOCKED: "git clean -fd" detected — permanently deletes untracked files and directories'}},{id:"rm-recursive",pattern:/\brm\b[^\n]*(?:-[^\s]*[rf]|--recursive|--force)/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive delete",message:"target-aware recursive delete"}},{id:"windows-recursive-delete",pattern:/\b(?:rmdir|rd|del)(?:\.exe)?\b[^\n]*\/[sqf]/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive delete",message:"target-aware Windows recursive delete"}},{id:"powershell-recursive-delete",pattern:/\bRemove-Item\b[^\n]*(?:-Recurse|-Force)/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"recursive remove",message:"target-aware PowerShell recursive delete"}},{id:"find-delete",pattern:/\bfind\b[^\n]*\s-delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"find delete",message:'BLOCKED: "find -delete" detected — dynamic delete expansion is not allowed from shell commands'}},{id:"rsync-delete",pattern:/\brsync\b[^\n]*--delete(?:-after|-before|-during|-delay)?\b/i,liveGuardrail:{mode:"target-aware",destructiveCategory:"rsync delete",message:"target-aware rsync delete"}},{id:"docker-system-prune",pattern:/\bdocker\s+system\s+prune\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"docker prune",message:'BLOCKED: "docker system prune" detected — destructive container operation'}},{id:"kubectl-delete",pattern:/\bkubectl\s+delete\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"kubectl delete",message:'BLOCKED: "kubectl delete" detected — destructive cluster operation'}},{id:"sql-drop",pattern:/\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"sql drop",message:"BLOCKED: SQL DROP command detected — destructive database operation"}},{id:"sql-truncate",pattern:/\bTRUNCATE\s+TABLE\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"sql truncate",message:"BLOCKED: SQL TRUNCATE command detected — destructive database operation"}},{id:"sed-config-rewrite",pattern:/\bsed\s+-i\b[^\n]*(?:biome\.json|oxlintrc|eslint)/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"config rewrite",message:"BLOCKED: in-place configuration rewrite detected — protected lint or policy config edit matched the shared command classifier"}},{id:"sdelete",pattern:/^sdelete(?:\.exe)?\s+/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"secure delete",message:'BLOCKED: "sdelete" detected — secure file deletion (Sysinternals)'}},{id:"fsutil-destructive",pattern:/^fsutil(?:\.exe)?\s+(?:reparsepoint\s+delete|file\s+setzerodata)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "fsutil" destructive subcommand detected'}},{id:"takeown-recursive",pattern:/^takeown(?:\.exe)?\s+.*\/[rR]\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"ownership takeover",message:'BLOCKED: "takeown /R" (recursive ownership takeover) detected — often precedes destructive operations'}},{id:"cipher-wipe",pattern:/^cipher(?:\.exe)?\s+\/[wW]\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"data wipe",message:'BLOCKED: "cipher /w" detected — overwrites free disk space (data wipe operation)'}},{id:"robocopy-mirror",pattern:/^robocopy(?:\.exe)?\s+.*\/(?:MIR|mir)\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"mirror sync",message:'BLOCKED: "robocopy /MIR" (mirror) detected — can delete files in the destination that do not exist in the source'}},{id:"chmod-permission-wipe",pattern:/^chmod\s+.*-[rR]\b.*000\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"permission wipe",message:'BLOCKED: "chmod -R 000" detected — removes all permissions recursively'}},{id:"chattr-immutable",pattern:/^chattr\s+.*\+i\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"immutable flag",message:'BLOCKED: "chattr +i" detected — makes files immutable'}},{id:"icacls-deny",pattern:/^icacls(?:\.exe)?\s+.*\/deny\b/i,liveGuardrail:{mode:"immediate-block",destructiveCategory:"permission deny",message:'BLOCKED: "icacls /deny" detected — denies filesystem permissions'}}],ESCALATE=[{id:"sudo-network-permissions",pattern:/\b(?:sudo|chmod|chown|curl|wget|ssh|scp|sftp|nc|netcat)\b/i},{id:"dynamic-eval",pattern:/\b(?:eval|Invoke-Expression|iex)\b/i}],SAFE=[{id:"safe-readonly-shell",pattern:/^(?:cat|head|tail|file|stat|wc|sort|uniq|cut|grep|rg|ag|ls|pwd|whoami|hostname|uname|date|which|type|tree)\b/i},{id:"safe-readonly-git",pattern:/^git\s+(?:-C\s+\S+\s+)?(?:status|log|show|diff|branch|describe|rev-parse|rev-list|ls-files|remote\s+-v)\b/i},{id:"safe-shell-builtin",pattern:/^(?:true|false|test|echo|printf)\b/i},{id:"safe-package-scripts",pattern:/^(?:bun|npm|yarn|pnpm)\s+(?:run\s+(?:typecheck|lint|test|build)|test|typecheck|lint)\b/i}],BLOCK_RULES_BY_ID=new Map([...CATASTROPHIC,...DESTRUCTIVE].map((rule)=>[rule.id,rule]))});import*as path58 from"node:path";function normalizeProtectedPath(value){return value.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function equalsOrDescendant(candidate,protectedPath){let left=process.platform==="win32"?candidate.toLowerCase():candidate,right=process.platform==="win32"?protectedPath.toLowerCase():protectedPath;return left===right||left.startsWith(`${right}/`)}function isPolicyProtectedPath(filePath,options={}){if(!filePath)return!1;let normalized=normalizeProtectedPath(filePath),segments=normalized.split("/").filter(Boolean);if(options.includeDefaults!==!1){if(segments.some((segment)=>DEFAULT_SEGMENTS.has(process.platform==="win32"?segment.toLowerCase():segment)))return!0;if(DEFAULT_PREFIXES.some((prefix)=>equalsOrDescendant(normalized,prefix)))return!0}return(options.additional??[]).some((entry)=>{let protectedPath=normalizeProtectedPath(entry);if(!protectedPath)return!1;if(equalsOrDescendant(normalized,protectedPath))return!0;if(protectedPath.includes("/"))return!1;return segments.some((segment)=>(process.platform==="win32"?segment.toLowerCase():segment)===(process.platform==="win32"?protectedPath.toLowerCase():protectedPath))})}function protectedRoots(projectRoot,additional=[]){return[...DEFAULT_PREFIXES,...DEFAULT_SEGMENTS,...additional].map((entry)=>path58.resolve(projectRoot,entry))}var DEFAULT_SEGMENTS,DEFAULT_PREFIXES,DEFAULT_PROTECTED_PATH_PREFIXES;var init_protected_path_policy=__esm(()=>{DEFAULT_SEGMENTS=new Set([".git",".swarm",".env","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","CODEOWNERS"]),DEFAULT_PREFIXES=[".github/workflows",".github/CODEOWNERS","src/sandbox","src/hooks/guardrails","src/security","src/evaluation","docs/releases","tests/fixtures/evaluation"],DEFAULT_PROTECTED_PATH_PREFIXES=DEFAULT_PREFIXES});class Reader{src;pos=0;constructor(src){this.src=src}eof(){return this.pos>=this.src.length}peek(){return this.src[this.pos]??""}skipWs(){while(!this.eof()&&WHITESPACE.test(this.peek()))this.pos+=1}eat(ch){if(this.peek()===ch)return this.pos+=1,!0;return!1}eatWord(word){if(!this.src.startsWith(word,this.pos))return!1;let next=this.src[this.pos+word.length]??"";if(next!==""&&IDENT_PART.test(next))return!1;return this.pos+=word.length,!0}ident(){if(!IDENT_START.test(this.peek()))return null;let start=this.pos;this.pos+=1;while(!this.eof()&&IDENT_PART.test(this.peek()))this.pos+=1;return this.src.slice(start,this.pos)}string(){let quote=this.peek();if(quote!=='"'&"e!=="'")return null;this.pos+=1;let out="";while(!this.eof()){let ch=this.peek();if(this.pos+=1,ch===quote)return out;if(ch===`
|
|
708
|
-
`||ch==="\r")return null;if(ch==="\\"){let esc2=this.peek();if(!SIMPLE_ESCAPES.has(esc2))return null;this.pos+=1,out+=esc2;continue}out+=ch}return null}number(){let m=/^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(this.src.slice(this.pos));if(!m)return!1;return this.pos+=m[0].length,!0}}function parseValue(r,depth){if(depth>8)return!1;r.skipWs();let ch=r.peek();if(ch==='"'||ch==="'")return r.string()!==null;if(ch==="{")return parseObject(r,depth+1);if(ch==="[")return parseArray(r,depth+1);if(r.eatWord("true")||r.eatWord("false")||r.eatWord("null"))return!0;return r.number()}function parseArray(r,depth){if(!r.eat("["))return!1;if(r.skipWs(),r.eat("]"))return!0;for(;;){if(!parseValue(r,depth))return!1;if(r.skipWs(),r.eat(",")){if(r.skipWs(),r.eat("]"))return!0;continue}return r.eat("]")}}function parseObject(r,depth){if(!r.eat("{"))return!1;if(r.skipWs(),r.eat("}"))return!0;for(;;){r.skipWs();let key=r.peek()==='"'||r.peek()==="'"?r.string():r.ident();if(key===null||BLOCKED_NAMES.has(key))return!1;if(r.skipWs(),!r.eat(":"))return!1;if(!parseValue(r,depth))return!1;if(r.skipWs(),r.eat(",")){if(r.skipWs(),r.eat("}"))return!0;continue}return r.eat("}")}}function parseCallee(r){if(r.eatWord("search"))return!0;if(!r.eatWord("tools"))return!1;let segments=0;for(;;){if(r.skipWs(),r.eat(".")){r.skipWs();let name=r.ident();if(name===null||BLOCKED_NAMES.has(name))return!1;segments+=1;continue}if(r.peek()==="["){r.pos+=1,r.skipWs();let name=r.string();if(r.skipWs(),name===null||!SEGMENT_NAME.test(name)||BLOCKED_NAMES.has(name)||!r.eat("]"))return!1;segments+=1;continue}return segments>0}}function isSingleToolCallProgram(code){if(typeof code!=="string")return!1;if(code.length===0||code.length>20000)return!1;let r=new Reader(code);if(r.skipWs(),r.eatWord("return"),r.skipWs(),r.eatWord("await"),r.skipWs(),!parseCallee(r))return!1;if(r.skipWs(),!r.eat("("))return!1;if(r.skipWs(),!r.eat(")")){if(!parseValue(r,0))return!1;if(r.skipWs(),!r.eat(")"))return!1}return r.skipWs(),r.eat(";"),r.skipWs(),r.eof()}var BLOCKED_NAMES,IDENT_START,IDENT_PART,SEGMENT_NAME,WHITESPACE,SIMPLE_ESCAPES;var init_code_mode_program=__esm(()=>{BLOCKED_NAMES=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]),IDENT_START=/[A-Za-z_$]/,IDENT_PART=/[A-Za-z0-9_$]/,SEGMENT_NAME=/^[A-Za-z0-9_-]{1,100}$/,WHITESPACE=/[ \t\r\n]/,SIMPLE_ESCAPES=new Set(["n","r","t",'"',"'","\\","/"])});import*as fs33 from"node:fs";import*as path59 from"node:path";function isReadOnlyTool(toolName){if(!toolName)return!1;return READ_ONLY_TOOLS.has(toolName.toLowerCase())}function isWriteLikeTool(toolName){if(!toolName)return!1;return WRITE_LIKE_TOOLS.has(toolName.toLowerCase())}function isSubagentDelegation(toolName,args2){if(isTaskToolId(toolName)&&args2&&typeof args2==="object")return!0;let lower=normalizeToolNameLowerCase(toolName??"");return SUBAGENT_TOOLS.has(lower)}function isWithinDirectory(target,root){if(!target||!root)return!1;let resolvedTarget=path59.resolve(target),resolvedRoot=path59.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path59.sep)?resolvedRoot:resolvedRoot+path59.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}function isProtectedPath2(filePath,config2){if(!filePath)return!1;let normalized=normalizePath(filePath);for(let prefix of ALWAYS_PROTECTED_PREFIXES){let np=normalizePath(prefix);if(normalized===np||normalized.startsWith(`${np}/`))return!0}let allowDefaults=config2?.permission_policy?.allow_defaults!==!1;return isPolicyProtectedPath(normalized,{includeDefaults:allowDefaults,additional:[...allowDefaults?PROTECTED_PATH_DEFAULTS:[],...config2?.permission_policy?.protected_paths??[]]})}function classifyPathRisk(filePath,context){if(!filePath)return{withinProjectRoot:!1,withinDeclaredScope:null,protected:!1,highRiskBuild:!1};let absolute=path59.isAbsolute(filePath)?filePath:path59.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs33.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs33.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path59.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative14=normalizePath(path59.relative(context.directory,absolute)),withinDeclaredScope=null;if(Array.isArray(context.declaredScope))withinDeclaredScope=context.declaredScope.length===0?!1:context.declaredScope.some((scope)=>{let s=normalizePath(scope);if(!s)return!1;return relative14===s||relative14.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative14.startsWith(e);return relative14===e||relative14.startsWith(`${e}/`)});return{withinProjectRoot,withinDeclaredScope,protected:!1,highRiskBuild}}function classifyCommandRisk(command,_cwd,_context){if(FULL_AUTO_SECRET_READ_PATTERN.test(command)||FULL_AUTO_SECRET_ENV_PATTERN.test(command)||FULL_AUTO_PRIMARY_PUSH_PATTERN.test(command))return{decision:"deny",reason:"full-auto consumer policy: command reads secrets or targets a primary branch push"};let classification=classifyCommand(command);if(classification.aggregate==="catastrophic"||classification.aggregate==="destructive")return{decision:"deny",reason:`shared classifier: ${classification.aggregate}`};if(classification.aggregate==="safe")return{decision:"allow",reason:"shared classifier: safe"};return{decision:"escalate_critic",reason:`shared classifier: ${classification.aggregate}`}}function extractPathArgs(toolName,args2){if(!args2||typeof args2!=="object")return[];let found=[];for(let key of PATH_ARG_KEYS){let v=args2[key];if(typeof v==="string"&&v.trim())found.push(v)}let filesArg=args2.files;if(Array.isArray(filesArg)){for(let f of filesArg)if(typeof f==="string"&&f.trim())found.push(f);else if(f&&typeof f==="object"&&typeof f.path==="string")found.push(f.path)}let editsArg=args2.edits;if(Array.isArray(editsArg)){for(let e of editsArg)if(e&&typeof e==="object"&&typeof e.file_path==="string")found.push(e.file_path)}if(toolName==="declare_scope"&&Array.isArray(args2.files));return found}function extractCommandArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.command==="string"&&args2.command||typeof args2.cmd==="string"&&args2.cmd||typeof args2.script==="string"&&args2.script||void 0}function extractURLArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.url==="string"&&args2.url||typeof args2.uri==="string"&&args2.uri||typeof args2.endpoint==="string"&&args2.endpoint||void 0}function isTrustedDomain(url2,config2){let domains=config2?.permission_policy?.trusted_domains??[];if(domains.length===0)return!1;let host="";try{host=new URL(url2).hostname.toLowerCase()}catch{return!1}return domains.some((d)=>{let dl=d.toLowerCase();return host===dl||host.endsWith(`.${dl}`)})}function resolveAgentCapabilityTools(roleName,pluginConfig){let tools=pluginConfig?.tool_filter?.overrides?.[roleName]??AGENT_TOOL_MAP[roleName]??[];if(pluginConfig?.memory?.enabled===!0)tools=Array.from(new Set([...tools,...MEMORY_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.external_skills?.curation_enabled===!0)tools=Array.from(new Set([...tools,...EXTERNAL_SKILL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.enabled===!0)tools=Array.from(new Set([...tools,...COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.general?.enabled===!0)tools=Array.from(new Set([...tools,...GENERAL_COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.turbo!==void 0)tools=Array.from(new Set([...tools,...TURBO_AGENT_TOOL_MAP[roleName]??[]]));if(isEpicModeConfigEnabled(pluginConfig))tools=Array.from(new Set([...tools,...EPIC_AGENT_TOOL_MAP[roleName]??[]]));let skillTools=SKILL_AGENT_TOOL_MAP[roleName]??[];if(skillTools.length>0)if(pluginConfig?.skills?.enabled===!0)tools=Array.from(new Set([...tools,...skillTools]));else{let skillSet=new Set(skillTools);tools=tools.filter((tool)=>!skillSet.has(tool))}if(pluginConfig?.skills?.enabled!==!0&&roleName!=="skill_improver"){let allSkillTools=new Set(SKILL_TOOL_NAMES);tools=tools.filter((tool)=>!allSkillTools.has(tool))}return tools}function resolveDelegationRisk(input,subagentName){let role=input.generatedAgentNames&&input.generatedAgentNames.length>0?resolveGeneratedAgentRole(subagentName,input.generatedAgentNames):getCanonicalAgentRole(subagentName);if(!isKnownCanonicalRole(role))return{risk:"high",reason:"subagent role is unknown or not registry-backed",role,tools:[],safeReadOnly:!1};let tools=resolveAgentCapabilityTools(role,input.pluginConfig);if(tools.length===0)return{risk:"high",reason:"subagent has no registered capability map",role,tools,safeReadOnly:!1};let dangerous=tools.some((tool)=>isWriteLikeTool(tool)||SHELL_TOOLS.has(tool)||NETWORK_TOOLS.has(tool)||tool==="swarm_command"||tool==="Task"||tool==="task"),unknown2=tools.some((tool)=>!isReadOnlyTool(tool)&&!isWriteLikeTool(tool)&&!SHELL_TOOLS.has(tool)&&!NETWORK_TOOLS.has(tool)&&tool!=="swarm_command");if(dangerous||unknown2)return{risk:"high",reason:dangerous?"delegated role can write, execute, publish, or recurse":"delegated role exposes non-read-only unknown capabilities",role,tools,safeReadOnly:!1};return{risk:"medium",reason:"delegated role is limited to registered read-only capabilities",role,tools,safeReadOnly:!0}}function classifyFullAutoToolAction(input){let tool=input.toolName?.toLowerCase()??"",config2=input.fullAutoConfig,mode=config2?.mode??"supervised";if(!(mode==="strict"||config2?.permission_policy?.enabled!==!1))return{action:"allow",reason:"permission policy disabled by config",tier:"local"};if(isReadOnlyTool(tool))return{action:"allow",reason:"read-only tool",tier:"safe"};if(tool==="execute"&&config2?.permission_policy?.trust_code_mode_wrapper===!0&&input.hostCodeModeWrapper===!0&&isSingleToolCallProgram(input.args?.code))return{action:"allow",reason:"OpenCode v2 Code Mode wrapper around a single tool call (operator-trusted) — the nested call is classified individually",tier:"local"};if(tool==="swarm_command"&&mode!=="strict"&&input.swarmCommandReadOnly===!0)return{action:"allow",reason:"swarm_command is on the explicit read-only allowlist and permitted by the tool policy",tier:"local"};if(isSubagentDelegation(tool,input.args)){let subagentName=typeof input.args?.subagent_type==="string"&&input.args.subagent_type||typeof input.args?.agent==="string"&&input.args.agent||"unknown",delegationRisk=resolveDelegationRisk(input,subagentName);if(mode!=="strict"&&delegationRisk.safeReadOnly)return{action:"allow",reason:`read-only subagent delegation allowed (${delegationRisk.role})`,tier:"local"};return{action:"escalate_critic",reason:`subagent delegation requires plan/scope verification (${delegationRisk.reason})`,risk:mode==="strict"?"high":delegationRisk.risk,context:{tool,subagent:subagentName,canonicalRole:delegationRisk.role,registeredTools:delegationRisk.tools,currentTaskID:input.currentTaskID,currentPhase:input.currentPhase}}}if(tool==="phase_complete")return{action:"escalate_critic",reason:"phase_complete requires Full-Auto approval evidence",risk:"high",context:{tool,currentPhase:input.currentPhase}};if(tool==="update_task_status"){let status=typeof input.args?.status==="string"&&input.args.status||"";if(status==="completed"){if(mode==="strict"||config2?.oversight?.on_task_completion===!0)return{action:"escalate_critic",reason:"task completion requires Full-Auto critic verification",risk:"medium",context:{tool,status}}}else{if(mode==="strict")return{action:"escalate_critic",reason:`strict mode: update_task_status with status=${status} requires critic verification`,risk:"medium",context:{tool,status}};return{action:"allow",reason:`update_task_status with status=${status} is a routine state change`,tier:"local"}}}if(tool==="save_plan")return{action:"escalate_critic",reason:"plan mutation requires Full-Auto critic verification",risk:"high",context:{tool}};if(NETWORK_TOOLS.has(tool)){let url2=extractURLArg(input.args);if(url2&&isTrustedDomain(url2,config2))return{action:"allow",reason:"network tool with trusted domain",tier:"local"};return{action:"escalate_critic",reason:"network/web tool — verify intent and target",risk:"medium",context:{tool,url:url2}}}if(SHELL_TOOLS.has(tool)){let command=extractCommandArg(input.args);if(!command)return{action:"deny",reason:"shell tool invoked without a command argument",code:"shell_no_command",recoverable:!0};let cmdRisk=classifyCommandRisk(command,input.workingDirectory??"",{directory:input.directory});if(cmdRisk.decision==="deny")return{action:"deny",reason:cmdRisk.reason,code:"shell_deny",recoverable:!0};if(cmdRisk.decision==="allow")return{action:"allow",reason:cmdRisk.reason,tier:"local"};return{action:"escalate_critic",reason:cmdRisk.reason,risk:"medium",context:{tool,command}}}if(isWriteLikeTool(tool)||tool==="patch"||tool==="edit"){let paths=extractPathArgs(tool,input.args);if(paths.length===0){if(new Set(["declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine"]).has(tool))return{action:"allow",reason:`pathless plan/evidence tool '${tool}' allowed under Full-Auto`,tier:"local"};return{action:"escalate_critic",reason:"write-like tool without explicit path — verify side effects",risk:"medium",context:{tool,args:input.args}}}for(let p of paths){let risk=classifyPathRisk(p,{directory:input.directory,declaredScope:input.declaredScope??null});if(!risk.withinProjectRoot)return{action:"deny",reason:`write target outside project root: ${p}`,code:"path_out_of_root",recoverable:!0};if(isProtectedPath2(path59.relative(input.directory,path59.resolve(input.directory,p)),config2))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool}}}function buildStructuredDenial(decision,tool){return{full_auto_denial:!0,tool,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}var READ_ONLY_TOOLS,WRITE_LIKE_TOOLS,SHELL_TOOLS,NETWORK_TOOLS,SUBAGENT_TOOLS,HIGH_RISK_BUILD_PATHS,ALWAYS_PROTECTED_PREFIXES,PROTECTED_PATH_DEFAULTS,FULL_AUTO_SECRET_READ_PATTERN,FULL_AUTO_SECRET_ENV_PATTERN,FULL_AUTO_PRIMARY_PUSH_PATTERN,PATH_ARG_KEYS;var init_policy=__esm(()=>{init_constants();init_schema();init_config();init_normalize_tool_name();init_command_classifier();init_protected_path_policy();init_path();init_code_mode_program();READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine","suggest_patch"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","gitingest"]),SUBAGENT_TOOLS=new Set(["agent","delegate"]),HIGH_RISK_BUILD_PATHS=["src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto/","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"];FULL_AUTO_SECRET_READ_PATTERN=/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)\b/i,FULL_AUTO_SECRET_ENV_PATTERN=/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,FULL_AUTO_PRIMARY_PUSH_PATTERN=/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i;PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"]});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals57});import{existsSync as existsSync30,statSync as statSync19}from"node:fs";import*as path60 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{Language,Parser as TreeSitterParser}from"web-tree-sitter";async function initTreeSitter(){if(!treeSitterInitPromise)treeSitterInitPromise=(async()=>{if(_internals57.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals57.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path60.join(grammarsDir,"tree-sitter.wasm");if(!_internals57.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
|
|
708
|
+
`||ch==="\r")return null;if(ch==="\\"){let esc2=this.peek();if(!SIMPLE_ESCAPES.has(esc2))return null;this.pos+=1,out+=esc2;continue}out+=ch}return null}number(){let m=/^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(this.src.slice(this.pos));if(!m)return!1;return this.pos+=m[0].length,!0}}function parseValue(r,depth){if(depth>8)return!1;r.skipWs();let ch=r.peek();if(ch==='"'||ch==="'")return r.string()!==null;if(ch==="{")return parseObject(r,depth+1);if(ch==="[")return parseArray(r,depth+1);if(r.eatWord("true")||r.eatWord("false")||r.eatWord("null"))return!0;return r.number()}function parseArray(r,depth){if(!r.eat("["))return!1;if(r.skipWs(),r.eat("]"))return!0;for(;;){if(!parseValue(r,depth))return!1;if(r.skipWs(),r.eat(",")){if(r.skipWs(),r.eat("]"))return!0;continue}return r.eat("]")}}function parseObject(r,depth){if(!r.eat("{"))return!1;if(r.skipWs(),r.eat("}"))return!0;for(;;){r.skipWs();let key=r.peek()==='"'||r.peek()==="'"?r.string():r.ident();if(key===null||BLOCKED_NAMES.has(key))return!1;if(r.skipWs(),!r.eat(":"))return!1;if(!parseValue(r,depth))return!1;if(r.skipWs(),r.eat(",")){if(r.skipWs(),r.eat("}"))return!0;continue}return r.eat("}")}}function parseCallee(r){if(r.eatWord("search"))return!0;if(!r.eatWord("tools"))return!1;let segments=0;for(;;){if(r.skipWs(),r.eat(".")){r.skipWs();let name=r.ident();if(name===null||BLOCKED_NAMES.has(name))return!1;segments+=1;continue}if(r.peek()==="["){r.pos+=1,r.skipWs();let name=r.string();if(r.skipWs(),name===null||!SEGMENT_NAME.test(name)||BLOCKED_NAMES.has(name)||!r.eat("]"))return!1;segments+=1;continue}return segments>0}}function isSingleToolCallProgram(code){if(typeof code!=="string")return!1;if(code.length===0||code.length>20000)return!1;let r=new Reader(code);if(r.skipWs(),r.eatWord("return"),r.skipWs(),r.eatWord("await"),r.skipWs(),!parseCallee(r))return!1;if(r.skipWs(),!r.eat("("))return!1;if(r.skipWs(),!r.eat(")")){if(!parseValue(r,0))return!1;if(r.skipWs(),!r.eat(")"))return!1}return r.skipWs(),r.eat(";"),r.skipWs(),r.eof()}var BLOCKED_NAMES,IDENT_START,IDENT_PART,SEGMENT_NAME,WHITESPACE,SIMPLE_ESCAPES;var init_code_mode_program=__esm(()=>{BLOCKED_NAMES=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]),IDENT_START=/[A-Za-z_$]/,IDENT_PART=/[A-Za-z0-9_$]/,SEGMENT_NAME=/^[A-Za-z0-9_-]{1,100}$/,WHITESPACE=/[ \t\r\n]/,SIMPLE_ESCAPES=new Set(["n","r","t",'"',"'","\\","/"])});import*as fs33 from"node:fs";import*as path59 from"node:path";function isReadOnlyTool(toolName){if(!toolName)return!1;return READ_ONLY_TOOLS.has(toolName.toLowerCase())}function isWriteLikeTool(toolName){if(!toolName)return!1;return WRITE_LIKE_TOOLS.has(toolName.toLowerCase())}function isSubagentDelegation(toolName,args2){if(isTaskToolId(toolName)&&args2&&typeof args2==="object")return!0;let lower=normalizeToolNameLowerCase(toolName??"");return SUBAGENT_TOOLS.has(lower)}function isWithinDirectory(target,root){if(!target||!root)return!1;let resolvedTarget=path59.resolve(target),resolvedRoot=path59.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path59.sep)?resolvedRoot:resolvedRoot+path59.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}function isProtectedPath2(filePath,config2){if(!filePath)return!1;let normalized=normalizePath(filePath);for(let prefix of ALWAYS_PROTECTED_PREFIXES){let np=normalizePath(prefix);if(normalized===np||normalized.startsWith(`${np}/`))return!0}let allowDefaults=config2?.permission_policy?.allow_defaults!==!1;return isPolicyProtectedPath(normalized,{includeDefaults:allowDefaults,additional:[...allowDefaults?PROTECTED_PATH_DEFAULTS:[],...config2?.permission_policy?.protected_paths??[]]})}function classifyPathRisk(filePath,context){if(!filePath)return{withinProjectRoot:!1,withinDeclaredScope:null,protected:!1,highRiskBuild:!1};let absolute=path59.isAbsolute(filePath)?filePath:path59.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs33.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs33.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path59.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative14=normalizePath(path59.relative(context.directory,absolute)),withinDeclaredScope=null;if(Array.isArray(context.declaredScope))withinDeclaredScope=context.declaredScope.length===0?!1:context.declaredScope.some((scope)=>{let s=normalizePath(scope);if(!s)return!1;return relative14===s||relative14.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative14.startsWith(e);return relative14===e||relative14.startsWith(`${e}/`)});return{withinProjectRoot,withinDeclaredScope,protected:!1,highRiskBuild}}function classifyCommandRisk(command,_cwd,_context){if(FULL_AUTO_SECRET_READ_PATTERN.test(command)||FULL_AUTO_SECRET_ENV_PATTERN.test(command)||FULL_AUTO_PRIMARY_PUSH_PATTERN.test(command))return{decision:"deny",reason:"full-auto consumer policy: command reads secrets or targets a primary branch push"};let classification=classifyCommand(command);if(classification.aggregate==="catastrophic"||classification.aggregate==="destructive")return{decision:"deny",reason:`shared classifier: ${classification.aggregate}`};if(classification.aggregate==="safe")return{decision:"allow",reason:"shared classifier: safe"};return{decision:"escalate_critic",reason:`shared classifier: ${classification.aggregate}`}}function extractPathArgs(toolName,args2){if(!args2||typeof args2!=="object")return[];let found=[];for(let key of PATH_ARG_KEYS){let v=args2[key];if(typeof v==="string"&&v.trim())found.push(v)}let filesArg=args2.files;if(Array.isArray(filesArg)){for(let f of filesArg)if(typeof f==="string"&&f.trim())found.push(f);else if(f&&typeof f==="object"&&typeof f.path==="string")found.push(f.path)}let editsArg=args2.edits;if(Array.isArray(editsArg)){for(let e of editsArg)if(e&&typeof e==="object"&&typeof e.file_path==="string")found.push(e.file_path)}if(toolName==="declare_scope"&&Array.isArray(args2.files));return found}function extractCommandArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.command==="string"&&args2.command||typeof args2.cmd==="string"&&args2.cmd||typeof args2.script==="string"&&args2.script||void 0}function extractURLArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.url==="string"&&args2.url||typeof args2.uri==="string"&&args2.uri||typeof args2.endpoint==="string"&&args2.endpoint||void 0}function isTrustedDomain(url2,config2){let domains=config2?.permission_policy?.trusted_domains??[];if(domains.length===0)return!1;let host="";try{host=new URL(url2).hostname.toLowerCase()}catch{return!1}return domains.some((d)=>{let dl=d.toLowerCase();return host===dl||host.endsWith(`.${dl}`)})}function resolveAgentCapabilityTools(roleName,pluginConfig){let tools=pluginConfig?.tool_filter?.overrides?.[roleName]??AGENT_TOOL_MAP[roleName]??[];if(pluginConfig?.memory?.enabled===!0)tools=Array.from(new Set([...tools,...MEMORY_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.external_skills?.curation_enabled===!0)tools=Array.from(new Set([...tools,...EXTERNAL_SKILL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.enabled===!0)tools=Array.from(new Set([...tools,...COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.council?.general?.enabled===!0)tools=Array.from(new Set([...tools,...GENERAL_COUNCIL_AGENT_TOOL_MAP[roleName]??[]]));if(pluginConfig?.turbo!==void 0)tools=Array.from(new Set([...tools,...TURBO_AGENT_TOOL_MAP[roleName]??[]]));if(isEpicModeConfigEnabled(pluginConfig))tools=Array.from(new Set([...tools,...EPIC_AGENT_TOOL_MAP[roleName]??[]]));let skillTools=SKILL_AGENT_TOOL_MAP[roleName]??[];if(skillTools.length>0)if(pluginConfig?.skills?.enabled===!0)tools=Array.from(new Set([...tools,...skillTools]));else{let skillSet=new Set(skillTools);tools=tools.filter((tool)=>!skillSet.has(tool))}if(pluginConfig?.skills?.enabled!==!0&&roleName!=="skill_improver"){let allSkillTools=new Set(SKILL_TOOL_NAMES);tools=tools.filter((tool)=>!allSkillTools.has(tool))}return tools}function resolveDelegationRisk(input,subagentName){let role=input.generatedAgentNames&&input.generatedAgentNames.length>0?resolveGeneratedAgentRole(subagentName,input.generatedAgentNames):getCanonicalAgentRole(subagentName);if(!isKnownCanonicalRole(role))return{risk:"high",reason:"subagent role is unknown or not registry-backed",role,tools:[],safeReadOnly:!1};let tools=resolveAgentCapabilityTools(role,input.pluginConfig);if(tools.length===0)return{risk:"high",reason:"subagent has no registered capability map",role,tools,safeReadOnly:!1};let dangerous=tools.some((tool)=>isWriteLikeTool(tool)||SHELL_TOOLS.has(tool)||NETWORK_TOOLS.has(tool)||tool==="swarm_command"||tool==="Task"||tool==="task"),unknown2=tools.some((tool)=>!isReadOnlyTool(tool)&&!isWriteLikeTool(tool)&&!SHELL_TOOLS.has(tool)&&!NETWORK_TOOLS.has(tool)&&tool!=="swarm_command");if(dangerous||unknown2)return{risk:"high",reason:dangerous?"delegated role can write, execute, publish, or recurse":"delegated role exposes non-read-only unknown capabilities",role,tools,safeReadOnly:!1};return{risk:"medium",reason:"delegated role is limited to registered read-only capabilities",role,tools,safeReadOnly:!0}}function classifyFullAutoToolAction(input){let tool=input.toolName?.toLowerCase()??"",config2=input.fullAutoConfig,mode=config2?.mode??"supervised";if(!(mode==="strict"||config2?.permission_policy?.enabled!==!1))return{action:"allow",reason:"permission policy disabled by config",tier:"local"};if(isReadOnlyTool(tool))return{action:"allow",reason:"read-only tool",tier:"safe"};if(tool==="execute"&&config2?.permission_policy?.trust_code_mode_wrapper===!0&&input.hostCodeModeWrapper===!0&&isSingleToolCallProgram(input.args?.code))return{action:"allow",reason:"OpenCode v2 Code Mode wrapper around a single tool call (operator-trusted) — the nested call is classified individually",tier:"local"};if(tool==="swarm_command"&&mode!=="strict"&&input.swarmCommandReadOnly===!0)return{action:"allow",reason:"swarm_command is on the explicit read-only allowlist and permitted by the tool policy",tier:"local"};if(isSubagentDelegation(tool,input.args)){let subagentName=typeof input.args?.subagent_type==="string"&&input.args.subagent_type||typeof input.args?.agent==="string"&&input.args.agent||"unknown",delegationRisk=resolveDelegationRisk(input,subagentName);if(mode!=="strict"&&delegationRisk.safeReadOnly)return{action:"allow",reason:`read-only subagent delegation allowed (${delegationRisk.role})`,tier:"local"};return{action:"escalate_critic",reason:`subagent delegation requires plan/scope verification (${delegationRisk.reason})`,risk:mode==="strict"?"high":delegationRisk.risk,context:{tool,subagent:subagentName,canonicalRole:delegationRisk.role,registeredTools:delegationRisk.tools,currentTaskID:input.currentTaskID,currentPhase:input.currentPhase}}}if(tool==="phase_complete")return{action:"escalate_critic",reason:"phase_complete requires Full-Auto approval evidence",risk:"high",context:{tool,currentPhase:input.currentPhase}};if(tool==="update_task_status"){let status=typeof input.args?.status==="string"&&input.args.status||"";if(status==="completed"){if(mode==="strict"||config2?.oversight?.on_task_completion===!0)return{action:"escalate_critic",reason:"task completion requires Full-Auto critic verification",risk:"medium",context:{tool,status}}}else{if(mode==="strict")return{action:"escalate_critic",reason:`strict mode: update_task_status with status=${status} requires critic verification`,risk:"medium",context:{tool,status}};return{action:"allow",reason:`update_task_status with status=${status} is a routine state change`,tier:"local"}}}if(tool==="save_plan")return{action:"escalate_critic",reason:"plan mutation requires Full-Auto critic verification",risk:"high",context:{tool}};if(NETWORK_TOOLS.has(tool)){let url2=extractURLArg(input.args);if(url2&&isTrustedDomain(url2,config2))return{action:"allow",reason:"network tool with trusted domain",tier:"local"};return{action:"escalate_critic",reason:"network/web tool — verify intent and target",risk:"medium",context:{tool,url:url2}}}if(SHELL_TOOLS.has(tool)){let command=extractCommandArg(input.args);if(!command)return{action:"deny",reason:"shell tool invoked without a command argument",code:"shell_no_command",recoverable:!0};let cmdRisk=classifyCommandRisk(command,input.workingDirectory??"",{directory:input.directory});if(cmdRisk.decision==="deny")return{action:"deny",reason:cmdRisk.reason,code:"shell_deny",recoverable:!0};if(cmdRisk.decision==="allow")return{action:"allow",reason:cmdRisk.reason,tier:"local"};return{action:"escalate_critic",reason:cmdRisk.reason,risk:"medium",context:{tool,command}}}if(isWriteLikeTool(tool)||tool==="patch"||tool==="edit"){let paths=extractPathArgs(tool,input.args);if(paths.length===0){if(new Set(["declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine"]).has(tool))return{action:"allow",reason:`pathless plan/evidence tool '${tool}' allowed under Full-Auto`,tier:"local"};return{action:"escalate_critic",reason:"write-like tool without explicit path — verify side effects",risk:"medium",context:{tool,args:input.args}}}for(let p of paths){let risk=classifyPathRisk(p,{directory:input.directory,declaredScope:input.declaredScope??null});if(!risk.withinProjectRoot)return{action:"deny",reason:`write target outside project root: ${p}`,code:"path_out_of_root",recoverable:!0};if(isProtectedPath2(path59.relative(input.directory,path59.resolve(input.directory,p)),config2))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool}}}function buildStructuredDenial(decision,tool){return{full_auto_denial:!0,tool,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}var FULL_AUTO_AUDITED_READ_ONLY_SWARM_TOOLS,READ_ONLY_TOOLS,WRITE_LIKE_TOOLS,SHELL_TOOLS,NETWORK_TOOLS,SUBAGENT_TOOLS,HIGH_RISK_BUILD_PATHS,ALWAYS_PROTECTED_PREFIXES,PROTECTED_PATH_DEFAULTS,FULL_AUTO_SECRET_READ_PATTERN,FULL_AUTO_SECRET_ENV_PATTERN,FULL_AUTO_PRIMARY_PUSH_PATTERN,PATH_ARG_KEYS;var init_policy=__esm(()=>{init_constants();init_schema();init_config();init_normalize_tool_name();init_command_classifier();init_protected_path_policy();init_path();init_code_mode_program();FULL_AUTO_AUDITED_READ_ONLY_SWARM_TOOLS=["skill_list","skill_inspect","external_skill_list","external_skill_inspect","knowledge_receipt_status","retrieve_lane_output","lean_turbo_plan_lanes","plan_conflict_check","scope_validate","context_status","suggest_patch"],READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),...FULL_AUTO_AUDITED_READ_ONLY_SWARM_TOOLS,"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","gitingest"]),SUBAGENT_TOOLS=new Set(["agent","delegate"]),HIGH_RISK_BUILD_PATHS=["src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto/","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"];FULL_AUTO_SECRET_READ_PATTERN=/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)\b/i,FULL_AUTO_SECRET_ENV_PATTERN=/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,FULL_AUTO_PRIMARY_PUSH_PATTERN=/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i;PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"]});var exports_runtime={};__export(exports_runtime,{resolveGrammarsDir:()=>resolveGrammarsDir,parserCache:()=>parserCache,loadGrammar:()=>loadGrammar,isGrammarAvailable:()=>isGrammarAvailable,getSupportedLanguages:()=>getSupportedLanguages,getInitializedLanguages:()=>getInitializedLanguages,clearParserCache:()=>clearParserCache,_internals:()=>_internals57});import{existsSync as existsSync30,statSync as statSync19}from"node:fs";import*as path60 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{Language,Parser as TreeSitterParser}from"web-tree-sitter";async function initTreeSitter(){if(!treeSitterInitPromise)treeSitterInitPromise=(async()=>{if(_internals57.getModuleDir().replace(/\\/g,"/").endsWith("/src/lang"))await _internals57.parserInit();else{let grammarsDir=getGrammarsDirAbsolute(),coreWasmPath=path60.join(grammarsDir,"tree-sitter.wasm");if(!_internals57.fileExists(coreWasmPath))throw Error(`Core tree-sitter WASM runtime missing: ${coreWasmPath}
|
|
709
709
|
The installed OpenCode plugin cache is incomplete or stale. Run 'bunx opencode-swarm update', then restart OpenCode so it fetches a fresh package from npm.`);await _internals57.parserInit({locateFile(scriptName){return path60.join(grammarsDir,scriptName)}})}})().catch((err)=>{throw treeSitterInitPromise=null,err});return treeSitterInitPromise}function sanitizeLanguageId(languageId){let normalized=languageId.toLowerCase();if(!/^[a-z0-9-]+$/.test(normalized))throw Error(`Invalid language ID: ${languageId}`);return normalized}function getWasmFileName(languageId){let sanitized=sanitizeLanguageId(languageId).toLowerCase();if(LANGUAGE_WASM_MAP[sanitized])return LANGUAGE_WASM_MAP[sanitized];return`tree-sitter-${sanitized}.wasm`}function resolveGrammarsDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/lang"),isCliBundle=normalized.endsWith("/cli");return isSource?path60.join(thisDir,"grammars"):isCliBundle?path60.join(thisDir,"..","lang","grammars"):path60.join(thisDir,"lang","grammars")}function getGrammarsDirAbsolute(){let thisDir=_internals57.getModuleDir();return resolveGrammarsDir(thisDir)}async function loadGrammar(languageId){if(typeof languageId!=="string"||languageId.length>100)throw Error("Invalid languageId: must be a string of at most 100 characters");let normalizedId=sanitizeLanguageId(languageId).toLowerCase();if(normalizedId.length===0)throw Error("Invalid languageId: empty after sanitization");if(parserCache.has(normalizedId))return parserCache.get(normalizedId);let existing=inflightLoads.get(normalizedId);if(existing)return existing;let loadPromise=(async()=>{await initTreeSitter();let parser=new TreeSitterParser,wasmFileName=getWasmFileName(normalizedId),wasmPath=path60.join(getGrammarsDirAbsolute(),wasmFileName);if(!_internals57.fileExists(wasmPath))throw Error(`Grammar file not found for ${languageId}: ${wasmPath}
|
|
710
710
|
Make sure to run 'bun run build' to copy grammar files to dist/lang/grammars/. If this is an installed OpenCode plugin cache, run 'bunx opencode-swarm update' and restart OpenCode.`);try{let language=await withTimeout(Language.load(wasmPath),GRAMMAR_LOAD_TIMEOUT_MS,Error(`Timed out after ${GRAMMAR_LOAD_TIMEOUT_MS}ms loading grammar`));parser.setLanguage(language)}catch(error49){throw Error(`Failed to load grammar for ${languageId}: ${error49 instanceof Error?error49.message:String(error49)}
|
|
711
711
|
WASM path: ${wasmPath}`)}return parserCache.set(normalizedId,parser),initializedLanguages.add(normalizedId),parser})();inflightLoads.set(normalizedId,loadPromise);try{return await loadPromise}finally{inflightLoads.delete(normalizedId)}}async function isGrammarAvailable(languageId){if(typeof languageId!=="string"||languageId.length>100)return!1;let normalizedId;try{normalizedId=sanitizeLanguageId(languageId).toLowerCase()}catch{return!1}if(normalizedId.length===0)return!1;if(parserCache.has(normalizedId))return!0;try{let wasmFileName=getWasmFileName(normalizedId),wasmPath=path60.join(getGrammarsDirAbsolute(),wasmFileName);return statSync19(wasmPath),!0}catch{return!1}}function clearParserCache(){parserCache.clear(),inflightLoads.clear(),initializedLanguages.clear(),treeSitterInitPromise=null}function getInitializedLanguages(){return Array.from(initializedLanguages)}function getSupportedLanguages(){return Object.keys(LANGUAGE_WASM_MAP)}var parserCache,inflightLoads,GRAMMAR_LOAD_TIMEOUT_MS=1e4,initializedLanguages,treeSitterInitPromise=null,_internals57,LANGUAGE_WASM_MAP;var init_runtime=__esm(()=>{init_timeout();parserCache=new Map,inflightLoads=new Map,initializedLanguages=new Set,_internals57={parserInit:TreeSitterParser.init,getModuleDir:()=>path60.dirname(fileURLToPath2(import.meta.url)),fileExists:existsSync30};LANGUAGE_WASM_MAP={javascript:"tree-sitter-javascript.wasm",typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",python:"tree-sitter-python.wasm",go:"tree-sitter-go.wasm",rust:"tree-sitter-rust.wasm",cpp:"tree-sitter-cpp.wasm",c:"tree-sitter-cpp.wasm",csharp:"tree-sitter-c-sharp.wasm",css:"tree-sitter-css.wasm",bash:"tree-sitter-bash.wasm",ruby:"tree-sitter-ruby.wasm",php:"tree-sitter-php.wasm",java:"tree-sitter-java.wasm",kotlin:"tree-sitter-kotlin.wasm",swift:"tree-sitter-swift.wasm",dart:"tree-sitter-dart.wasm",powershell:"tree-sitter-powershell.wasm",ini:"tree-sitter-ini.wasm",regex:"tree-sitter-regex.wasm"}});import{extname}from"node:path";function getLanguageForExtension(extension){return extensionMap.get(extension.toLowerCase())}async function getParserForFile(filePath){let extension=extname(filePath).toLowerCase(),language=getLanguageForExtension(extension);if(!language)return null;try{let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));return await loadGrammar2(language.id)}catch{return null}}var languageDefinitions,extensionMap;var init_registry=__esm(()=>{languageDefinitions=[{id:"javascript",extensions:[".js",".jsx",".mjs",".cjs"],commentNodes:["comment","line_comment","block_comment"]},{id:"typescript",extensions:[".ts"],commentNodes:["comment","line_comment","block_comment"]},{id:"python",extensions:[".py",".pyw"],commentNodes:["comment"]},{id:"go",extensions:[".go"],commentNodes:["comment"]},{id:"rust",extensions:[".rs"],commentNodes:["line_comment","block_comment"]},{id:"php",extensions:[".php",".phtml"],commentNodes:["comment"]},{id:"java",extensions:[".java"],commentNodes:["line_comment","block_comment"]},{id:"c",extensions:[".c",".h"],commentNodes:["comment"]},{id:"cpp",extensions:[".cpp",".cxx",".cc",".hpp",".hxx",".hh"],commentNodes:["comment"]},{id:"csharp",extensions:[".cs",".csx"],commentNodes:["comment"]},{id:"ruby",extensions:[".rb",".rake",".gemspec"],commentNodes:["comment"]},{id:"swift",extensions:[".swift"],commentNodes:["comment","multiline_comment"]},{id:"kotlin",extensions:[".kt",".kts"],commentNodes:["line_comment","multiline_comment"]},{id:"dart",extensions:[".dart"],commentNodes:["comment","documentation_comment"]},{id:"css",extensions:[".css"],commentNodes:["comment"]},{id:"bash",extensions:[".sh",".bash"],commentNodes:["comment"]},{id:"powershell",extensions:[".ps1",".psm1"],commentNodes:["comment"]},{id:"ini",extensions:[".ini",".cfg",".conf"],commentNodes:["comment"]},{id:"regex",extensions:[".regex"],commentNodes:[]},{id:"tsx",extensions:[".tsx"],commentNodes:["comment"]}],extensionMap=new Map;for(let definition of languageDefinitions)for(let extension of definition.extensions)extensionMap.set(extension,definition)});var exports_ast_diff={};__export(exports_ast_diff,{computeASTDiff:()=>computeASTDiff});import{extname as extname2}from"node:path";import{Query}from"web-tree-sitter";async function computeASTDiff(filePath,oldContent,newContent){let startTime=Date.now(),extension=extname2(filePath).toLowerCase(),language=getLanguageForExtension(extension);if(!language)return{filePath,language:null,changes:[],durationMs:Date.now()-startTime,usedAST:!1};try{let timeoutId,parser=await Promise.race([loadGrammar(language.id),new Promise((_,reject2)=>{timeoutId=setTimeout(()=>reject2(Error("AST_TIMEOUT")),AST_TIMEOUT_MS)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)}),oldTree=parser.parse(oldContent),newTree=parser.parse(newContent);if(!oldTree||!newTree)return{filePath,language:language.id,changes:[],durationMs:Date.now()-startTime,usedAST:!1,error:"Failed to parse file"};let oldSymbols=extractSymbols(oldTree,language),newSymbols=extractSymbols(newTree,language),changes=compareSymbols(oldSymbols,newSymbols);return oldTree.delete(),newTree.delete(),{filePath,language:language.id,changes,durationMs:Date.now()-startTime,usedAST:!0}}catch(error49){let errorMsg=error49 instanceof Error?error49.message:"Unknown error";if(errorMsg==="AST_TIMEOUT")log(`[ast-diff] Timeout for ${filePath}, falling back to raw diff`);return{filePath,language:language.id,changes:[],durationMs:Date.now()-startTime,usedAST:!1,error:errorMsg}}}function extractSymbols(tree,language){let symbols=[],queryStr=QUERIES[language.id];if(!queryStr)return symbols;try{let lang=tree.language;if(!lang)return symbols;let matches=new Query(lang,queryStr).matches(tree.rootNode);for(let match of matches){let symbol2=parseMatch(match,language.id);if(symbol2)symbols.push(symbol2)}let defEntries=symbols.filter((s)=>s.category!=="export"&&s.category!=="import");if(defEntries.length>0&&defEntries.length<symbols.length){let filtered=symbols.filter((symbol2)=>{if(symbol2.category!=="export"&&symbol2.category!=="import")return!0;return!defEntries.some((def)=>symbol2.lineStart===def.lineStart&&symbol2.lineEnd===def.lineEnd)});symbols.length=0,symbols.push(...filtered)}}catch{}return symbols}function parseMatch(match,languageId){let captures=match.captures,defCapture=captures.find((c)=>c.name.endsWith(".def")),nameCapture=captures.find((c)=>c.name.endsWith(".name"));if(!defCapture){let exportCapture=captures.find((c)=>c.name==="export"),importCapture=captures.find((c)=>c.name==="import"),categoryCapture=exportCapture||importCapture;if(!categoryCapture)return null;let node2=categoryCapture.node,text=node2.text.trim(),name=extractStatementName(text,categoryCapture.name);return{category:categoryCapture.name==="export"?"export":"import",name,lineStart:node2.startPosition.row+1,lineEnd:node2.endPosition.row+1}}let node=defCapture.node,nameNode=nameCapture?.node;return{category:inferCategory(captures[0]?.name||"other"),name:nameNode?.text||"anonymous",lineStart:node.startPosition.row+1,lineEnd:node.endPosition.row+1,signature:extractSignature(node,languageId)}}function extractStatementName(text,captureType){if(captureType==="import"){let fromMatch=text.match(/from\s+['"]([^'"]+)['"]/);if(fromMatch)return fromMatch[1];let stringMatch=text.match(/['"]([^'"]+)['"]/);if(stringMatch)return stringMatch[1]}else{let namedExport=text.match(/export\s+(?:default\s+)?(?:function|class|const|let|var|type|interface)\s+(\w+)/);if(namedExport)return namedExport[1];if(text.match(/export\s+default\s+(?:function|class)\b/))return"default";let braceExport=text.match(/export\s+\{([^}]+)\}/);if(braceExport)return braceExport[1].trim()}let tokens=text.split(/\s+/);return tokens.length>1?tokens.slice(0,3).join(" "):text.slice(0,30)}function inferCategory(captureName){if(captureName.includes("func"))return"function";if(captureName.includes("class"))return"class";if(captureName.includes("type")||captureName.includes("interface")||captureName.includes("struct")||captureName.includes("protocol")||captureName.includes("mixin")||captureName.includes("object")||captureName.includes("module"))return"type";if(captureName.includes("export"))return"export";if(captureName.includes("import")||captureName.includes("use")||captureName.includes("using"))return"import";if(captureName.includes("var"))return"variable";if(captureName.includes("command"))return"function";if(captureName.includes("rule"))return"type";return"other"}function extractSignature(node,languageId){let nodeTypes=paramNodeTypes[languageId]||[];for(let child of node.children)if(child&&nodeTypes.includes(child.type))return child.text;if(languageId==="javascript"||languageId==="typescript"||languageId==="tsx"){let paramsNode=node.children.find((c)=>c!==null&&c.type==="formal_parameters");if(paramsNode)return paramsNode.text}if(node.type==="class_declaration"||node.type==="class_definition"||node.type==="class"){let classBodyNode=node.children.find((c)=>c!==null&&(c.type==="class_body"||c.type==="declaration_list"));if(classBodyNode)return classBodyNode.text}return}function compareSymbols(oldSymbols,newSymbols){let changes=[],oldMap=new Map(oldSymbols.map((s)=>[s.name,s])),newMap=new Map(newSymbols.map((s)=>[s.name,s])),matchedOldSymbols=new Set;for(let newSymbol of newSymbols)if(!oldMap.has(newSymbol.name)){let matchingOldSymbol=findRenamedSymbol(newSymbol,oldSymbols,matchedOldSymbols);if(matchingOldSymbol)changes.push({type:"renamed",category:newSymbol.category,name:newSymbol.name,lineStart:newSymbol.lineStart,lineEnd:newSymbol.lineEnd,signature:newSymbol.signature,renamedFrom:matchingOldSymbol.name}),matchedOldSymbols.add(matchingOldSymbol);else changes.push({type:"added",category:newSymbol.category,name:newSymbol.name,lineStart:newSymbol.lineStart,lineEnd:newSymbol.lineEnd,signature:newSymbol.signature})}else{let oldSymbol=oldMap.get(newSymbol.name);if(matchedOldSymbols.add(oldSymbol),oldSymbol.lineStart!==newSymbol.lineStart||oldSymbol.lineEnd!==newSymbol.lineEnd||oldSymbol.signature!==newSymbol.signature)changes.push({type:"modified",category:newSymbol.category,name:newSymbol.name,lineStart:newSymbol.lineStart,lineEnd:newSymbol.lineEnd,signature:newSymbol.signature})}for(let oldSymbol of oldSymbols)if(!newMap.has(oldSymbol.name)&&!matchedOldSymbols.has(oldSymbol))changes.push({type:"removed",category:oldSymbol.category,name:oldSymbol.name,lineStart:oldSymbol.lineStart,lineEnd:oldSymbol.lineEnd,signature:oldSymbol.signature});return changes}function findRenamedSymbol(newSymbol,oldSymbols,matchedOldSymbols){if(newSymbol.category!=="function"&&newSymbol.category!=="type"&&newSymbol.category!=="class")return null;if(!newSymbol.signature)return null;if(newSymbol.category==="function"&&newSymbol.signature.replace(/\s/g,"")==="()")return null;let lineCount=newSymbol.lineEnd-newSymbol.lineStart;for(let oldSymbol of oldSymbols){if(matchedOldSymbols.has(oldSymbol)||oldSymbol.category!==newSymbol.category)continue;if(oldSymbol.signature!==newSymbol.signature)continue;let oldLineCount=oldSymbol.lineEnd-oldSymbol.lineStart,maxAllowedLines=Math.ceil(lineCount*1.2);if(oldLineCount>maxAllowedLines)continue;return oldSymbol}return null}var QUERIES,AST_TIMEOUT_MS=500,paramNodeTypes;var init_ast_diff=__esm(()=>{init_registry();init_runtime();init_logger();QUERIES={javascript:`
|
|
@@ -7903,7 +7903,7 @@ ${content}
|
|
|
7903
7903
|
|
|
7904
7904
|
### Mutation Coverage Gap
|
|
7905
7905
|
- **[${finding.severity}]** \`${finding.location}\` (${finding.category}) — ${finding.detail}
|
|
7906
|
-
_Evidence:_ ${finding.evidence}`}init_zod();init_pr_review_contract();init_pr_workflow_gate();init_canonical_root();init_create_tool();var SubmitPrReviewResultArgsSchema=exports_external.object({schemaVersion:exports_external.preprocess((value)=>value==="1"?1:value,exports_external.literal(1)).describe('the JSON number 1 (the string "1" is also accepted)'),batchId:exports_external.string().trim().min(1).max(120).optional(),laneId:exports_external.string().trim().min(1).max(120).optional(),revisionDigest:exports_external.string().trim().regex(/^[0-9a-f]{64}$/i),result:PrReviewLaneResultEnvelopeSchema}).strict(),RECEIVED_VALUE_RENDER_LIMIT=120,MAX_FORMATTED_ISSUE_MESSAGE_CHARS=2000;function resolveReceivedValue(args2,path383){let current=args2;for(let key3 of path383){if(current===null||typeof current!=="object")return;current=current[key3]}return current}function renderReceivedValue(value){let typeofLabel=typeof value;if(value===void 0)return"received undefined";let rendered;try{rendered=JSON.stringify(value)??"null"}catch{return`received <unrepresentable> (${typeofLabel})`}if(rendered.length>RECEIVED_VALUE_RENDER_LIMIT)rendered=`${rendered.slice(0,RECEIVED_VALUE_RENDER_LIMIT)}…`;return`received ${rendered} (${typeofLabel})`}var UNRECOGNIZED_KEY_PATTERN=/Unrecognized key: "([^"]*)"/;function formatSubmitValidationIssues(args2,issues){let joined=issues.map((issue3)=>{let pathLabel=issue3.path.length>0?issue3.path.join("."):"(root)",receivedSource,haveReceivedSource=!1;if(issue3.path.length>0)receivedSource=resolveReceivedValue(args2,issue3.path),haveReceivedSource=!0;else{let key3=UNRECOGNIZED_KEY_PATTERN.exec(issue3.message)?.[1];if(key3!==void 0&&args2!==null&&typeof args2==="object")receivedSource=args2[key3],haveReceivedSource=!0}let received=haveReceivedSource?` (${renderReceivedValue(receivedSource)})`:"";return`${pathLabel}: ${issue3.message}${received}`}).join("; ");if(joined.length<=MAX_FORMATTED_ISSUE_MESSAGE_CHARS)return joined;return`${joined.slice(0,MAX_FORMATTED_ISSUE_MESSAGE_CHARS)}… [truncated: ${issues.length} validation issue(s) exceed the ${MAX_FORMATTED_ISSUE_MESSAGE_CHARS}-char diagnostic budget; fix the first listed issue(s) and resubmit]`}var MAX_TRACKED_SUBMIT_SESSIONS=128,SUBMIT_REJECTION_HINT_THRESHOLD=3,consecutiveSubmitRejections=new Map;function submitRejectionKey(directory,sessionID){return`${canonicalRootKeyFresh(directory)}${String.fromCharCode(0)}${sessionID}`}function noteSubmitRejection(directory,sessionID){let key3=submitRejectionKey(directory,sessionID),next=(consecutiveSubmitRejections.get(key3)??0)+1;consecutiveSubmitRejections.set(key3,next);while(consecutiveSubmitRejections.size>MAX_TRACKED_SUBMIT_SESSIONS){let oldest=consecutiveSubmitRejections.keys().next().value;if(oldest===void 0)break;consecutiveSubmitRejections.delete(oldest)}return next}function clearSubmitRejections(directory,sessionID){consecutiveSubmitRejections.delete(submitRejectionKey(directory,sessionID))}async function executeSubmitPrReviewResult(args2,directory,context={}){let parsed=SubmitPrReviewResultArgsSchema.safeParse(args2),childSessionId=context.sessionID?.trim();if(!childSessionId)return JSON.stringify({success:!1,message:"submit_pr_review_result requires an authenticated child session"});if(!parsed.success){let count4=noteSubmitRejection(directory,childSessionId),hint=count4>=SUBMIT_REJECTION_HINT_THRESHOLD?` — ${count4} consecutive rejections: re-read the tool schema; do NOT resubmit the same payload shape.`:"",message=`Invalid PR-review result: ${formatSubmitValidationIssues(args2,parsed.error.issues)}${hint}`;return await recordPrReviewSubmitRejection(directory,childSessionId,message),JSON.stringify({success:!1,message})}clearSubmitRejections(directory,childSessionId);let outcome=await submitPrReviewResult(directory,childSessionId,{...parsed.data.batchId?{batchId:parsed.data.batchId}:{},...parsed.data.laneId?{laneId:parsed.data.laneId}:{},revisionDigest:parsed.data.revisionDigest,result:parsed.data.result});return JSON.stringify({success:outcome.status==="recorded"||outcome.status==="duplicate",...outcome})}var submit_pr_review_result=createSwarmTool({description:"Submit exactly one typed CLEAN, FINDINGS, or INCOMPLETE result for the active child-bound PR-review base/micro lane. The authenticated child session identifies its exact delegation and supplies authoritative batch/lane provenance; optional batchId/laneId values are checked when present. The receipt is atomically bound to the child session, workflow instance, revision, batch, lane, root, base, and head. Identical replay is idempotent; conflicting or late submissions fail closed. Exception (issue #2585): when a lane's child is terminally unavailable (cancelled, stale, or liveness-error), the lane's dispatching parent session may submit one repair receipt for that lane; the receipt records the architect provenance and stays bound to the dead child session. Every other session is still refused. Call once, then stop.",args:{schemaVersion:SubmitPrReviewResultArgsSchema.shape.schemaVersion,batchId:SubmitPrReviewResultArgsSchema.shape.batchId,laneId:SubmitPrReviewResultArgsSchema.shape.laneId,revisionDigest:SubmitPrReviewResultArgsSchema.shape.revisionDigest,result:SubmitPrReviewResultArgsSchema.shape.result},execute:executeSubmitPrReviewResult});init_zod();init_path_security();init_create_tool();import*as fs237 from"node:fs";import*as path383 from"node:path";var BINARY_EXTENSIONS2=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".woff",".woff2",".ttf",".eot",".mp3",".mp4",".avi",".mov",".pdf",".zip",".tar",".gz",".rar"]),WINDOWS_RESERVED_NAMES6=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks5(str){if(/^[A-Za-z]:[/\\]/.test(str))return!0;if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES6.test(part))return!0;return!1}function isPathInWorkspace4(filePath,workspace){try{let resolvedPath=path383.resolve(workspace,filePath);return isCanonicalPathWithinRoot(resolvedPath,workspace)}catch{return!1}}function validateFilePath2(filePath,workspace){if(!filePath||filePath.trim()==="")return!1;if(containsPathTraversal(filePath))return!1;if(containsControlChars(filePath))return!1;if(containsWindowsAttacks5(filePath))return!1;return isPathInWorkspace4(filePath,workspace)}function findContextMatch(content,contextBefore,contextAfter,oldContent){let lines=splitDiffLines(content);if((!contextBefore||contextBefore.length===0)&&(!contextAfter||contextAfter.length===0))return null;if(contextBefore&&contextBefore.length>0)for(let i=0;i<=lines.length-contextBefore.length;i++){let slice=lines.slice(i,i+contextBefore.length);if(arraysEqual2(slice,contextBefore)){let afterStart=i+contextBefore.length;if(contextAfter&&contextAfter.length>0){for(let j=afterStart;j<=lines.length-contextAfter.length;j++){let afterSlice=lines.slice(j,j+contextAfter.length);if(arraysEqual2(afterSlice,contextAfter))if(j===afterStart)return{startLineIndex:i,endLineIndex:j+contextAfter.length-1,matchedBefore:contextBefore,matchedAfter:contextAfter};else if(oldContent&&oldContent.length>0){let oldContentLines=splitDiffLines(oldContent),betweenLines=lines.slice(afterStart,j);if(arraysEqual2(betweenLines,oldContentLines))return{startLineIndex:i,endLineIndex:j-1,matchedBefore:contextBefore,matchedAfter:contextAfter}}else return{startLineIndex:i,endLineIndex:j-1,matchedBefore:contextBefore,matchedAfter:contextAfter}}return null}else if(oldContent&&oldContent.length>0){let oldContentLines=splitDiffLines(oldContent);for(let k=afterStart;k<=lines.length-oldContentLines.length;k++){let candidate2=lines.slice(k,k+oldContentLines.length);if(arraysEqual2(candidate2,oldContentLines))return{startLineIndex:i,endLineIndex:k+oldContentLines.length-1,matchedBefore:contextBefore,matchedAfter:[]}}return null}else return{startLineIndex:i,endLineIndex:afterStart-1,matchedBefore:contextBefore,matchedAfter:[]}}}else if(contextAfter&&contextAfter.length>0)for(let j=0;j<=lines.length-contextAfter.length;j++){let afterSlice=lines.slice(j,j+contextAfter.length);if(arraysEqual2(afterSlice,contextAfter))return{startLineIndex:0,endLineIndex:j-1,matchedBefore:[],matchedAfter:contextAfter}}return null}function arraysEqual2(a,b){if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return!0}function isBinaryFile4(filePath){let ext=path383.extname(filePath).toLowerCase();return BINARY_EXTENSIONS2.has(ext)}function splitDiffLines(content){if(content==="")return[];return content.endsWith(`
|
|
7906
|
+
_Evidence:_ ${finding.evidence}`}init_zod();init_pr_review_contract();init_pr_workflow_gate();init_canonical_root();init_create_tool();var SubmitPrReviewResultArgsSchema=exports_external.object({schemaVersion:exports_external.preprocess((value)=>value==="1"?1:value,exports_external.literal(1)).describe('the JSON number 1 (the string "1" is also accepted)'),batchId:exports_external.string().trim().min(1).max(120).optional(),laneId:exports_external.string().trim().min(1).max(120).optional(),revisionDigest:exports_external.string().trim().regex(/^[0-9a-f]{64}$/i),result:PrReviewLaneResultEnvelopeSchema}).strict(),RECEIVED_VALUE_RENDER_LIMIT=120,MAX_FORMATTED_ISSUE_MESSAGE_CHARS=2000;function resolveReceivedValue(args2,path383){let current=args2;for(let key3 of path383){if(current===null||typeof current!=="object")return;current=current[key3]}return current}function renderReceivedValue(value){let typeofLabel=typeof value;if(value===void 0)return"received undefined";let rendered;try{rendered=JSON.stringify(value)??"null"}catch{return`received <unrepresentable> (${typeofLabel})`}if(rendered.length>RECEIVED_VALUE_RENDER_LIMIT)rendered=`${rendered.slice(0,RECEIVED_VALUE_RENDER_LIMIT)}…`;return`received ${rendered} (${typeofLabel})`}var UNRECOGNIZED_KEY_PATTERN=/Unrecognized key: "([^"]*)"/;function formatSubmitValidationIssues(args2,issues){let joined=issues.map((issue3)=>{let pathLabel=issue3.path.length>0?issue3.path.join("."):"(root)",receivedSource,haveReceivedSource=!1;if(issue3.path.length>0)receivedSource=resolveReceivedValue(args2,issue3.path),haveReceivedSource=!0;else{let key3=UNRECOGNIZED_KEY_PATTERN.exec(issue3.message)?.[1];if(key3!==void 0&&args2!==null&&typeof args2==="object")receivedSource=args2[key3],haveReceivedSource=!0}let received=haveReceivedSource?` (${renderReceivedValue(receivedSource)})`:"";return`${pathLabel}: ${issue3.message}${received}`}).join("; ");if(joined.length<=MAX_FORMATTED_ISSUE_MESSAGE_CHARS)return joined;return`${joined.slice(0,MAX_FORMATTED_ISSUE_MESSAGE_CHARS)}… [truncated: ${issues.length} validation issue(s) exceed the ${MAX_FORMATTED_ISSUE_MESSAGE_CHARS}-char diagnostic budget; fix the first listed issue(s) and resubmit]`}var MAX_TRACKED_SUBMIT_SESSIONS=128,SUBMIT_REJECTION_HINT_THRESHOLD=3,consecutiveSubmitRejections=new Map;function submitRejectionKey(directory,sessionID){return`${canonicalRootKeyFresh(directory)}${String.fromCharCode(0)}${sessionID}`}function noteSubmitRejection(directory,sessionID){let key3=submitRejectionKey(directory,sessionID),next=(consecutiveSubmitRejections.get(key3)??0)+1;consecutiveSubmitRejections.set(key3,next);while(consecutiveSubmitRejections.size>MAX_TRACKED_SUBMIT_SESSIONS){let oldest=consecutiveSubmitRejections.keys().next().value;if(oldest===void 0)break;consecutiveSubmitRejections.delete(oldest)}return next}function clearSubmitRejections(directory,sessionID){consecutiveSubmitRejections.delete(submitRejectionKey(directory,sessionID))}async function executeSubmitPrReviewResult(args2,directory,context={}){let parsed=SubmitPrReviewResultArgsSchema.safeParse(args2),childSessionId=context.sessionID?.trim();if(!childSessionId)return JSON.stringify({success:!1,message:"submit_pr_review_result requires an authenticated child session"});if(!parsed.success){let count4=noteSubmitRejection(directory,childSessionId),hint=count4>=SUBMIT_REJECTION_HINT_THRESHOLD?` — ${count4} consecutive rejections: re-read the tool schema; do NOT resubmit the same payload shape.`:"",message=`Invalid PR-review result: ${formatSubmitValidationIssues(args2,parsed.error.issues)}${hint}`;return await recordPrReviewSubmitRejection(directory,childSessionId,message),JSON.stringify({success:!1,message})}clearSubmitRejections(directory,childSessionId);let outcome=await submitPrReviewResult(directory,childSessionId,{...parsed.data.batchId?{batchId:parsed.data.batchId}:{},...parsed.data.laneId?{laneId:parsed.data.laneId}:{},revisionDigest:parsed.data.revisionDigest,result:parsed.data.result});return JSON.stringify({success:outcome.status==="recorded"||outcome.status==="duplicate",...outcome})}var submit_pr_review_result=createSwarmTool({description:"Submit exactly one typed CLEAN, FINDINGS, or INCOMPLETE result for the active child-bound PR-review base/micro lane. The authenticated child session identifies its exact delegation and supplies authoritative batch/lane provenance; optional batchId/laneId values are checked when present. The receipt is atomically bound to the child session, workflow instance, revision, batch, lane, root, base, and head. Identical replay is idempotent; conflicting or late submissions fail closed. Exception (issue #2585): when a lane's child is terminally unavailable (cancelled, stale, or liveness-error), the lane's dispatching parent session may submit one repair receipt for that lane; the receipt records the architect provenance and stays bound to the dead child session. Every other session is still refused. Call once, then stop.",args:{schemaVersion:SubmitPrReviewResultArgsSchema.shape.schemaVersion,batchId:SubmitPrReviewResultArgsSchema.shape.batchId,laneId:SubmitPrReviewResultArgsSchema.shape.laneId,revisionDigest:SubmitPrReviewResultArgsSchema.shape.revisionDigest,result:SubmitPrReviewResultArgsSchema.shape.result},execute:executeSubmitPrReviewResult});init_zod();init_protected_path_policy();init_path_security();init_create_tool();import*as fs237 from"node:fs";import*as path383 from"node:path";var BINARY_EXTENSIONS2=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".woff",".woff2",".ttf",".eot",".mp3",".mp4",".avi",".mov",".pdf",".zip",".tar",".gz",".rar"]),WINDOWS_RESERVED_NAMES6=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks5(str){if(/^[A-Za-z]:[/\\]/.test(str))return!0;if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES6.test(part))return!0;return!1}function isPathInWorkspace4(filePath,workspace){try{let resolvedPath=path383.resolve(workspace,filePath);return isCanonicalPathWithinRoot(resolvedPath,workspace)}catch{return!1}}function validateFilePath2(filePath,workspace){if(!filePath||filePath.trim()==="")return!1;if(containsPathTraversal(filePath))return!1;if(containsControlChars(filePath))return!1;if(containsWindowsAttacks5(filePath))return!1;return isPathInWorkspace4(filePath,workspace)}function findContextMatch(content,contextBefore,contextAfter,oldContent){let lines=splitDiffLines(content);if((!contextBefore||contextBefore.length===0)&&(!contextAfter||contextAfter.length===0))return null;if(contextBefore&&contextBefore.length>0)for(let i=0;i<=lines.length-contextBefore.length;i++){let slice=lines.slice(i,i+contextBefore.length);if(arraysEqual2(slice,contextBefore)){let afterStart=i+contextBefore.length;if(contextAfter&&contextAfter.length>0){for(let j=afterStart;j<=lines.length-contextAfter.length;j++){let afterSlice=lines.slice(j,j+contextAfter.length);if(arraysEqual2(afterSlice,contextAfter))if(j===afterStart)return{startLineIndex:i,endLineIndex:j+contextAfter.length-1,matchedBefore:contextBefore,matchedAfter:contextAfter};else if(oldContent&&oldContent.length>0){let oldContentLines=splitDiffLines(oldContent),betweenLines=lines.slice(afterStart,j);if(arraysEqual2(betweenLines,oldContentLines))return{startLineIndex:i,endLineIndex:j-1,matchedBefore:contextBefore,matchedAfter:contextAfter}}else return{startLineIndex:i,endLineIndex:j-1,matchedBefore:contextBefore,matchedAfter:contextAfter}}return null}else if(oldContent&&oldContent.length>0){let oldContentLines=splitDiffLines(oldContent);for(let k=afterStart;k<=lines.length-oldContentLines.length;k++){let candidate2=lines.slice(k,k+oldContentLines.length);if(arraysEqual2(candidate2,oldContentLines))return{startLineIndex:i,endLineIndex:k+oldContentLines.length-1,matchedBefore:contextBefore,matchedAfter:[]}}return null}else return{startLineIndex:i,endLineIndex:afterStart-1,matchedBefore:contextBefore,matchedAfter:[]}}}else if(contextAfter&&contextAfter.length>0)for(let j=0;j<=lines.length-contextAfter.length;j++){let afterSlice=lines.slice(j,j+contextAfter.length);if(arraysEqual2(afterSlice,contextAfter))return{startLineIndex:0,endLineIndex:j-1,matchedBefore:[],matchedAfter:contextAfter}}return null}function arraysEqual2(a,b){if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return!0}function isBinaryFile4(filePath){let ext=path383.extname(filePath).toLowerCase();return BINARY_EXTENSIONS2.has(ext)}function splitDiffLines(content){if(content==="")return[];return content.endsWith(`
|
|
7907
7907
|
`)?content.slice(0,-1).split(`
|
|
7908
7908
|
`):content.split(`
|
|
7909
7909
|
`)}function generateFileHeader(file3){return`diff --git a/${file3} b/${file3}
|
|
@@ -7916,7 +7916,7 @@ ${content}
|
|
|
7916
7916
|
`),diff2+=`
|
|
7917
7917
|
`,diff2}function validateOldContent(lines,contextMatch,oldContent){if(!oldContent)return{valid:!0};let expectedLines=splitDiffLines(oldContent),removalStartIdx=contextMatch.startLineIndex+contextMatch.matchedBefore.length,actualLines=lines.slice(removalStartIdx,removalStartIdx+expectedLines.length);if(!arraysEqual2(actualLines,expectedLines))return{valid:!1,expected:expectedLines.join(`
|
|
7918
7918
|
`),actual:actualLines.join(`
|
|
7919
|
-
`)};return{valid:!0}}var suggestPatch=createSwarmTool({description:'Suggest a structured patch for specified files without modifying them. Returns context-based patch proposals with anchors for reviewer use. When format="unified", also produces a unified diff string consumable by apply_patch. '+"This is a read-only tool — it does not modify any files.",args:{targetFiles:exports_external.array(exports_external.string()).describe("Array of file paths to patch").min(1),changes:exports_external.array(exports_external.object({file:exports_external.string().describe("Path to the file this change applies to"),contextBefore:exports_external.array(exports_external.string()).optional().describe("Lines before the change region (anchor)"),contextAfter:exports_external.array(exports_external.string()).optional().describe("Lines after the change region (anchor)"),oldContent:exports_external.string().optional().describe("Current content to be replaced"),newContent:exports_external.string().describe("New content to replace with")})).describe("Array of change descriptions with context anchors").min(1),format:exports_external.enum(["json","unified"]).optional().default("json").describe('Output format: "json" (default, existing structured output) or "unified" (unified diff string for apply_patch)')},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"Could not parse suggest-patch arguments"},null,2);let obj=args2,targetFiles=obj.targetFiles??[],changes=obj.changes??[],format=obj.format??"json";if(!targetFiles||targetFiles.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"targetFiles cannot be empty"},null,2);if(!changes||changes.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"changes cannot be empty"},null,2);if(!fs237.existsSync(directory))return JSON.stringify({success:!1,error:!0,type:"file-not-found",message:"Workspace directory does not exist"},null,2);let patches=[],filesModifiedSet=new Set,errors5=[],unifiedDiffEntries=[],targetFileSet=new Set(targetFiles),skippedBinaryFiles=new Set;if(format==="unified"){for(let change of changes)if(isBinaryFile4(change.file))errors5.push({success:!1,error:!0,type:"parse-error",message:`Binary files are not supported in unified diff mode: ${change.file}`,details:{location:change.file}}),skippedBinaryFiles.add(change.file)}for(let changeIndex=0;changeIndex<changes.length;changeIndex++){let change=changes[changeIndex];if(format==="unified"&&skippedBinaryFiles.has(change.file))continue;if(!targetFileSet.has(change.file)){errors5.push({success:!1,error:!0,type:"parse-error",message:`File "${change.file}" is not in targetFiles`,details:{location:change.file}});continue}if(!validateFilePath2(change.file,directory)){errors5.push({success:!1,error:!0,type:"parse-error",message:`Invalid file path: ${change.file}`,details:{location:change.file}});continue}let fullPath=path383.resolve(directory,change.file);if(!fs237.existsSync(fullPath)){errors5.push({success:!1,error:!0,type:"file-not-found",message:`File not found: ${change.file}`,details:{location:change.file}});continue}let content;try{content=fs237.readFileSync(fullPath,"utf-8")}catch(err2){errors5.push({success:!1,error:!0,type:"unknown",message:`Could not read file: ${err2 instanceof Error?err2.message:String(err2)}`,details:{location:`${change.file}:0`}});continue}let contextMatch=findContextMatch(content,change.contextBefore,change.contextAfter,change.oldContent);if(!contextMatch){errors5.push({success:!1,error:!0,type:"context-mismatch",message:`Could not find context anchor in ${change.file}. Provide contextBefore/contextAfter lines to locate the change region.`,details:{location:change.file}});continue}let lines=splitDiffLines(content),oldContentValidation=validateOldContent(lines,contextMatch,change.oldContent);if(!oldContentValidation.valid){errors5.push({success:!1,error:!0,type:"context-mismatch",message:"Content at the specified location does not match oldContent",details:{expected:oldContentValidation.expected,actual:oldContentValidation.actual,location:`${change.file}:${contextMatch.startLineIndex+1}-${contextMatch.endLineIndex+1}`}});continue}let originalContext=[...contextMatch.matchedBefore,...contextMatch.matchedAfter.length>0?["..."]:[],...contextMatch.matchedAfter];if(patches.push({file:change.file,originalContext,newContent:change.newContent,hunkIndex:changeIndex}),filesModifiedSet.add(change.file),format==="unified")unifiedDiffEntries.push({file:change.file,contextMatch,oldContent:change.oldContent,newContent:change.newContent})}if(patches.length>0){let baseResult={success:!0,patches,filesModified:Array.from(filesModifiedSet),...errors5.length>0&&{errors:errors5}};if(format==="unified"){let fileGroups=new Map;for(let entry of unifiedDiffEntries){let group=fileGroups.get(entry.file)??[];group.push(entry),fileGroups.set(entry.file,group)}let unifiedParts=[];for(let[file3,entries2]of fileGroups){entries2.sort((a,b)=>a.contextMatch.startLineIndex-b.contextMatch.startLineIndex);let entryFullPath=path383.resolve(directory,file3),entryContent;try{entryContent=fs237.readFileSync(entryFullPath,"utf-8")}catch{continue}unifiedParts.push(generateFileHeader(file3));for(let entry of entries2)unifiedParts.push(generateHunk(entryContent,entry.contextMatch,entry.oldContent,entry.newContent))}let unifiedPatch=unifiedParts.join("");return JSON.stringify({...baseResult,unifiedPatch},null,2)}return JSON.stringify(baseResult,null,2)}if(errors5.length===1)return JSON.stringify(errors5[0],null,2);return JSON.stringify({success:!1,error:!0,type:"context-mismatch",message:`All ${errors5.length} patch suggestions failed`,errors:errors5},null,2)}});init_zod();init_loader();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();function getContextAgent2(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}var ArgsSchema5=exports_external.object({phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),parent_agent:exports_external.string().min(1).optional(),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()}),summarize_work=createSwarmTool({description:`Emit a short structured summary of the work you just completed (key decisions, assumptions, risks, constraints observed/violated). Call this once at task completion. Keep the summary under ${MAX_AGENT_SUMMARY_WORDS} words and each list to ${MAX_LIST_ITEMS} items — longer content is truncated, not rejected. These `+"summaries roll up per phase and are reviewed by the architecture supervisor to catch cross-task contradictions, drift, and repeated failure loops. Advisory only.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number this work belongs to."),summary:exports_external.string().min(1).describe(`One-paragraph summary of what you did (<= ${MAX_AGENT_SUMMARY_WORDS} words).`),task_id:exports_external.string().min(1).optional().describe('Task ID this summary covers (e.g. "1.2").'),parent_agent:exports_external.string().min(1).optional().describe("The agent that delegated this task, if any."),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()},execute:async(rawArgs,directory,ctx)=>{let parsed=ArgsSchema5.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,sessionId=ctx?.sessionID??"unknown-session",agent=getContextAgent2(ctx)??"unknown-agent",maxWords=MAX_AGENT_SUMMARY_WORDS;try{maxWords=loadPluginConfig(workingDir).architectural_supervision?.max_agent_summary_words??maxWords}catch{}let summary=normalizeAgentWorkSummary({phase:args2.phase,task_id:args2.task_id,session_id:sessionId,agent,parent_agent:args2.parent_agent,summary:args2.summary,key_decisions:args2.key_decisions,constraints_observed:args2.constraints_observed,constraints_violated:args2.constraints_violated,assumptions:args2.assumptions,risks:args2.risks,files_touched:args2.files_touched,evidence_refs:args2.evidence_refs},maxWords),storedTaskId=await writeAgentSummary(workingDir,summary);return JSON.stringify({success:!0,stored_task_id:storedTaskId,phase:summary.phase,agent:summary.agent,truncated:summary.truncated??!1},null,2)}});init_zod();init_command_dispatch();init_tool_policy();init_create_tool();function createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Run supported /swarm commands through the canonical opencode-swarm command registry. Return the tool output verbatim to the user.",args:{command:exports_external.enum(SWARM_COMMAND_TOOL_COMMANDS).describe("The /swarm subcommand to run, without the /swarm prefix."),args:exports_external.array(exports_external.string()).default([]).describe("Additional command arguments as separate tokens.")},async execute(rawArgs,directory,ctx){let args2=rawArgs;return(await executeSwarmCommand({directory,agents,sessionID:ctx?.sessionID??"",tokens:[args2.command,...args2.args??[]],policy:classifySwarmCommandToolUse,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,activeAgentName:getActiveAgentName?.(ctx?.sessionID??"")})).text}})}var swarm_command=createSwarmCommandTool({});init_zod();init_config2();init_memory();init_state();init_create_tool();import{createHash as createHash121}from"node:crypto";var OutcomeArgsSchema=exports_external.object({memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional(),question:exports_external.string().trim().min(1).max(2000).optional(),outcome:exports_external.enum(["useful","dead_end","corrected"]),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional(),correction:exports_external.string().trim().min(1).max(4000).optional()}).strict().superRefine((value,context)=>{if(Boolean(value.memory_id)===Boolean(value.question))context.addIssue({code:"custom",message:"exactly one of memory_id or question is required"});if(value.outcome==="corrected"&&!value.correction)context.addIssue({code:"custom",message:"corrected outcomes require correction text"})}),swarm_memory_outcome=createSwarmTool({description:"Record whether recalled memory or a graph answer was useful, a dead end, or corrected; when reflection is enabled, synchronously refresh deterministic reflection artifacts.",args:{memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional().describe("Existing memory id to update"),question:exports_external.string().trim().min(1).max(2000).optional().describe("Question for a lightweight result memory when no id is known"),outcome:exports_external.enum(["useful","dead_end","corrected"]).describe("Observed result"),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional().describe("Repository-relative file and optional symbol anchors"),correction:exports_external.string().trim().min(1).max(4000).optional().describe("Required corrected claim text for corrected outcomes")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals328.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=OutcomeArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=typeof ctx?.agent==="string"?ctx.agent:void 0,taskId=ctx?.sessionID?_internals328.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals328.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId:taskId},{config:config3.memory}),eventId=ctx?.sessionID&&ctx.messageID?`tool-${createHash121("sha256").update(JSON.stringify({sessionID:ctx.sessionID,messageID:ctx.messageID,args:parsed.data})).digest("hex").slice(0,32)}`:void 0;try{let result=await _internals328.recordOutcomeWithReflection(directory,config3.memory,gateway,{memoryId:parsed.data.memory_id,question:parsed.data.question,outcome:parsed.data.outcome,anchors:parsed.data.anchors,correction:parsed.data.correction,eventId}),reflectionUpdated=result.reflectionUpdated,reflectionAttempted=result.reflectionAttempted,partial3=result.reflectionEnabled===!0&&reflectionAttempted&&!reflectionUpdated,reflectionError="error"in result?result.error:void 0;return JSON.stringify({success:!0,status:partial3?"partial":"complete",partial:partial3,outcome_recorded:result.outcomeRecorded,event_id:result.eventId,memory_id:result.record.id,outcome:parsed.data.outcome,outcomes:result.record.outcomes?.length??0,reflection_enabled:result.reflectionEnabled,reflection_attempted:reflectionAttempted,reflection_updated:reflectionUpdated,reflection_entries:reflectionUpdated?result.digest.generatedFrom.entries:void 0,error:partial3?reflectionError:void 0,reflection_error:partial3?reflectionError:void 0},null,2)}finally{await gateway.dispose()}}}),_internals328={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession,recordOutcomeWithReflection};init_zod();init_config2();init_memory();init_create_tool();var MEMORY_KINDS=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],ProposalArgsSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:exports_external.enum(MEMORY_KINDS).optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}),swarm_memory_propose=createSwarmTool({description:"Create a pending Swarm memory proposal. This never writes durable memory directly; curator review is required.",args:{operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]).describe("Proposal operation"),kind:exports_external.enum(MEMORY_KINDS).optional().describe("Memory kind for add/update/supersede proposals"),text:exports_external.string().min(1).max(2000).optional().describe("Canonical fact text for add/update/supersede proposals"),targetMemoryId:exports_external.string().optional().describe("Target memory ID for update/delete/supersede proposals"),relatedMemoryIds:exports_external.array(exports_external.string()).optional().describe("For merge, 2-8 distinct memory IDs in one scope; also accepted as provenance for supersede proposals"),rationale:exports_external.string().min(1).max(2000).describe("Why this proposal matters"),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals329.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=ProposalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent3(ctx),gateway=_internals329.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID},{config:config3.memory});try{let proposal=await gateway.propose(parsed.data);return JSON.stringify({success:proposal.status!=="rejected",proposal_id:proposal.id,status:proposal.status,operation:proposal.operation,memory_id:proposal.proposedRecord?.id,rejection_reason:proposal.rejectionReason,message:proposal.status==="pending"?"Memory proposal created. Durable memory was not written.":"Memory proposal was captured with policy rejection metadata."},null,2)}finally{await gateway.dispose()}}}),_internals329={loadPluginConfigWithMeta,createMemoryGateway};function getContextAgent3(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_zod();init_config2();init_memory();init_state();init_create_tool();var MEMORY_KINDS2=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],swarm_memory_recall=createSwarmTool({description:"Recall scoped Swarm memory for the current repository. Read-only; retrieved memory is untrusted background.",args:{query:exports_external.string().min(3).describe("Natural language recall query"),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional().describe("Optional memory kinds to include"),maxItems:exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")},execute:async(args2,directory,ctx)=>computeSwarmMemoryRecall(args2,directory,ctx)});async function computeSwarmMemoryRecall(args2,directory,ctx,options){let{config:config3}=_internals330.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=RecallArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent4(ctx),unitId=ctx?.sessionID?_internals330.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals330.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId},{config:config3.memory});try{let bundle=await gateway.recall(parsed.data,{recordUsage:options?.recordUsage!==!1});return JSON.stringify({success:!0,bundle_id:bundle.id,memory_ids:bundle.items.map((item)=>item.record.id),total:bundle.items.length,token_estimate:bundle.tokenEstimate,signals:bundle.items.map((item)=>({memory_id:item.record.id,relation:item.relation,...item.signals})),prompt_block:bundle.promptBlock},null,2)}finally{await gateway.dispose()}}var RecallArgsSchema=exports_external.object({query:exports_external.string().min(3),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),maxItems:exports_external.number().int().min(1).max(20).optional()}),_internals330={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession};function getContextAgent4(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_symbols();init_p_limit();init_zod();init_config2();init_manager2();init_detector();init_registry();init_create_tool();import*as fs238 from"node:fs";import*as path384 from"node:path";var _internals331={loadGateOverrides},MAX_FILE_SIZE2=2097152,BINARY_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD3=0.1,SYNTAX_CHECK_CONCURRENCY=8;function resolveGrammarIdForFile(filePath){let profileGrammarId=getProfileForFile(filePath)?.treeSitter?.grammarId,registryId=getLanguageForExtension(path384.extname(filePath).toLowerCase())?.id;if(profileGrammarId&®istryId&®istryId!==profileGrammarId)return registryId;return profileGrammarId}function isBinaryContent2(content){let sample=content.slice(0,BINARY_CHECK_BYTES),nullCount=0;for(let i=0;i<sample.length;i++)if(sample.charCodeAt(i)===0)nullCount++;return nullCount/sample.length>BINARY_NULL_THRESHOLD3}function extractSyntaxErrors(parser,content){let tree=parser.parse(content);if(!tree)return[];let errors5=[],stack=[tree.rootNode];while(stack.length>0){let node=stack.pop();if(node.type==="ERROR")errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:"Syntax error"});else if(node.isMissing)errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:`Missing '${node.type}'`});let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}if(errors5.length===0&&tree.rootNode.hasError)errors5.push({line:1,column:0,message:"Syntax error detected (tree has errors)"});return tree.delete(),errors5}async function syntaxCheck(input,directory,gates){return computeSyntaxCheck(input,directory,gates,{persistEvidence:!0})}async function computeSyntaxCheck(input,directory,gates,options){if(gates?.syntax_check?.enabled===!1)return{verdict:"pass",files:[],summary:"syntax_check disabled by configuration"};let{changed_files,mode="changed",languages}=input,filesToCheck=changed_files;if(mode==="changed")filesToCheck=filesToCheck.filter((f)=>f.additions>0);if(languages?.length){let lowerLangs=languages.map((l)=>l.toLowerCase());filesToCheck=filesToCheck.filter((file3)=>{let ext=path384.extname(file3.path).toLowerCase(),langDef=getLanguageForExtension(ext),langId=getProfileForFile(file3.path)?.id||langDef?.id;return langId?lowerLangs.includes(langId.toLowerCase()):!1})}let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));async function checkOneFile(fileInfo){let{path:filePath}=fileInfo,fullPath=path384.isAbsolute(filePath)?filePath:path384.join(directory,filePath),result={path:filePath,language:"",ok:!1,errors:[]};try{let profile=getProfileForFile(filePath),grammarId=resolveGrammarIdForFile(filePath),parser=null;if(grammarId)try{parser=await loadGrammar2(grammarId)}catch{parser=null}if(!parser)parser=await getParserForFile(filePath);if(!parser)return result.skipped_reason="unsupported_language",{result,counted:!1,failed:!1,skipped:!0};try{if(fs238.statSync(fullPath).size>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0}}catch{}let content;try{content=fs238.readFileSync(fullPath,"utf8")}catch{return result.skipped_reason="file_read_error",{result,counted:!1,failed:!1,skipped:!0}}if(content.length>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0};if(isBinaryContent2(content))return result.skipped_reason="binary_file",{result,counted:!1,failed:!1,skipped:!0};let ext=path384.extname(filePath).toLowerCase(),langDef=getLanguageForExtension(ext);result.language=profile?.id||langDef?.id||"unknown";let errors5=extractSyntaxErrors(parser,content);if(errors5.length>0)return result.ok=!1,result.errors=errors5,{result,counted:!0,failed:!0,skipped:!1};return result.ok=!0,{result,counted:!0,failed:!1,skipped:!1}}catch(error93){return result.skipped_reason=error93 instanceof Error?error93.message:"unknown_error",{result,counted:!0,failed:!1,skipped:!0}}}let limit=pLimit(SYNTAX_CHECK_CONCURRENCY),outcomes=await Promise.all(filesToCheck.map((fileInfo)=>limit(()=>checkOneFile(fileInfo)))),results=[],filesChecked=0,filesFailed=0,skippedCount=0;for(let outcome of outcomes){if(results.push(outcome.result),outcome.counted)filesChecked++;if(outcome.failed)filesFailed++;if(outcome.skipped)skippedCount++}let emptyCheckReasons=[];if(changed_files.length===0)emptyCheckReasons.push("no files were supplied in changed_files");else{if(mode==="changed")emptyCheckReasons.push("mode='changed' dropped files with additions === 0 (deletion-only or pure-rename entries); pass mode='all' to include them");if(languages?.length)emptyCheckReasons.push(`the languages filter [${languages.join(", ")}] matched no supplied file`);if(emptyCheckReasons.length===0)emptyCheckReasons.push("every supplied file was skipped as unsupported, unreadable, too large, or binary")}let verdict=filesFailed>0?"fail":filesChecked===0?"skip":"pass",summary=filesFailed>0?`Syntax errors found in ${filesFailed} of ${filesChecked} files`:filesChecked===0?`No files were checked — ${emptyCheckReasons.join("; ")}. This is NOT a passing syntax check.`:`All ${filesChecked} files passed syntax check`;if(options?.persistEvidence===!0)await _internals72.saveEvidence(directory,"syntax_check",{task_id:"syntax_check",type:"syntax",timestamp:new Date().toISOString(),agent:"syntax_check",verdict,summary,files_checked:filesChecked,files_failed:filesFailed,skipped_count:skippedCount,files:results});return{verdict,files:results,summary}}var syntax_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Check syntax of source files using tree-sitter parsers. Supports JS/TS, Python, Go, Rust, Java, C/C++, C#, PHP, Ruby. Returns JSON with syntax errors found per file.",args:{changed_files:exports_external.array(exports_external.object({path:exports_external.string(),additions:exports_external.number()})).describe("Files to check (from diff gate)"),mode:exports_external.enum(["changed","all"]).optional().describe("Check mode over the supplied changed_files. 'changed' (default) checks only entries with additions > 0, so deletion-only and pure-rename entries are excluded; 'all' checks every supplied entry. Neither mode enumerates the repository — this tool only ever inspects the files you pass in changed_files. If the filters leave nothing to check the verdict is 'skip', never 'pass'."),languages:exports_external.array(exports_external.string()).optional().describe("Optional: restrict to specific languages")},async execute(args2,directory){let gates=_internals331.loadGateOverrides(directory),result=await syntaxCheck(args2,directory,gates);return JSON.stringify(result)}});init_zod();init_analyzer();init_create_tool();init_resolve_working_directory();var test_impact=createSwarmTool({description:"Analyze which test files are impacted by changes to the given source files. Returns TestImpactResult with impactedTests, untestedFiles, and the full impact map.",args:{changedFiles:exports_external.array(exports_external.string()).describe("Array of source file paths to analyze for test impact"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.changedFiles||!Array.isArray(typedArgs.changedFiles)||typedArgs.changedFiles.length===0)return JSON.stringify({error:"changedFiles must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({error:resolved.message,success:!1},null,2);let cwd=resolved.directory,result=await analyzeImpact(typedArgs.changedFiles,cwd);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`test_impact failed: ${e.message}`:"test_impact failed: unknown error",success:!1},null,2)}}});init_test_runner();init_zod();init_config2();init_gate_evidence();init_utils();init_logger();init_task_id();init_create_tool();init_path_security();import*as fs239 from"node:fs";import*as path385 from"node:path";var MAX_TEXT_LENGTH=200,MAX_FILE_SIZE_BYTES10=1048576,MAX_RECORDED_DETAILS=50,SUPPORTED_EXTENSIONS3=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".ps1",".go",".java",".c",".cpp",".h",".cs",".rb",".php",".blade.php",".swift",".kt"]),SKIP_DIRECTORIES5=new Set(["node_modules","dist","build",".git",".swarm","coverage"]),PRIORITY_MAP={FIXME:"high",HACK:"high",XXX:"high",TODO:"medium",WARN:"medium",NOTE:"low"},SHELL_METACHAR_REGEX3=/[;&|%$`\\]/;function validateTagsInput(tags){if(!tags||tags.length===0)return"tags cannot be empty";if(containsControlChars(tags))return"tags contains control characters";if(SHELL_METACHAR_REGEX3.test(tags))return"tags contains shell metacharacters (;|&$`\\)";if(!/^[a-zA-Z0-9,\s]+$/.test(tags))return"tags contains invalid characters (only alphanumeric, commas, spaces allowed)";return null}function validatePathsInput(paths,cwd){if(!paths||paths.length===0)return{error:null,resolvedPath:cwd};if(containsControlChars(paths))return{error:"paths contains control characters",resolvedPath:null};if(containsPathTraversal(paths))return{error:"paths contains path traversal",resolvedPath:null};try{let resolvedPath=path385.resolve(paths),normalizedCwd=path385.resolve(cwd);if(!path385.resolve(resolvedPath).startsWith(normalizedCwd))return{error:"paths must be within the current working directory",resolvedPath:null};return{error:null,resolvedPath}}catch(e){return{error:e instanceof Error?e.message:"invalid paths",resolvedPath:null}}}function isSupportedExtension(filePath){let ext=path385.extname(filePath).toLowerCase();return SUPPORTED_EXTENSIONS3.has(ext)}function findSourceFiles3(dir,files=[]){let entries2;try{entries2=fs239.readdirSync(dir)}catch{return files}entries2.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries2){if(SKIP_DIRECTORIES5.has(entry))continue;let fullPath=path385.join(dir,entry),stat25;try{stat25=fs239.statSync(fullPath)}catch{continue}if(stat25.isDirectory())findSourceFiles3(fullPath,files);else if(stat25.isFile()){if(isSupportedExtension(fullPath))files.push(fullPath)}}return files}function parseTodoComments(content,filePath,tagsSet){let entries2=[],lines=content.split(`
|
|
7919
|
+
`)};return{valid:!0}}var ENV_FILE_VARIANT=/^\.env(\.|$)/i;function isProtectedForEcho(file3,fullPath,directory){let spellings=[file3];try{spellings.push(path383.relative(fs237.realpathSync.native(directory),fs237.realpathSync.native(fullPath)))}catch{return!0}return spellings.some((spelling)=>[spelling,spelling.toLowerCase()].some((candidate2)=>isPolicyProtectedPath(candidate2)||ENV_FILE_VARIANT.test(path383.basename(candidate2.replace(/\\/g,"/")))))}var suggestPatch=createSwarmTool({description:'Suggest a structured patch for specified files without modifying them. Returns context-based patch proposals with anchors for reviewer use. When format="unified", also produces a unified diff string consumable by apply_patch. '+"This is a read-only tool — it does not modify any files.",args:{targetFiles:exports_external.array(exports_external.string()).describe("Array of file paths to patch").min(1),changes:exports_external.array(exports_external.object({file:exports_external.string().describe("Path to the file this change applies to"),contextBefore:exports_external.array(exports_external.string()).optional().describe("Lines before the change region (anchor)"),contextAfter:exports_external.array(exports_external.string()).optional().describe("Lines after the change region (anchor)"),oldContent:exports_external.string().optional().describe("Current content to be replaced"),newContent:exports_external.string().describe("New content to replace with")})).describe("Array of change descriptions with context anchors").min(1),format:exports_external.enum(["json","unified"]).optional().default("json").describe('Output format: "json" (default, existing structured output) or "unified" (unified diff string for apply_patch)')},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"Could not parse suggest-patch arguments"},null,2);let obj=args2,targetFiles=obj.targetFiles??[],changes=obj.changes??[],format=obj.format??"json";if(!targetFiles||targetFiles.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"targetFiles cannot be empty"},null,2);if(!changes||changes.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"changes cannot be empty"},null,2);if(!fs237.existsSync(directory))return JSON.stringify({success:!1,error:!0,type:"file-not-found",message:"Workspace directory does not exist"},null,2);let patches=[],filesModifiedSet=new Set,errors5=[],unifiedDiffEntries=[],targetFileSet=new Set(targetFiles),skippedBinaryFiles=new Set;if(format==="unified"){for(let change of changes)if(isBinaryFile4(change.file))errors5.push({success:!1,error:!0,type:"parse-error",message:`Binary files are not supported in unified diff mode: ${change.file}`,details:{location:change.file}}),skippedBinaryFiles.add(change.file)}for(let changeIndex=0;changeIndex<changes.length;changeIndex++){let change=changes[changeIndex];if(format==="unified"&&skippedBinaryFiles.has(change.file))continue;if(!targetFileSet.has(change.file)){errors5.push({success:!1,error:!0,type:"parse-error",message:`File "${change.file}" is not in targetFiles`,details:{location:change.file}});continue}if(!validateFilePath2(change.file,directory)){errors5.push({success:!1,error:!0,type:"parse-error",message:`Invalid file path: ${change.file}`,details:{location:change.file}});continue}let fullPath=path383.resolve(directory,change.file);if(!fs237.existsSync(fullPath)){errors5.push({success:!1,error:!0,type:"file-not-found",message:`File not found: ${change.file}`,details:{location:change.file}});continue}let content;try{content=fs237.readFileSync(fullPath,"utf-8")}catch(err2){errors5.push({success:!1,error:!0,type:"unknown",message:`Could not read file: ${err2 instanceof Error?err2.message:String(err2)}`,details:{location:`${change.file}:0`}});continue}let contextMatch=findContextMatch(content,change.contextBefore,change.contextAfter,change.oldContent);if(!contextMatch){errors5.push({success:!1,error:!0,type:"context-mismatch",message:`Could not find context anchor in ${change.file}. Provide contextBefore/contextAfter lines to locate the change region.`,details:{location:change.file}});continue}let lines=splitDiffLines(content),oldContentValidation=validateOldContent(lines,contextMatch,change.oldContent);if(!oldContentValidation.valid){let actualRedacted=isProtectedForEcho(change.file,fullPath,directory);errors5.push({success:!1,error:!0,type:"context-mismatch",message:"Content at the specified location does not match oldContent",details:{expected:oldContentValidation.expected,actual:actualRedacted?"[redacted: protected path]":oldContentValidation.actual,location:`${change.file}:${contextMatch.startLineIndex+1}-${contextMatch.endLineIndex+1}`}});continue}let originalContext=[...contextMatch.matchedBefore,...contextMatch.matchedAfter.length>0?["..."]:[],...contextMatch.matchedAfter];if(patches.push({file:change.file,originalContext,newContent:change.newContent,hunkIndex:changeIndex}),filesModifiedSet.add(change.file),format==="unified")unifiedDiffEntries.push({file:change.file,contextMatch,oldContent:change.oldContent,newContent:change.newContent})}if(patches.length>0){let baseResult={success:!0,patches,filesModified:Array.from(filesModifiedSet),...errors5.length>0&&{errors:errors5}};if(format==="unified"){let fileGroups=new Map;for(let entry of unifiedDiffEntries){let group=fileGroups.get(entry.file)??[];group.push(entry),fileGroups.set(entry.file,group)}let unifiedParts=[];for(let[file3,entries2]of fileGroups){entries2.sort((a,b)=>a.contextMatch.startLineIndex-b.contextMatch.startLineIndex);let entryFullPath=path383.resolve(directory,file3),entryContent;try{entryContent=fs237.readFileSync(entryFullPath,"utf-8")}catch{continue}unifiedParts.push(generateFileHeader(file3));for(let entry of entries2)unifiedParts.push(generateHunk(entryContent,entry.contextMatch,entry.oldContent,entry.newContent))}let unifiedPatch=unifiedParts.join("");return JSON.stringify({...baseResult,unifiedPatch},null,2)}return JSON.stringify(baseResult,null,2)}if(errors5.length===1)return JSON.stringify(errors5[0],null,2);return JSON.stringify({success:!1,error:!0,type:"context-mismatch",message:`All ${errors5.length} patch suggestions failed`,errors:errors5},null,2)}});init_zod();init_loader();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();function getContextAgent2(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}var ArgsSchema5=exports_external.object({phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),parent_agent:exports_external.string().min(1).optional(),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()}),summarize_work=createSwarmTool({description:`Emit a short structured summary of the work you just completed (key decisions, assumptions, risks, constraints observed/violated). Call this once at task completion. Keep the summary under ${MAX_AGENT_SUMMARY_WORDS} words and each list to ${MAX_LIST_ITEMS} items — longer content is truncated, not rejected. These `+"summaries roll up per phase and are reviewed by the architecture supervisor to catch cross-task contradictions, drift, and repeated failure loops. Advisory only.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number this work belongs to."),summary:exports_external.string().min(1).describe(`One-paragraph summary of what you did (<= ${MAX_AGENT_SUMMARY_WORDS} words).`),task_id:exports_external.string().min(1).optional().describe('Task ID this summary covers (e.g. "1.2").'),parent_agent:exports_external.string().min(1).optional().describe("The agent that delegated this task, if any."),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()},execute:async(rawArgs,directory,ctx)=>{let parsed=ArgsSchema5.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,sessionId=ctx?.sessionID??"unknown-session",agent=getContextAgent2(ctx)??"unknown-agent",maxWords=MAX_AGENT_SUMMARY_WORDS;try{maxWords=loadPluginConfig(workingDir).architectural_supervision?.max_agent_summary_words??maxWords}catch{}let summary=normalizeAgentWorkSummary({phase:args2.phase,task_id:args2.task_id,session_id:sessionId,agent,parent_agent:args2.parent_agent,summary:args2.summary,key_decisions:args2.key_decisions,constraints_observed:args2.constraints_observed,constraints_violated:args2.constraints_violated,assumptions:args2.assumptions,risks:args2.risks,files_touched:args2.files_touched,evidence_refs:args2.evidence_refs},maxWords),storedTaskId=await writeAgentSummary(workingDir,summary);return JSON.stringify({success:!0,stored_task_id:storedTaskId,phase:summary.phase,agent:summary.agent,truncated:summary.truncated??!1},null,2)}});init_zod();init_command_dispatch();init_tool_policy();init_create_tool();function createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Run supported /swarm commands through the canonical opencode-swarm command registry. Return the tool output verbatim to the user.",args:{command:exports_external.enum(SWARM_COMMAND_TOOL_COMMANDS).describe("The /swarm subcommand to run, without the /swarm prefix."),args:exports_external.array(exports_external.string()).default([]).describe("Additional command arguments as separate tokens.")},async execute(rawArgs,directory,ctx){let args2=rawArgs;return(await executeSwarmCommand({directory,agents,sessionID:ctx?.sessionID??"",tokens:[args2.command,...args2.args??[]],policy:classifySwarmCommandToolUse,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,activeAgentName:getActiveAgentName?.(ctx?.sessionID??"")})).text}})}var swarm_command=createSwarmCommandTool({});init_zod();init_config2();init_memory();init_state();init_create_tool();import{createHash as createHash121}from"node:crypto";var OutcomeArgsSchema=exports_external.object({memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional(),question:exports_external.string().trim().min(1).max(2000).optional(),outcome:exports_external.enum(["useful","dead_end","corrected"]),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional(),correction:exports_external.string().trim().min(1).max(4000).optional()}).strict().superRefine((value,context)=>{if(Boolean(value.memory_id)===Boolean(value.question))context.addIssue({code:"custom",message:"exactly one of memory_id or question is required"});if(value.outcome==="corrected"&&!value.correction)context.addIssue({code:"custom",message:"corrected outcomes require correction text"})}),swarm_memory_outcome=createSwarmTool({description:"Record whether recalled memory or a graph answer was useful, a dead end, or corrected; when reflection is enabled, synchronously refresh deterministic reflection artifacts.",args:{memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional().describe("Existing memory id to update"),question:exports_external.string().trim().min(1).max(2000).optional().describe("Question for a lightweight result memory when no id is known"),outcome:exports_external.enum(["useful","dead_end","corrected"]).describe("Observed result"),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional().describe("Repository-relative file and optional symbol anchors"),correction:exports_external.string().trim().min(1).max(4000).optional().describe("Required corrected claim text for corrected outcomes")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals328.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=OutcomeArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=typeof ctx?.agent==="string"?ctx.agent:void 0,taskId=ctx?.sessionID?_internals328.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals328.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId:taskId},{config:config3.memory}),eventId=ctx?.sessionID&&ctx.messageID?`tool-${createHash121("sha256").update(JSON.stringify({sessionID:ctx.sessionID,messageID:ctx.messageID,args:parsed.data})).digest("hex").slice(0,32)}`:void 0;try{let result=await _internals328.recordOutcomeWithReflection(directory,config3.memory,gateway,{memoryId:parsed.data.memory_id,question:parsed.data.question,outcome:parsed.data.outcome,anchors:parsed.data.anchors,correction:parsed.data.correction,eventId}),reflectionUpdated=result.reflectionUpdated,reflectionAttempted=result.reflectionAttempted,partial3=result.reflectionEnabled===!0&&reflectionAttempted&&!reflectionUpdated,reflectionError="error"in result?result.error:void 0;return JSON.stringify({success:!0,status:partial3?"partial":"complete",partial:partial3,outcome_recorded:result.outcomeRecorded,event_id:result.eventId,memory_id:result.record.id,outcome:parsed.data.outcome,outcomes:result.record.outcomes?.length??0,reflection_enabled:result.reflectionEnabled,reflection_attempted:reflectionAttempted,reflection_updated:reflectionUpdated,reflection_entries:reflectionUpdated?result.digest.generatedFrom.entries:void 0,error:partial3?reflectionError:void 0,reflection_error:partial3?reflectionError:void 0},null,2)}finally{await gateway.dispose()}}}),_internals328={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession,recordOutcomeWithReflection};init_zod();init_config2();init_memory();init_create_tool();var MEMORY_KINDS=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],ProposalArgsSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:exports_external.enum(MEMORY_KINDS).optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}),swarm_memory_propose=createSwarmTool({description:"Create a pending Swarm memory proposal. This never writes durable memory directly; curator review is required.",args:{operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]).describe("Proposal operation"),kind:exports_external.enum(MEMORY_KINDS).optional().describe("Memory kind for add/update/supersede proposals"),text:exports_external.string().min(1).max(2000).optional().describe("Canonical fact text for add/update/supersede proposals"),targetMemoryId:exports_external.string().optional().describe("Target memory ID for update/delete/supersede proposals"),relatedMemoryIds:exports_external.array(exports_external.string()).optional().describe("For merge, 2-8 distinct memory IDs in one scope; also accepted as provenance for supersede proposals"),rationale:exports_external.string().min(1).max(2000).describe("Why this proposal matters"),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals329.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=ProposalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent3(ctx),gateway=_internals329.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID},{config:config3.memory});try{let proposal=await gateway.propose(parsed.data);return JSON.stringify({success:proposal.status!=="rejected",proposal_id:proposal.id,status:proposal.status,operation:proposal.operation,memory_id:proposal.proposedRecord?.id,rejection_reason:proposal.rejectionReason,message:proposal.status==="pending"?"Memory proposal created. Durable memory was not written.":"Memory proposal was captured with policy rejection metadata."},null,2)}finally{await gateway.dispose()}}}),_internals329={loadPluginConfigWithMeta,createMemoryGateway};function getContextAgent3(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_zod();init_config2();init_memory();init_state();init_create_tool();var MEMORY_KINDS2=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],swarm_memory_recall=createSwarmTool({description:"Recall scoped Swarm memory for the current repository. Read-only; retrieved memory is untrusted background.",args:{query:exports_external.string().min(3).describe("Natural language recall query"),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional().describe("Optional memory kinds to include"),maxItems:exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")},execute:async(args2,directory,ctx)=>computeSwarmMemoryRecall(args2,directory,ctx)});async function computeSwarmMemoryRecall(args2,directory,ctx,options){let{config:config3}=_internals330.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=RecallArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent4(ctx),unitId=ctx?.sessionID?_internals330.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals330.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId},{config:config3.memory});try{let bundle=await gateway.recall(parsed.data,{recordUsage:options?.recordUsage!==!1});return JSON.stringify({success:!0,bundle_id:bundle.id,memory_ids:bundle.items.map((item)=>item.record.id),total:bundle.items.length,token_estimate:bundle.tokenEstimate,signals:bundle.items.map((item)=>({memory_id:item.record.id,relation:item.relation,...item.signals})),prompt_block:bundle.promptBlock},null,2)}finally{await gateway.dispose()}}var RecallArgsSchema=exports_external.object({query:exports_external.string().min(3),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),maxItems:exports_external.number().int().min(1).max(20).optional()}),_internals330={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession};function getContextAgent4(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_symbols();init_p_limit();init_zod();init_config2();init_manager2();init_detector();init_registry();init_create_tool();import*as fs238 from"node:fs";import*as path384 from"node:path";var _internals331={loadGateOverrides},MAX_FILE_SIZE2=2097152,BINARY_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD3=0.1,SYNTAX_CHECK_CONCURRENCY=8;function resolveGrammarIdForFile(filePath){let profileGrammarId=getProfileForFile(filePath)?.treeSitter?.grammarId,registryId=getLanguageForExtension(path384.extname(filePath).toLowerCase())?.id;if(profileGrammarId&®istryId&®istryId!==profileGrammarId)return registryId;return profileGrammarId}function isBinaryContent2(content){let sample=content.slice(0,BINARY_CHECK_BYTES),nullCount=0;for(let i=0;i<sample.length;i++)if(sample.charCodeAt(i)===0)nullCount++;return nullCount/sample.length>BINARY_NULL_THRESHOLD3}function extractSyntaxErrors(parser,content){let tree=parser.parse(content);if(!tree)return[];let errors5=[],stack=[tree.rootNode];while(stack.length>0){let node=stack.pop();if(node.type==="ERROR")errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:"Syntax error"});else if(node.isMissing)errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:`Missing '${node.type}'`});let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}if(errors5.length===0&&tree.rootNode.hasError)errors5.push({line:1,column:0,message:"Syntax error detected (tree has errors)"});return tree.delete(),errors5}async function syntaxCheck(input,directory,gates){return computeSyntaxCheck(input,directory,gates,{persistEvidence:!0})}async function computeSyntaxCheck(input,directory,gates,options){if(gates?.syntax_check?.enabled===!1)return{verdict:"pass",files:[],summary:"syntax_check disabled by configuration"};let{changed_files,mode="changed",languages}=input,filesToCheck=changed_files;if(mode==="changed")filesToCheck=filesToCheck.filter((f)=>f.additions>0);if(languages?.length){let lowerLangs=languages.map((l)=>l.toLowerCase());filesToCheck=filesToCheck.filter((file3)=>{let ext=path384.extname(file3.path).toLowerCase(),langDef=getLanguageForExtension(ext),langId=getProfileForFile(file3.path)?.id||langDef?.id;return langId?lowerLangs.includes(langId.toLowerCase()):!1})}let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));async function checkOneFile(fileInfo){let{path:filePath}=fileInfo,fullPath=path384.isAbsolute(filePath)?filePath:path384.join(directory,filePath),result={path:filePath,language:"",ok:!1,errors:[]};try{let profile=getProfileForFile(filePath),grammarId=resolveGrammarIdForFile(filePath),parser=null;if(grammarId)try{parser=await loadGrammar2(grammarId)}catch{parser=null}if(!parser)parser=await getParserForFile(filePath);if(!parser)return result.skipped_reason="unsupported_language",{result,counted:!1,failed:!1,skipped:!0};try{if(fs238.statSync(fullPath).size>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0}}catch{}let content;try{content=fs238.readFileSync(fullPath,"utf8")}catch{return result.skipped_reason="file_read_error",{result,counted:!1,failed:!1,skipped:!0}}if(content.length>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0};if(isBinaryContent2(content))return result.skipped_reason="binary_file",{result,counted:!1,failed:!1,skipped:!0};let ext=path384.extname(filePath).toLowerCase(),langDef=getLanguageForExtension(ext);result.language=profile?.id||langDef?.id||"unknown";let errors5=extractSyntaxErrors(parser,content);if(errors5.length>0)return result.ok=!1,result.errors=errors5,{result,counted:!0,failed:!0,skipped:!1};return result.ok=!0,{result,counted:!0,failed:!1,skipped:!1}}catch(error93){return result.skipped_reason=error93 instanceof Error?error93.message:"unknown_error",{result,counted:!0,failed:!1,skipped:!0}}}let limit=pLimit(SYNTAX_CHECK_CONCURRENCY),outcomes=await Promise.all(filesToCheck.map((fileInfo)=>limit(()=>checkOneFile(fileInfo)))),results=[],filesChecked=0,filesFailed=0,skippedCount=0;for(let outcome of outcomes){if(results.push(outcome.result),outcome.counted)filesChecked++;if(outcome.failed)filesFailed++;if(outcome.skipped)skippedCount++}let emptyCheckReasons=[];if(changed_files.length===0)emptyCheckReasons.push("no files were supplied in changed_files");else{if(mode==="changed")emptyCheckReasons.push("mode='changed' dropped files with additions === 0 (deletion-only or pure-rename entries); pass mode='all' to include them");if(languages?.length)emptyCheckReasons.push(`the languages filter [${languages.join(", ")}] matched no supplied file`);if(emptyCheckReasons.length===0)emptyCheckReasons.push("every supplied file was skipped as unsupported, unreadable, too large, or binary")}let verdict=filesFailed>0?"fail":filesChecked===0?"skip":"pass",summary=filesFailed>0?`Syntax errors found in ${filesFailed} of ${filesChecked} files`:filesChecked===0?`No files were checked — ${emptyCheckReasons.join("; ")}. This is NOT a passing syntax check.`:`All ${filesChecked} files passed syntax check`;if(options?.persistEvidence===!0)await _internals72.saveEvidence(directory,"syntax_check",{task_id:"syntax_check",type:"syntax",timestamp:new Date().toISOString(),agent:"syntax_check",verdict,summary,files_checked:filesChecked,files_failed:filesFailed,skipped_count:skippedCount,files:results});return{verdict,files:results,summary}}var syntax_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Check syntax of source files using tree-sitter parsers. Supports JS/TS, Python, Go, Rust, Java, C/C++, C#, PHP, Ruby. Returns JSON with syntax errors found per file.",args:{changed_files:exports_external.array(exports_external.object({path:exports_external.string(),additions:exports_external.number()})).describe("Files to check (from diff gate)"),mode:exports_external.enum(["changed","all"]).optional().describe("Check mode over the supplied changed_files. 'changed' (default) checks only entries with additions > 0, so deletion-only and pure-rename entries are excluded; 'all' checks every supplied entry. Neither mode enumerates the repository — this tool only ever inspects the files you pass in changed_files. If the filters leave nothing to check the verdict is 'skip', never 'pass'."),languages:exports_external.array(exports_external.string()).optional().describe("Optional: restrict to specific languages")},async execute(args2,directory){let gates=_internals331.loadGateOverrides(directory),result=await syntaxCheck(args2,directory,gates);return JSON.stringify(result)}});init_zod();init_analyzer();init_create_tool();init_resolve_working_directory();var test_impact=createSwarmTool({description:"Analyze which test files are impacted by changes to the given source files. Returns TestImpactResult with impactedTests, untestedFiles, and the full impact map.",args:{changedFiles:exports_external.array(exports_external.string()).describe("Array of source file paths to analyze for test impact"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.changedFiles||!Array.isArray(typedArgs.changedFiles)||typedArgs.changedFiles.length===0)return JSON.stringify({error:"changedFiles must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({error:resolved.message,success:!1},null,2);let cwd=resolved.directory,result=await analyzeImpact(typedArgs.changedFiles,cwd);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`test_impact failed: ${e.message}`:"test_impact failed: unknown error",success:!1},null,2)}}});init_test_runner();init_zod();init_config2();init_gate_evidence();init_utils();init_logger();init_task_id();init_create_tool();init_path_security();import*as fs239 from"node:fs";import*as path385 from"node:path";var MAX_TEXT_LENGTH=200,MAX_FILE_SIZE_BYTES10=1048576,MAX_RECORDED_DETAILS=50,SUPPORTED_EXTENSIONS3=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".ps1",".go",".java",".c",".cpp",".h",".cs",".rb",".php",".blade.php",".swift",".kt"]),SKIP_DIRECTORIES5=new Set(["node_modules","dist","build",".git",".swarm","coverage"]),PRIORITY_MAP={FIXME:"high",HACK:"high",XXX:"high",TODO:"medium",WARN:"medium",NOTE:"low"},SHELL_METACHAR_REGEX3=/[;&|%$`\\]/;function validateTagsInput(tags){if(!tags||tags.length===0)return"tags cannot be empty";if(containsControlChars(tags))return"tags contains control characters";if(SHELL_METACHAR_REGEX3.test(tags))return"tags contains shell metacharacters (;|&$`\\)";if(!/^[a-zA-Z0-9,\s]+$/.test(tags))return"tags contains invalid characters (only alphanumeric, commas, spaces allowed)";return null}function validatePathsInput(paths,cwd){if(!paths||paths.length===0)return{error:null,resolvedPath:cwd};if(containsControlChars(paths))return{error:"paths contains control characters",resolvedPath:null};if(containsPathTraversal(paths))return{error:"paths contains path traversal",resolvedPath:null};try{let resolvedPath=path385.resolve(paths),normalizedCwd=path385.resolve(cwd);if(!path385.resolve(resolvedPath).startsWith(normalizedCwd))return{error:"paths must be within the current working directory",resolvedPath:null};return{error:null,resolvedPath}}catch(e){return{error:e instanceof Error?e.message:"invalid paths",resolvedPath:null}}}function isSupportedExtension(filePath){let ext=path385.extname(filePath).toLowerCase();return SUPPORTED_EXTENSIONS3.has(ext)}function findSourceFiles3(dir,files=[]){let entries2;try{entries2=fs239.readdirSync(dir)}catch{return files}entries2.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries2){if(SKIP_DIRECTORIES5.has(entry))continue;let fullPath=path385.join(dir,entry),stat25;try{stat25=fs239.statSync(fullPath)}catch{continue}if(stat25.isDirectory())findSourceFiles3(fullPath,files);else if(stat25.isFile()){if(isSupportedExtension(fullPath))files.push(fullPath)}}return files}function parseTodoComments(content,filePath,tagsSet){let entries2=[],lines=content.split(`
|
|
7920
7920
|
`),tagPattern=Array.from(tagsSet).map(escapeRegex2).join("|"),regex=new RegExp(`\\b(${tagPattern})\\b[:\\s]?`,"i");for(let i=0;i<lines.length;i++){let line=lines[i],match=regex.exec(line);if(match){let tag=match[1].toUpperCase(),priority=PRIORITY_MAP[tag]||"medium",text=line.substring(match.index+match[0].length).trim();if(text=text.replace(/^[/*\-\s]+/,""),text.length>MAX_TEXT_LENGTH)text=`${text.substring(0,MAX_TEXT_LENGTH-3)}...`;entries2.push({file:filePath,line:i+1,tag,text,priority})}}return entries2}var todo_extract=createSwarmTool({description:"Scan the codebase for TODO/FIXME/HACK/XXX/WARN/NOTE comments. Returns JSON with count by priority and sorted entries. Useful for identifying pending tasks and code issues. When task_id is provided and the todo_gate config is enabled (default), the high-priority scan is also recorded as todo_scan gate evidence for that task, consumed by check_gate_status and the phase-complete todo_gate gate.",args:{paths:exports_external.string().optional().describe("Directory or file to scan (default: entire project/cwd)"),tags:exports_external.string().optional().describe("Comma-separated tags to search for (default: TODO,FIXME,HACK,XXX,WARN,NOTE)"),task_id:exports_external.string().regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "2.3.1")').optional().describe("Optional task ID (N.M format). When provided and todo_gate is enabled, the high-priority (FIXME/HACK/XXX) count is recorded as todo_scan gate evidence in .swarm/evidence/{task_id}.json")},async execute(args2,directory){let paths,tags,taskId;try{if(args2&&typeof args2==="object"){let obj=args2;paths=typeof obj.paths==="string"?obj.paths:void 0,tags=typeof obj.tags==="string"?obj.tags:void 0,taskId=typeof obj.task_id==="string"?obj.task_id:void 0}}catch{}let cwd=directory,tagsInput=tags||"TODO,FIXME,HACK,XXX,WARN,NOTE",tagsValidationError=validateTagsInput(tagsInput);if(tagsValidationError){let errorResult={error:`invalid tags: ${tagsValidationError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let tagsList=tagsInput.split(",").map((t)=>t.trim().toUpperCase()).filter((t)=>t.length>0),tagsSet=new Set(tagsList);if(tagsSet.size===0)return JSON.stringify({error:"invalid tags: no valid tags provided",total:0,byPriority:{high:0,medium:0,low:0},entries:[]},null,2);let pathsInput=paths||cwd,{error:pathsError,resolvedPath}=validatePathsInput(pathsInput,cwd);if(pathsError){let errorResult={error:`invalid paths: ${pathsError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let scanPath=resolvedPath;if(!fs239.existsSync(scanPath)){let errorResult={error:`path not found: ${pathsInput}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let filesToScan=[];if(fs239.statSync(scanPath).isFile())if(isSupportedExtension(scanPath))filesToScan.push(scanPath);else{let errorResult={error:`unsupported file extension: ${path385.extname(scanPath)}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}else findSourceFiles3(scanPath,filesToScan);let allEntries=[];for(let filePath of filesToScan)try{if(fs239.statSync(filePath).size>MAX_FILE_SIZE_BYTES10)continue;let content=fs239.readFileSync(filePath,"utf-8"),entries2=parseTodoComments(content,filePath,tagsSet);allEntries.push(...entries2)}catch{}allEntries.sort((a,b)=>{let priorityOrder={high:0,medium:1,low:2},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.file.toLowerCase().localeCompare(b.file.toLowerCase())});let byPriority={high:allEntries.filter((e)=>e.priority==="high").length,medium:allEntries.filter((e)=>e.priority==="medium").length,low:allEntries.filter((e)=>e.priority==="low").length},result={total:allEntries.length,byPriority,entries:allEntries},coversHighPriorityClass=["FIXME","HACK","XXX"].every((tag)=>tagsSet.has(tag));if(taskId&&isStrictTaskId(taskId))if(!coversHighPriorityClass)log("todo_extract: todo_scan evidence recording skipped — custom tags omit the FIXME/HACK/XXX high-priority class");else try{let{config:config3}=loadPluginConfigWithMeta(directory);if(config3.todo_gate?.enabled!==!1){let detailLines=allEntries.filter((entry)=>entry.priority==="high").slice(0,MAX_RECORDED_DETAILS).map((entry)=>{return`${path385.relative(directory,entry.file)}:${entry.line} ${entry.tag} ${entry.text}`});await recordTodoScanEvidence(directory,taskId,{priority:"high",count:byPriority.high,details:detailLines,recorded_at:new Date().toISOString()})}}catch(recordError){log("todo_extract: todo_scan evidence recording skipped",recordError)}return JSON.stringify(result,null,2)}});init_update_task_status();init_zod();init_loader();import{lookup}from"node:dns/promises";import*as http from"node:http";import*as https from"node:https";import{isIP}from"node:net";import{Readable}from"node:stream";import*as zlib from"node:zlib";init_utils2();init_redaction();init_project_boundary();import{createHash as createHash122}from"node:crypto";import{appendFile as appendFile11,mkdir as mkdir50}from"node:fs/promises";import*as path386 from"node:path";var EVIDENCE_CACHE_FILE2="evidence-cache/documents.jsonl",MAX_EVIDENCE_TEXT_LENGTH=4000;async function writeEvidenceDocuments(directory,inputs,now2=()=>new Date){assertProjectRoot(directory);let filePath=validateSwarmPath(directory,EVIDENCE_CACHE_FILE2),capturedAt=now2().toISOString(),records=inputs.map((input)=>createEvidenceDocumentRecord(input,capturedAt)).filter((record3)=>record3!==null);if(records.length>0)await mkdir50(path386.dirname(filePath),{recursive:!0}),await appendFile11(filePath,`${records.map((record3)=>JSON.stringify(record3)).join(`
|
|
7921
7921
|
`)}
|
|
7922
7922
|
`,"utf-8");return{path:".swarm/evidence-cache/documents.jsonl",records,refs:records.map((record3)=>record3.ref)}}function createEvidenceDocumentRecord(input,defaultCapturedAt){let text=normalizeEvidenceText(input.text??input.snippet??"");if(!text)return null;let capturedAt=input.capturedAt??defaultCapturedAt,base={sourceType:input.sourceType,query:normalizeOptional(input.query),title:normalizeOptional(input.title),url:normalizeOptional(input.url),text},id=createEvidenceDocumentId(base);return{id,ref:`evidence-cache:${id}`,...base,capturedAt,createdBy:normalizeOptional(input.createdBy),metadata:input.metadata??{}}}function createEvidenceDocumentId(input){return`evd_${createHash122("sha256").update([input.sourceType,input.query??"",input.title??"",input.url??"",input.text].join(`
|
|
@@ -7937,7 +7937,7 @@ ${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable()
|
|
|
7937
7937
|
${tailContent.join(`
|
|
7938
7938
|
`)}
|
|
7939
7939
|
${footerLines.join(`
|
|
7940
|
-
`)}`}init_core_events();init_skill_propagation_gate();init_warning_buffer();init_canonical_root();init_cache_paths();import*as fs247 from"node:fs";import*as os32 from"node:os";import*as path395 from"node:path";import*as fs246 from"node:fs";import*as path394 from"node:path";var _internals341={realpathSyncNative:fs246.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path394.resolve(hostWindowsPath(input));try{return _internals341.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path394.join(hostNormalizePath(dir),"*")}init_lane_context();class LastWinsRuleMap{entries=new Map;set(pattern,action2){this.entries.delete(pattern),this.entries.set(pattern,action2)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path395.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path395.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key3=canonicalRootKeyFresh(resolved);if(seen.has(key3))return;seen.add(key3),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os32.tmpdir();if(push(out,seen,path395.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path395.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path395.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os32.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path395.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path395.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path395.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path395.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path395.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative103 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path395.resolve(base,relative103),`skill root (${label}): ${relative103}`);if(home)push(out,seen,path395.resolve(home,relative103),`skill root (user level): ~/${relative103}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path395.join(home,configured.slice(2)):configured;push(out,seen,path395.isAbsolute(expanded)?expanded:path395.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action2]of Object.entries(user)){if(action2==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action2)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals342={resolveLaneContext,addDeferredWarning,appendFileSync:fs247.appendFileSync,mkdirSync:fs247.mkdirSync};function readConfiguredSkillList(opencodeConfig,key3){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key3];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action2]of Object.entries(map3)){if(action2!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{appendCoreEventSync(directory,event)}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals342.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals342.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();init_contracts2();init_factory();init_hash();init_patch();init_protected_path_policy();init_git_executable();init_path_security();init_project_boundary();init_contracts2();init_hash();import{spawn as spawn6}from"node:child_process";import{createHash as createHash124}from"node:crypto";import{existsSync as existsSync204,lstatSync as lstatSync45}from"node:fs";import*as path396 from"node:path";var SHA_RE4=/^[a-f0-9]{40,64}$/,RECORD_VERSION2=1,GIT_TIMEOUT_MS13=3000,MAX_GIT_OUTPUT_BYTES3=32768,TEXT_DECODER=new TextDecoder("utf-8",{fatal:!0});function normalizeRelativePath2(value){return value.replace(/\\/g,"/").replace(/^\.\/+/,"")}function decodeQuotedGitPathToken(value){if(!value.startsWith('"')||!value.endsWith('"'))return null;let decoded="";for(let index=1;index<value.length-1;index++){let current=value[index];if(current!=="\\"){decoded+=current;continue}let next=value[index+1];if(!next)return null;if(/[0-7]/.test(next)){let octal=next,cursor=index+2;while(cursor<value.length-1&&octal.length<3){let digit=value[cursor];if(!/[0-7]/.test(digit))break;octal+=digit,cursor++}decoded+=String.fromCharCode(Number.parseInt(octal,8)),index+=octal.length;continue}decoded+=next==="t"?"\t":next==="n"?`
|
|
7940
|
+
`)}`}init_core_events();init_skill_propagation_gate();init_warning_buffer();init_canonical_root();init_cache_paths();import*as fs247 from"node:fs";import*as os32 from"node:os";import*as path395 from"node:path";import*as fs246 from"node:fs";import*as path394 from"node:path";var _internals341={realpathSyncNative:fs246.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path394.resolve(hostWindowsPath(input));try{return _internals341.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path394.join(hostNormalizePath(dir),"*")}init_lane_context();class LastWinsRuleMap{entries=new Map;set(pattern,action2){this.entries.delete(pattern),this.entries.set(pattern,action2)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path395.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path395.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key3=canonicalRootKeyFresh(resolved);if(seen.has(key3))return;seen.add(key3),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os32.tmpdir();if(push(out,seen,path395.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path395.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path395.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os32.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path395.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path395.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path395.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path395.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path395.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative104 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path395.resolve(base,relative104),`skill root (${label}): ${relative104}`);if(home)push(out,seen,path395.resolve(home,relative104),`skill root (user level): ~/${relative104}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path395.join(home,configured.slice(2)):configured;push(out,seen,path395.isAbsolute(expanded)?expanded:path395.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action2]of Object.entries(user)){if(action2==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action2)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals342={resolveLaneContext,addDeferredWarning,appendFileSync:fs247.appendFileSync,mkdirSync:fs247.mkdirSync};function readConfiguredSkillList(opencodeConfig,key3){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key3];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action2]of Object.entries(map3)){if(action2!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{appendCoreEventSync(directory,event)}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals342.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals342.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();init_contracts2();init_factory();init_hash();init_patch();init_protected_path_policy();init_git_executable();init_path_security();init_project_boundary();init_contracts2();init_hash();import{spawn as spawn6}from"node:child_process";import{createHash as createHash124}from"node:crypto";import{existsSync as existsSync204,lstatSync as lstatSync45}from"node:fs";import*as path396 from"node:path";var SHA_RE4=/^[a-f0-9]{40,64}$/,RECORD_VERSION2=1,GIT_TIMEOUT_MS13=3000,MAX_GIT_OUTPUT_BYTES3=32768,TEXT_DECODER=new TextDecoder("utf-8",{fatal:!0});function normalizeRelativePath2(value){return value.replace(/\\/g,"/").replace(/^\.\/+/,"")}function decodeQuotedGitPathToken(value){if(!value.startsWith('"')||!value.endsWith('"'))return null;let decoded="";for(let index=1;index<value.length-1;index++){let current=value[index];if(current!=="\\"){decoded+=current;continue}let next=value[index+1];if(!next)return null;if(/[0-7]/.test(next)){let octal=next,cursor=index+2;while(cursor<value.length-1&&octal.length<3){let digit=value[cursor];if(!/[0-7]/.test(digit))break;octal+=digit,cursor++}decoded+=String.fromCharCode(Number.parseInt(octal,8)),index+=octal.length;continue}decoded+=next==="t"?"\t":next==="n"?`
|
|
7941
7941
|
`:next==="r"?"\r":next==="b"?"\b":next==="f"?"\f":next,index++}return decoded}function parseGitPathToken(value,startIndex=0){if(startIndex>=value.length)return null;if(value[startIndex]==='"'){let index2=startIndex+1;while(index2<value.length){let current=value[index2];if(current==="\\"){index2+=2;continue}if(current==='"')return{token:value.slice(startIndex,index2+1),nextIndex:index2+1};index2++}return null}let index=startIndex;while(index<value.length&&value[index]!==" ")index++;return{token:value.slice(startIndex,index),nextIndex:index}}function parseGitPathValue(value,expectedPrefix){let trimmed=value.trim(),parsed=parseGitPathToken(trimmed);if(!parsed||parsed.nextIndex!==value.trim().length)return null;let decoded=parsed.token.startsWith('"')?decodeQuotedGitPathToken(parsed.token):parsed.token;if(!decoded)return null;if(decoded==="/dev/null")return decoded;if(expectedPrefix&&!decoded.startsWith(expectedPrefix))return null;return normalizeRelativePath2(expectedPrefix?decoded.slice(expectedPrefix.length):decoded)}function parseGitHeaderPath(line,headerPrefix,expectedPathPrefix){if(!line.startsWith(headerPrefix))return null;return parseGitPathValue(line.slice(headerPrefix.length),expectedPathPrefix)}function parseDiffGitLine(line){if(!line.startsWith("diff --git "))return null;let body=line.slice(11),oldToken=parseGitPathToken(body);if(!oldToken)return null;let cursor=oldToken.nextIndex;while(cursor<body.length&&body[cursor]===" ")cursor++;let newToken=parseGitPathToken(body,cursor);if(!newToken)return null;cursor=newToken.nextIndex;while(cursor<body.length&&body[cursor]===" ")cursor++;if(cursor!==body.length)return null;let oldDecoded=parseGitPathValue(oldToken.token,"a/"),newDecoded=parseGitPathValue(newToken.token,"b/");if(!oldDecoded||!newDecoded)return null;return{oldPath:oldDecoded,newPath:newDecoded}}function isWithinPrefix(relativePath2,prefix){return relativePath2===prefix||relativePath2.startsWith(`${prefix}/`)}function isAllowlisted(relativePath2,allowlist){return allowlist.some((prefix)=>isWithinPrefix(relativePath2,normalizeRelativePath2(prefix)))}function isProtectedPath4(relativePath2,extraProtectedPaths){return isPolicyProtectedPath(relativePath2,{additional:[".opencode",".claude",".agents","dist","evaluation-fixtures","src/services/skill-improver","src/services/skill-optimizer","src/evidence","scripts",...extraProtectedPaths]})}function parseCount(token){if(!token)return 1;let parsed=Number.parseInt(token,10);return Number.isFinite(parsed)&&parsed>=0?parsed:-1}function validateParsedHunk(hunk){if(hunk.oldCount<0||hunk.newCount<0)return!1;if(hunk.oldCount===0?hunk.oldStart<0:hunk.oldStart<1)return!1;if(hunk.newCount===0?hunk.newStart<0:hunk.newStart<1)return!1;let oldSeen=0,newSeen=0,previousWasContent=!1;for(let line of hunk.lines){if(line==="\"){if(!previousWasContent)return!1;previousWasContent=!1;continue}let marker=line[0];if(marker===" ")oldSeen++,newSeen++;else if(marker==="-")oldSeen++;else if(marker==="+")newSeen++;else return!1;previousWasContent=!0}return oldSeen===hunk.oldCount&&newSeen===hunk.newCount}function validateHunkOrdering(hunks){let nextOldAnchor=0,nextNewAnchor=0;for(let hunk of hunks){let oldAnchor=hunk.oldCount===0?hunk.oldStart:hunk.oldStart-1,newAnchor=hunk.newCount===0?hunk.newStart:hunk.newStart-1;if(oldAnchor<nextOldAnchor||newAnchor<nextNewAnchor)return!1;nextOldAnchor=oldAnchor+hunk.oldCount,nextNewAnchor=newAnchor+hunk.newCount}return!0}function parsePatch(patch2){let lines=patch2.replace(/\r\n/g,`
|
|
7942
7942
|
`).split(`
|
|
7943
7943
|
`),files=[],index=0;while(index<lines.length){let line=lines[index];if(!line){index++;continue}let diffLine=parseDiffGitLine(line);if(!diffLine)return null;let{oldPath,newPath}=diffLine;index++;let operation=oldPath===newPath?"modify":"rename",declaredOldPath=oldPath,declaredNewPath=newPath,oldMode,newMode,oldObjectId,newObjectId;while(index<lines.length){let header=lines[index];if(!header){index++;continue}if(parseDiffGitLine(header))break;if(header.startsWith("new file mode ")){operation="add",newMode=header.slice(14),index++;continue}if(header.startsWith("deleted file mode ")){operation="delete",oldMode=header.slice(18),index++;continue}if(header.startsWith("rename from ")){operation="rename";let parsedPath=parseGitPathValue(header.slice(12));if(!parsedPath||parsedPath==="/dev/null")return null;declaredOldPath=parsedPath,index++;continue}if(header.startsWith("rename to ")){let parsedPath=parseGitPathValue(header.slice(10));if(!parsedPath||parsedPath==="/dev/null")return null;declaredNewPath=parsedPath,index++;continue}if(header.startsWith("copy from ")){operation="copy";let parsedPath=parseGitPathValue(header.slice(10));if(!parsedPath||parsedPath==="/dev/null")return null;declaredOldPath=parsedPath,index++;continue}if(header.startsWith("copy to ")){let parsedPath=parseGitPathValue(header.slice(8));if(!parsedPath||parsedPath==="/dev/null")return null;declaredNewPath=parsedPath,index++;continue}if(header.startsWith("old mode ")){operation="mode",oldMode=header.slice(9),index++;continue}if(header.startsWith("new mode ")){newMode=header.slice(9),index++;continue}if(header.startsWith("similarity index ")||header.startsWith("dissimilarity index ")){index++;continue}if(header==="GIT binary patch"||header.startsWith("Binary files "))return null;if(header.startsWith("index ")){let objectMatch=/^index ([a-f0-9]{7,64})\.\.([a-f0-9]{7,64})(?: [0-7]{6})?$/.exec(header);if(!objectMatch)return null;oldObjectId=objectMatch[1],newObjectId=objectMatch[2],index++;continue}let parsedOldHeader=parseGitHeaderPath(header,"--- ",operation==="add"?void 0:"a/"),parsedNewHeader=parseGitHeaderPath(String(lines[index+1]??""),"+++ ",operation==="delete"?void 0:"b/"),expectedOld=operation==="add"?"/dev/null":declaredOldPath,expectedNew=operation==="delete"?"/dev/null":declaredNewPath;if(parsedOldHeader!==expectedOld)return null;if(parsedNewHeader!==expectedNew)return null;index+=2;break}let hunks=[];while(index<lines.length){let hunkHeader=lines[index];if(!hunkHeader){index++;continue}if(parseDiffGitLine(hunkHeader))break;let hunkMatch=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(hunkHeader);if(!hunkMatch)return null;index++;let hunkLines=[];while(index<lines.length){let hunkLine=lines[index];if(hunkLine===""){index++;continue}if(hunkLine.startsWith("@@ -")||parseDiffGitLine(hunkLine))break;if(hunkLine.startsWith(" ")||hunkLine.startsWith("+")||hunkLine.startsWith("-")||hunkLine==="\"){hunkLines.push(hunkLine),index++;continue}return null}if(hunks.push({oldStart:Number.parseInt(hunkMatch[1],10),oldCount:parseCount(hunkMatch[2]),newStart:Number.parseInt(hunkMatch[3],10),newCount:parseCount(hunkMatch[4]),lines:hunkLines}),!validateParsedHunk(hunks[hunks.length-1]))return null}if(hunks.length===0&&operation!=="mode"&&operation!=="rename"&&operation!=="copy")return null;if(!validateHunkOrdering(hunks))return null;files.push({oldRelativePath:operation==="add"?null:declaredOldPath,relativePath:operation==="delete"?declaredOldPath:declaredNewPath,operation,oldMode,newMode,oldObjectId,newObjectId,hunks})}return files.length>0?{files}:null}function splitTextLines(text){let normalized=text.replace(/\r\n/g,`
|