opencode-swarm 7.197.1 → 7.197.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{auto-checkpoint-1dv9a1w5.js → auto-checkpoint-e6t09fc1.js} +4 -4
  4. package/dist/cli/{checkpoint-rkjb6kpr.js → checkpoint-5j752d1a.js} +8 -8
  5. package/dist/cli/{coder-settlement-eavtvg8d.js → coder-settlement-8t3yznbq.js} +3 -3
  6. package/dist/cli/{config-doctor-4ck8e1fq.js → config-doctor-8pdsjzsw.js} +7 -7
  7. package/dist/cli/{core-cyj0vphv.js → core-1dty31az.js} +1 -1
  8. package/dist/cli/{curator-p1r777m5.js → curator-9gwwtyjt.js} +25 -25
  9. package/dist/cli/{curator-drift-15mcxawb.js → curator-drift-7htrxbht.js} +5 -5
  10. package/dist/cli/{curator-llm-factory-k0yebhsk.js → curator-llm-factory-ew2h0zed.js} +25 -25
  11. package/dist/cli/{doctor-knowledge-receipt-phase-id-k204028d.js → doctor-knowledge-receipt-phase-id-y2v12h2y.js} +4 -4
  12. package/dist/cli/{evidence-summary-service-4mx5ge81.js → evidence-summary-service-gthqb26q.js} +9 -9
  13. package/dist/cli/{gate-evidence-pa8qadxh.js → gate-evidence-xv1228n3.js} +2 -2
  14. package/dist/cli/{guardrail-explain-pba5em4h.js → guardrail-explain-h41yf31c.js} +26 -26
  15. package/dist/cli/{guardrail-log-24fbykv3.js → guardrail-log-6f55sa60.js} +3 -3
  16. package/dist/cli/{guardrail-reset-rfnr2vnn.js → guardrail-reset-j9bk61er.js} +25 -25
  17. package/dist/cli/{hive-promoter-0ht8jafr.js → hive-promoter-6y24tdbf.js} +25 -25
  18. package/dist/cli/{index-xtb61w73.js → index-04xgdmps.js} +1 -1
  19. package/dist/cli/{index-57g7yqx9.js → index-1pek46cc.js} +84 -64
  20. package/dist/cli/{index-vanjqbhp.js → index-2fwsd357.js} +5 -5
  21. package/dist/cli/{index-f0d3z2ha.js → index-2jd8sark.js} +2 -2
  22. package/dist/cli/{index-mwh6srje.js → index-4b64v1kx.js} +1 -1
  23. package/dist/cli/{index-hyxw4j9t.js → index-6dz5venm.js} +1 -1
  24. package/dist/cli/{index-6g81mmmy.js → index-7m5cf6nb.js} +4 -4
  25. package/dist/cli/{index-efen9p4c.js → index-841jrejq.js} +1 -1
  26. package/dist/cli/{index-qqe9tt5y.js → index-9exby7at.js} +1 -1
  27. package/dist/cli/{index-9vwsvgzp.js → index-a4jwt70q.js} +1 -1
  28. package/dist/cli/{index-pywrvjxj.js → index-ax7n55cd.js} +3 -3
  29. package/dist/cli/{index-0sw6gjtn.js → index-aynf8fgp.js} +3 -3
  30. package/dist/cli/{index-qae4572e.js → index-c602bgyp.js} +1 -1
  31. package/dist/cli/{index-rqbhn0mh.js → index-f87r78zb.js} +2 -2
  32. package/dist/cli/{index-3h4tajza.js → index-fws15qp0.js} +2 -2
  33. package/dist/cli/{index-syrktqz9.js → index-j8bgrxc8.js} +2 -2
  34. package/dist/cli/{index-pek9gmwm.js → index-mpc3z3ky.js} +3 -3
  35. package/dist/cli/{index-z5rkkhng.js → index-mqk09xcm.js} +6 -6
  36. package/dist/cli/{index-t4nxee8x.js → index-p0ha6zyg.js} +1 -1
  37. package/dist/cli/{index-r9ab1sat.js → index-pd98xk00.js} +27 -27
  38. package/dist/cli/{index-fmgkemn9.js → index-pwgb4ysh.js} +1 -1
  39. package/dist/cli/{index-h69nppa3.js → index-rpa47vzb.js} +1 -1
  40. package/dist/cli/{index-d483e4gz.js → index-s67cbrd1.js} +3 -3
  41. package/dist/cli/{index-56n6nb7p.js → index-svmhj9x2.js} +25 -25
  42. package/dist/cli/{index-d0m3snqt.js → index-t7egd710.js} +1 -1
  43. package/dist/cli/{index-528gk6k1.js → index-tf3y0x41.js} +1 -1
  44. package/dist/cli/{index-tstk9xx7.js → index-yed14yth.js} +1 -1
  45. package/dist/cli/{index-a9bs0c71.js → index-yg2qwadj.js} +1 -1
  46. package/dist/cli/{index-9rqvm5sk.js → index-z250fgd9.js} +2 -2
  47. package/dist/cli/{index-kah11mjw.js → index-z75fz6x3.js} +3 -3
  48. package/dist/cli/index.js +26 -26
  49. package/dist/cli/{knowledge-escalator-89crpby4.js → knowledge-escalator-xvkfez9d.js} +7 -7
  50. package/dist/cli/{knowledge-events-eyratqdp.js → knowledge-events-t4enxfp7.js} +5 -5
  51. package/dist/cli/{knowledge-store-kkwds05z.js → knowledge-store-tdqx1z7e.js} +1 -1
  52. package/dist/cli/{knowledge-validator-fww6p37v.js → knowledge-validator-3n52kff9.js} +2 -2
  53. package/dist/cli/{mcp-8t3m998m.js → mcp-yqfahteb.js} +1 -1
  54. package/dist/cli/{model-preflight-98g183my.js → model-preflight-s3s7t38g.js} +25 -25
  55. package/dist/cli/{pending-delegations-qj5e0hh2.js → pending-delegations-j89ak26j.js} +2 -2
  56. package/dist/cli/{pr-subscriptions-edwd3syw.js → pr-subscriptions-r5q1035f.js} +1 -1
  57. package/dist/cli/{pr-workflow-gate-t8veygyh.js → pr-workflow-gate-dahpc06k.js} +25 -25
  58. package/dist/cli/{scan-cursor-0ffhpz79.js → scan-cursor-yjk3czah.js} +2 -2
  59. package/dist/cli/{schema-zytt0t7a.js → schema-1bs31fpf.js} +1 -1
  60. package/dist/cli/{scope-persistence-p8a9a2xb.js → scope-persistence-0mpbc1ht.js} +5 -5
  61. package/dist/cli/{server-q4b9s64v.js → server-8swemw8w.js} +25 -25
  62. package/dist/cli/{skill-generator-wt7d640t.js → skill-generator-mx125j7w.js} +8 -8
  63. package/dist/cli/{snapshot-coordination-init-ywxyf130.js → snapshot-coordination-init-sayvd15t.js} +25 -25
  64. package/dist/cli/{speckit-checkoff-y8na83hj.js → speckit-checkoff-76j7h7qt.js} +3 -3
  65. package/dist/cli/{worktree-collision-ownership-kssmhrpk.js → worktree-collision-ownership-8f8c9bcr.js} +2 -2
  66. package/dist/cli/{worktree-isolation-w6np680v.js → worktree-isolation-kgfk5aj8.js} +25 -25
  67. package/dist/commands/close/constants.d.ts +17 -1
  68. package/dist/commands/close/fs-helpers.d.ts +6 -1
  69. package/dist/index.js +3 -3
  70. 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.197.1",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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; 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.197.3",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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; 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
 
@@ -1383,8 +1383,8 @@ ${step.stderr}`);if(fileRefs.length>0){lines.push(""),lines.push("**Failure loca
1383
1383
  source TEXT NOT NULL,
1384
1384
  target TEXT NOT NULL,
1385
1385
  edge_json TEXT NOT NULL
1386
- )`},{version:5,name:"create_edges_source_index",sql:"CREATE INDEX idx_edges_source ON edges(source)"},{version:6,name:"create_edges_target_index",sql:"CREATE INDEX idx_edges_target ON edges(target)"}],LATEST_SCHEMA_VERSION=MIGRATIONS2[MIGRATIONS2.length-1]?.version??0,_handles=new Map;_internals117={isIndexedStorageAvailable,removeRepoMemoryFiles,unlinkSync:unlinkSync21,cacheHandle,maxOpenHandles:MAX_OPEN_HANDLES,openHandleCount:()=>_handles.size,hasOpenHandle:(workspace)=>{try{return _handles.has(getRepoMemoryPath(workspace))}catch{return!1}}}});var NO_RECEIPT_PHASE_CLOSE_SCOPE_DETAIL="no exact receipt lifecycle scope exists for phase closure",CLOSE_SKILL_REVIEW_TIMEOUT_MS=120000,CLOSE_REFLECTION_TIMEOUT_MS=90000,ARCHIVE_ARTIFACTS,ACTIVE_STATE_TO_CLEAN,TERMINAL_STATE_FILES,KNOWLEDGE_FAMILY_ARTIFACTS,REQUIRED_ARTIFACTS,ACTIVE_STATE_DIRS_TO_CLEAN,ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS;var init_constants2=__esm(()=>{init_indexed_storage();ARCHIVE_ARTIFACTS=["plan.json","plan.md","plan-ledger.jsonl","context.md","events.jsonl","events-authority-index.json","handoff.md","handoff-prompt.md","handoff-consumed.md","escalation-report.md","close-lessons.md","knowledge.jsonl","knowledge-rejected.jsonl","knowledge-receipts-v2.jsonl","knowledge-receipts-v2.snapshot.json","knowledge-receipts-v2-archive.jsonl","run-memory.jsonl","repo-graph.json","repo-graph.fingerprint.json","doc-manifest.json","dark-matter.md","telemetry.jsonl","telemetry.jsonl.1","swarm.db","epic-state.json","turbo-state.json",REPO_MEMORY_FILENAME,"close-summary.md","session-reflection.md","spec.md","spec-staleness.json","spec-snapshot.md","background-delegations.jsonl","background-delegations.checkpoint.json","background-delegations.manifest.json","background-delegations-health.json","context-telemetry.jsonl","workspace-snapshot.digest"],ACTIVE_STATE_TO_CLEAN=["plan.json","plan.md","plan-ledger.jsonl","events.jsonl","events-authority-index.json","handoff.md","handoff-prompt.md","handoff-consumed.md","escalation-report.md","knowledge-rejected.jsonl","run-memory.jsonl","repo-graph.json","repo-graph.fingerprint.json","doc-manifest.json","dark-matter.md","telemetry.jsonl","telemetry.jsonl.1","session-reflection.md","spec.md","spec-staleness.json","spec-snapshot.md","swarm.db",REPO_MEMORY_FILENAME,"epic-state.json","turbo-state.json","workspace-snapshot.digest"],TERMINAL_STATE_FILES=["plan.json","plan-ledger.jsonl","spec-staleness.json","spec-snapshot.md"],KNOWLEDGE_FAMILY_ARTIFACTS=new Set(["knowledge.jsonl","knowledge-rejected.jsonl"]),REQUIRED_ARTIFACTS=new Set(["plan.json","plan-ledger.jsonl"]),ACTIVE_STATE_DIRS_TO_CLEAN=["coder-settlements","council","evidence","session","scopes","spec-archive","task-repairs","task-terminals","runs","epic"],ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS=[25,50,100,200]});import*as fsSync12 from"node:fs";import{promises as fs80}from"node:fs";var closeReceiptLifecycleInternals,_internals118;var init_internals=__esm(()=>{init_audit_log();init_shell_audit_store();init_constants2();closeReceiptLifecycleInternals={recordPhaseCloseIntent:void 0,reconcilePhaseClose:void 0},_internals118={closeSnapshotCoordinationInitialization:void 0,closeRepoMemory:void 0,unlinkActiveStateFileWithRetry:void 0,unlink:fs80.unlink,unlinkSidecarSync:fsSync12.unlinkSync,sleep:void 0,collectGarbageBestEffort:void 0,ACTIVE_STATE_DIRS_TO_CLEAN,countSessionKnowledgeEntries:void 0,CLOSE_SKILL_REVIEW_TIMEOUT_MS,CLOSE_REFLECTION_TIMEOUT_MS,detectFullAuto:void 0,guaranteeAllPlansComplete:void 0,getGitRepositoryStatus:void 0,resetToMainAfterMerge:void 0,resetToRemoteBranch:void 0,copyDirRecursive:void 0,loadPluginConfigWithMeta:void 0,curateAndStoreSwarm:void 0,checkHivePromotions:void 0,runCuratorPostMortem:void 0,createCuratorLLMDelegate:void 0,resetSwarmStatePreservingSingletons:void 0,runFinalizeStage:void 0,runFinalizeRewardSweep:void 0,acquireFinalizeLock:void 0,runArchiveStage:void 0,archiveCloseSummary:void 0,runArchiveEvidenceRetention:void 0,runCleanStage:void 0,runAlignStage:void 0,runFinalizeDryRun:void 0,archiveEvidence:void 0,closePlanTerminalState:void 0,endAgentSession:void 0,flushAndDrainTelemetry:void 0,finalizeContextTelemetry:void 0,finalizeCoreEvents:void 0,finalizeShellAudit:(directory)=>{finalizeShellAuditForClose(directory,{lineTransform:redactDecisionLineForArchive})}}});function renderRecheckRefusal(reason,newDirtyPaths){let listed=newDirtyPaths.slice(0,10),overflow=newDirtyPaths.length-listed.length,swarmHint=newDirtyPaths.some((p)=>p.startsWith(".swarm/"))?"One or more changed paths are under .swarm/ — this project tracks swarm runtime state in git. Consider `git rm -r --cached .swarm/` and re-adding `.swarm/` to .git/info/exclude; close never confirms runtime state as destructive scope.":void 0;return[`\uD83D\uDED1 Git alignment aborted (fail-closed): ${reason} — this destructive scope was never confirmed${listed[0]?` (first: ${listed[0]})`:""}.`,...listed.map((p)=>` - ${p}`),...overflow>0?[` … and ${overflow} more`]:[],...swarmHint?[swarmHint]:[],"Nothing was reset or checked out; the session is finalized (finalize/archive/clean completed). Complete git alignment manually if still wanted."].join(`
1387
- `)}async function guardResetWithRecheck(real,cwd,options){let recheck=recheckBeforeDestructive(cwd,options?.expectedDirtyPaths??[]);if(recheck.ok)return real(cwd,{pruneBranches:options?.pruneBranches});return log(`[close-align] re-check refused destructive reset: ${recheck.reason} (${recheck.newDirtyPaths.length} newly-dirty path(s))`),{success:!1,targetBranch:"",previousBranch:"",message:renderRecheckRefusal(recheck.reason,recheck.newDirtyPaths),branchDeleted:!1,changesDiscarded:!1,warnings:[],recheckRefused:!0}}async function runAlignStage(ctx){let pruneBranches=ctx.args.includes("--prune-branches"),gitAlignResult="",prunedBranches=[],gitStatus=_internals118.getGitRepositoryStatus(ctx.directory);if(gitStatus.isRepo){let aggressiveResult=await _internals118.resetToMainAfterMerge(ctx.directory,{pruneBranches,expectedDirtyPaths:ctx.purgeGateDirtyPaths??[]});if(aggressiveResult.recheckRefused)return gitAlignResult=aggressiveResult.message,ctx.warnings.push(aggressiveResult.message),{gitAlignResult,prunedBranches};if(aggressiveResult.success){gitAlignResult=aggressiveResult.message;for(let w of aggressiveResult.warnings)ctx.warnings.push(w);if(aggressiveResult.changesDiscarded)ctx.warnings.push("Uncommitted changes were discarded during git alignment")}else{let alignResult=await _internals118.resetToRemoteBranch(ctx.directory,{pruneBranches});if(gitAlignResult=alignResult.message,prunedBranches.push(...alignResult.prunedBranches),!alignResult.success)ctx.warnings.push(`Git alignment: ${alignResult.message}`);if(alignResult.alreadyAligned)gitAlignResult=`Already aligned with ${alignResult.targetBranch}`;for(let w of alignResult.warnings)ctx.warnings.push(w)}}else if(gitStatus.reason==="git_unavailable")gitAlignResult=`Git executable unavailable — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else if(gitStatus.reason==="git_error")gitAlignResult=`Git repository check failed — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else gitAlignResult="Not a git repository — skipped git alignment";return{gitAlignResult,prunedBranches}}var init_align_stage=__esm(()=>{init_logger();init_destructive_purge();init_internals()});import*as fsSync13 from"node:fs";import path130 from"node:path";function resolveDatabaseCtor(){return _internals119.DatabaseCtor??loadDatabaseCtor()}function safeRemoveTemp(tempPath){try{_internals119.rmSync(tempPath,{force:!0,recursive:!0,maxRetries:3,retryDelay:100})}catch{}}function buildVacuumIntoSql(destPath){return`VACUUM INTO '${destPath.replace(/\\/g,"/").replace(/'/g,"''")}'`}function rowString(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];return v===null||v===void 0?"":String(v)}return""}function rowNumber(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];if(typeof v==="number"&&Number.isFinite(v))return v;if(typeof v==="bigint")return Number(v);if(typeof v==="string"){let n=Number(v);if(Number.isFinite(n))return n}}return null}function captureRowCounts(db){let tableExists=(name)=>{let row=db.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name);return rowNumber(row,"c")!==null&&(rowNumber(row,"c")??0)>0},schemaMigrationsMax=null;if(tableExists("schema_migrations")){let row=db.query("SELECT MAX(version) AS m FROM schema_migrations").get();schemaMigrationsMax=rowNumber(row,"m")}let projectConstraints=tableExists("project_constraints")?rowNumber(db.query("SELECT COUNT(*) AS c FROM project_constraints").get(),"c")??0:0,qaGateProfile=tableExists("qa_gate_profile")?rowNumber(db.query("SELECT COUNT(*) AS c FROM qa_gate_profile").get(),"c")??0:0;return{schema_migrations_max_version:schemaMigrationsMax,project_constraints:projectConstraints,qa_gate_profile:qaGateProfile}}async function archiveSqliteSnapshot(opts){let maxSourceBytes=opts.maxSourceBytes??DEFAULT_MAX_SOURCE_BYTES2,busyTimeoutMs=opts.busyTimeoutMs??DEFAULT_BUSY_TIMEOUT_MS;if(!_internals119.existsSync(opts.sourcePath))return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"};let sourceBytes=0;for(let suffix of["","-wal","-shm"]){let sidecar=opts.sourcePath+suffix;if(!_internals119.existsSync(sidecar))continue;try{sourceBytes+=_internals119.statSync(sidecar).size}catch(err){if(suffix==="")return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`source stat failed: ${err instanceof Error?err.message:String(err)}`}}}if(sourceBytes>maxSourceBytes)return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"retained",method:"none",reason_code:"source_over_budget",detail:`source bytes ${sourceBytes} > budget ${maxSourceBytes}`};let destFinal=path130.join(opts.destDir,opts.destName),destTemp=path130.join(opts.destDir,`.${opts.destName}.tmp.${_internals119.now()}.${_internals119.randomSuffix()}`),Db;try{Db=resolveDatabaseCtor()}catch(err){return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`driver unavailable: ${err instanceof Error?err.message:String(err)}`}}let snapshotDb=null;try{snapshotDb=new Db(opts.sourcePath);try{snapshotDb.run(`PRAGMA busy_timeout = ${busyTimeoutMs};`),snapshotDb.run(buildVacuumIntoSql(destTemp))}finally{snapshotDb.close(),snapshotDb=null}}catch(err){if(snapshotDb)try{snapshotDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:err instanceof Error?err.message:String(err)}}let rowCounts,verifyDb=null;try{verifyDb=new Db(destTemp),verifyDb.run("PRAGMA query_only = ON;");let integrityRow=verifyDb.query("PRAGMA integrity_check").get(),integrity=rowString(integrityRow,"integrity_check");if(integrity!=="ok")return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:`integrity_check: ${integrity||"(empty)"}`};if((rowNumber(verifyDb.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='schema_migrations'").get(),"c")??0)<1)return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"schema_mismatch",detail:"schema_migrations table absent"};rowCounts=captureRowCounts(verifyDb),verifyDb.close(),verifyDb=null}catch(err){if(verifyDb)try{verifyDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:err instanceof Error?err.message:String(err)}}try{_internals119.renameSync(destTemp,destFinal)}catch(err){return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"publish_failed",detail:err instanceof Error?err.message:String(err),rowCounts}}return{requiredness:"required",attempt:"succeeded",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"ok",destPath:destFinal,rowCounts}}var DEFAULT_MAX_SOURCE_BYTES2=2147483648,DEFAULT_BUSY_TIMEOUT_MS=5000,_internals119;var init_archive_sqlite=__esm(()=>{init_sqlite_loader();_internals119={existsSync:fsSync13.existsSync,statSync:fsSync13.statSync,renameSync:fsSync13.renameSync,rmSync:fsSync13.rmSync,now:()=>Date.now(),randomSuffix:()=>Math.random().toString(36).slice(2,8),DatabaseCtor:null}});import{promises as fs81}from"node:fs";import path131 from"node:path";async function copyDirRecursiveWithFailures(src,dest){let count2=0,failures=[],entries=await fs81.readdir(src);await fs81.mkdir(dest,{recursive:!0});for(let entry of entries){let srcEntry=path131.join(src,entry),destEntry=path131.join(dest,entry);try{if((await fs81.stat(srcEntry)).isDirectory()){let subResult=await copyDirRecursiveWithFailures(srcEntry,destEntry);count2+=subResult.copied,failures.push(...subResult.failures)}else try{await fs81.copyFile(srcEntry,destEntry),count2++}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}return{copied:count2,failures}}async function copyDirRecursive(src,dest){return(await copyDirRecursiveWithFailures(src,dest)).copied}async function unlinkActiveStateFileWithRetry(filePath){for(let attempt=0;;attempt+=1)try{await _internals118.unlink(filePath);return}catch(error93){let code=error93?.code,delay2=ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS[attempt];if(code!=="EBUSY"&&code!=="EPERM"||delay2===void 0)throw error93;if(attempt===0)_internals118.collectGarbageBestEffort();await _internals118.sleep(delay2)}}var init_fs_helpers=__esm(()=>{init_constants2();init_internals()});import*as fsSync14 from"node:fs";import{promises as fs82}from"node:fs";import path132 from"node:path";function emitCloseArchiveResult(ctx,cleanResult){let cleaned=new Set(cleanResult.cleanedFiles),failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,sqliteSnapshots=ctx.archiveResults.filter((r)=>r.method==="vacuum_into"&&r.attempt==="succeeded"),archiveEmpty=sqliteSnapshots.length>0&&sqliteSnapshots.every((r)=>(r.row_counts?.project_constraints??0)===0&&(r.row_counts?.qa_gate_profile??0)===0),archiveValid=!ctx.archiveStageFailed&&failedCount===0;try{telemetry.closeArchiveResult({archive_valid:archiveValid,archive_empty:archiveEmpty,file_count:ctx.archivedFileCount,bundle:`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`,artifacts:ctx.archiveResults.map((r)=>{let removed=cleaned.has(r.artifact);return{artifact:r.artifact,requiredness:r.requiredness,attempt:r.attempt,validation:r.validation,source_disposition:removed?"removed":r.source_disposition,method:r.method,reason_code:r.reason_code,...r.row_counts?{row_counts:r.row_counts}:{}}})})}catch(telemetryErr){log("[close-command] close_archive_result telemetry emit failed:",telemetryErr)}observeCloseArchive({directory:ctx.directory,archiveValid,archiveEmpty,activityPredictsContent:archiveActivityPredictsContent(ctx.directory)})}function archiveActivityPredictsContent(directory){try{for(let name of["knowledge-events.jsonl","telemetry.jsonl","evidence"]){let target=path132.join(directory,".swarm",name),stat13=fsSync14.statSync(target);if(target.endsWith("evidence")){if(fsSync14.readdirSync(target).length>0)return!0}else if(stat13.size>0)return!0}return!1}catch{return!1}}async function runArchiveStage(ctx){ctx.timestamp=new Date().toISOString().replace(/[:.]/g,"-"),ctx.archiveSuffix=Math.random().toString(36).slice(2,8),ctx.archiveDir=path132.join(ctx.swarmDir,"archive",`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`);try{await fs82.mkdir(ctx.archiveDir,{recursive:!0});try{await _internals118.flushAndDrainTelemetry()}catch(flushErr){let msg=flushErr instanceof Error?flushErr.message:String(flushErr);ctx.warnings.push(`Telemetry flush before archive failed: ${msg}`)}try{_internals118.finalizeContextTelemetry(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Context-map telemetry finalize before archive failed: ${msg}`)}try{_internals118.finalizeCoreEvents(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Core events finalize before archive failed: ${msg}`)}try{_internals118.finalizeShellAudit(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Shell audit finalize before archive failed: ${msg}`)}let linkedKnowledgeShared=isLinked(ctx.directory);if(linkedKnowledgeShared)ctx.warnings.push("Worktree is linked: shared knowledge (knowledge.jsonl, knowledge-rejected.jsonl) lives in the link store and is not archived or cleaned by /swarm close. Manage it via the link.");for(let artifact of ARCHIVE_ARTIFACTS){if(linkedKnowledgeShared&&KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact))continue;let srcPath=path132.join(ctx.swarmDir,artifact),destPath=path132.join(ctx.archiveDir,artifact),requiredness=REQUIRED_ARTIFACTS.has(artifact)?"required":"optional";if(artifact==="swarm.db"||artifact===REPO_MEMORY_FILENAME){let r=await archiveSqliteSnapshot({sourcePath:srcPath,destDir:ctx.archiveDir,destName:artifact}),result={artifact,requiredness,attempt:r.attempt,validation:r.validation,source_disposition:r.attempt==="succeeded"?"retained":r.source_disposition,method:r.method,reason_code:r.reason_code,detail:r.detail,row_counts:r.rowCounts};if(ctx.archiveResults.push(result),r.attempt==="succeeded"&&r.validation==="passed"){if(ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact)}else if(!(r.attempt==="not_attempted"&&r.source_disposition==="absent"))ctx.archiveFailureReasons.set(artifact,`${r.reason_code}: ${r.detail??""}`),ctx.warnings.push(`Failed to archive ${artifact} [${r.reason_code}]: ${r.detail??""}. Source preserved.`)}else try{if(await fs82.copyFile(srcPath,destPath),ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact);ctx.archiveResults.push({artifact,requiredness,attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno==="ENOENT")ctx.archiveResults.push({artifact,requiredness,attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"});else{let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness,attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}}}let dynamicArchiveArtifacts=(await fs82.readdir(ctx.swarmDir).catch(()=>[])).filter((name)=>/^post-mortem-[^/\\]+\.md$/.test(name)||/^drift-report-phase-\d+\.json$/.test(name));for(let artifact of dynamicArchiveArtifacts){let srcPath=path132.join(ctx.swarmDir,artifact),destPath=path132.join(ctx.archiveDir,artifact);try{await fs82.copyFile(srcPath,destPath),ctx.archivedFileCount++,ctx.archivedActiveStateFiles.add(artifact),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno!=="ENOENT"){let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}else ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"})}}for(let dirName of ACTIVE_STATE_DIRS_TO_CLEAN){let srcDir=path132.join(ctx.swarmDir,dirName),destDir=path132.join(ctx.archiveDir,dirName);try{let result=await copyDirRecursiveWithFailures(srcDir,destDir);if(ctx.archivedFileCount+=result.copied,result.failures.length===0)ctx.archivedActiveStateDirs.add(dirName);else{ctx.warnings.push(`Directory ${dirName} not fully archived (${result.failures.length} failure(s)). Source preserved.`);for(let failure of result.failures)ctx.warnings.push(` - ${failure}`)}}catch(err){let code=err.code;if(code!=="ENOENT")ctx.warnings.push(`Failed to archive directory ${dirName} [${code??"unknown"}]: ${err.message}. Source preserved.`)}}let succeededCount=ctx.archiveResults.filter((r)=>r.attempt==="succeeded").length,failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,absentCount=ctx.archiveResults.filter((r)=>r.source_disposition==="absent").length,bundleName=`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`;ctx.archiveResult=failedCount>0?`Archive partial: ${succeededCount} succeeded, ${failedCount} failed, ${absentCount} absent (see warnings). Bundle: .swarm/archive/${bundleName}/`:`Archived ${ctx.archivedFileCount} artifact(s) to .swarm/archive/${bundleName}/`}catch(archiveError){ctx.warnings.push(`Archive creation failed: ${archiveError instanceof Error?archiveError.message:String(archiveError)}`),ctx.archiveResult="Archive creation failed (see warnings)",ctx.archiveStageFailed=!0}await runArchiveEvidenceRetention({directory:ctx.directory,swarmDir:ctx.swarmDir,config:ctx.config,warnings:ctx.warnings})}async function runArchiveEvidenceRetention(ctx){let maxAgeDays=30,maxBundles=10,cacheMaxBytes,cacheMaxRecords;try{let{config:evidenceLoadedConfig}=_internals118.loadPluginConfigWithMeta(ctx.directory),evidenceCfg=evidenceLoadedConfig.evidence??{};if(typeof evidenceCfg.max_age_days==="number")maxAgeDays=evidenceCfg.max_age_days;if(typeof evidenceCfg.max_bundles==="number")maxBundles=evidenceCfg.max_bundles;if(typeof evidenceCfg.cache_max_bytes==="number")cacheMaxBytes=evidenceCfg.cache_max_bytes;if(typeof evidenceCfg.cache_max_records==="number")cacheMaxRecords=evidenceCfg.cache_max_records}catch{}try{await _internals118.archiveEvidence(ctx.directory,maxAgeDays,maxBundles,{report:!0,cacheMaxBytes,cacheMaxRecords})}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Evidence retention archive failed: ${msg}`),log("[close-command] archiveEvidence error:",error93)}}var init_archive_stage=__esm(()=>{init_learning_health();init_knowledge_link();init_telemetry();init_indexed_storage();init_logger();init_archive_sqlite();init_constants2();init_fs_helpers();init_internals()});import{createHash as createHash63}from"node:crypto";import*as fs83 from"node:fs";import*as path133 from"node:path";function collectCandidates(swarmRoot){let items=[],scannedEntries=0,truncated=!1,walk=(relDir,depth)=>{if(truncated)return;let absDir=relDir===""?swarmRoot:path133.join(swarmRoot,...relDir.split("/")),dirents;try{dirents=fs83.readdirSync(absDir,{withFileTypes:!0})}catch{return}for(let dirent of dirents){if(++scannedEntries>MAX_RESIDUE_SCAN_ENTRIES){truncated=!0;return}if(relDir===""&&RESIDUE_SKIP_DIRS.includes(dirent.name))continue;let rel=relDir===""?dirent.name:`${relDir}/${dirent.name}`;if(dirent.isDirectory()&&!dirent.isSymbolicLink()){if(depth+1<=RESIDUE_SCAN_DEPTH)walk(rel,depth+1);continue}let grammar=matchTempGrammar(dirent.name);if(!grammar)continue;let bytes=0,mtimeMs=0;if(!dirent.isSymbolicLink())try{let st=fs83.lstatSync(path133.join(swarmRoot,...rel.split("/")));if(!st.isFile())continue;bytes=st.size,mtimeMs=st.mtimeMs}catch{continue}items.push({relPath:rel,grammar,isSymlink:dirent.isSymbolicLink(),bytes,mtimeMs})}};return walk("",0),{items,scannedEntries,truncated}}async function inventorySwarmResidue(directory){let swarmRoot=path133.normalize(path133.resolve(directory,".swarm"));if(!fs83.existsSync(swarmRoot))return{swarmRoot,scannedEntries:0,truncated:!1,entries:[],summary:{matched:0,eligible:0,ambiguous:0,totalBytes:0,oldestAgeMs:0},gitState:"unknown"};if(fs83.lstatSync(swarmRoot).isSymbolicLink())throw Error(`Refusing to scan a symlinked .swarm root: ${swarmRoot}`);let projectRoot=path133.dirname(swarmRoot),{tracked}=_internals120.queryTracked(projectRoot,swarmRoot),lockTargets=_internals120.activeLockTargets(directory),{items,scannedEntries,truncated}=collectCandidates(swarmRoot),now2=_internals120.now(),entries=[];for(let item of items){let ageMs=Math.max(0,now2-item.mtimeMs);if(item.grammar.token==="constant"&&item.grammar.id!=="dot-tmp-prefix-legacy"){if(ageMs<RESIDUE_STALE_AGE_MS)continue}let abs=path133.normalize(path133.join(swarmRoot,...item.relPath.split("/"))),reasons=[];if(!item.grammar.quarantineEligible)reasons.push("constant-name-grammar");if(ageMs<RESIDUE_STALE_AGE_MS)reasons.push("recent");let trackedState;if(tracked===void 0){if(trackedState="unknown",item.grammar.quarantineEligible)reasons.push("tracked-state-unknown")}else if(trackedState=tracked.has(abs)?"tracked":"untracked",trackedState==="tracked")reasons.push("git-tracked");if(item.isSymlink)reasons.push("symlink");let lockHeld=lockTargets.has(abs)||(item.grammar.parsesTarget?lockTargets.has(path133.normalize(path133.join(path133.dirname(abs),parseTargetBasename(item.relPath.split("/").pop()??"")??""))):!1);if(lockHeld)reasons.push("active-lock");if(item.bytes>RESIDUE_HASH_MAX_BYTES)reasons.push("oversize");if(item.grammar.quarantineEligible&&item.grammar.parsesTarget){let targetBasename=parseTargetBasename(item.relPath.split("/").pop()??"");if(targetBasename){let targetAbs=path133.join(path133.dirname(abs),targetBasename),targetOk=!1;try{targetOk=fs83.lstatSync(targetAbs).isFile()}catch{targetOk=!1}if(!targetOk)reasons.push("target-absent")}}entries.push({relPath:item.relPath,grammarId:item.grammar.id,grammarEra:item.grammar.era,bytes:item.bytes,mtimeMs:item.mtimeMs,ageMs,isSymlink:item.isSymlink,tracked:trackedState,lockHeld,proposedAction:item.grammar.quarantineEligible&&reasons.length===0?"quarantine":"report_only",reasons})}entries.sort((a,b)=>b.ageMs-a.ageMs);let eligible=entries.filter((e)=>e.proposedAction==="quarantine");return{swarmRoot,scannedEntries,truncated,entries,summary:{matched:entries.length,eligible:eligible.length,ambiguous:entries.length-eligible.length,totalBytes:entries.reduce((sum,e)=>sum+e.bytes,0),oldestAgeMs:entries[0]?.ageMs??0},gitState:tracked===void 0?"unknown":"ok"}}function validateRelPath(rel,what){if(!rel||path133.isAbsolute(rel)||rel.split("/").some((s)=>s===".."||s===""||/[\0-\x1f]/.test(s)))throw Error(`unsafe ${what} in quarantine manifest: ${JSON.stringify(rel)}`);return rel}function sha256Bounded(absPath){try{return _internals120.sha256File(absPath)}catch{return}}async function quarantineSwarmResidue(directory,options){let inventory=await inventorySwarmResidue(directory),eligible=inventory.entries.filter((e)=>e.proposedAction==="quarantine"),preserved=inventory.entries.filter((e)=>e.proposedAction==="report_only").map((e)=>({relPath:e.relPath,status:"preserved",reasons:e.reasons}));if(options?.dryRun||eligible.length===0)return{inventory,quarantined:0,preserved};let swarmRoot=inventory.swarmRoot,batchId=`${new Date().toISOString().replace(/[:.]/g,"-")}-${Math.random().toString(36).slice(2,10)}`,batchAbs=path133.join(swarmRoot,"quarantine",batchId);fs83.mkdirSync(batchAbs,{recursive:!0});let manifest={schema_version:1,batch_id:batchId,created_at:new Date().toISOString(),trigger:options?.trigger??"manual",entries:[]},moved=[];for(let entry of eligible){let abs=path133.join(swarmRoot,...entry.relPath.split("/"));try{let st=fs83.lstatSync(abs);if(!st.isFile()||st.size!==entry.bytes||st.mtimeMs!==entry.mtimeMs){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["changed-since-scan"]});continue}}catch{preserved.push({relPath:entry.relPath,status:"preserved",reasons:["vanished"]});continue}let sha=sha256Bounded(abs);if(!sha){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["hash-failed"]});continue}let storedAbs=path133.join(batchAbs,...entry.relPath.split("/"));try{fs83.mkdirSync(path133.dirname(storedAbs),{recursive:!0}),_internals120.renameResidueEntry(abs,storedAbs)}catch(moveErr){let code=moveErr?.code??"unknown";preserved.push({relPath:entry.relPath,status:"preserved",reasons:[`move-failed:${code}`]});continue}manifest.entries.push({original_rel_path:entry.relPath,stored_rel_path:path133.posix.join("quarantine",batchId,entry.relPath),sha256:sha,bytes:entry.bytes,mtime_ms:entry.mtimeMs,grammar_id:entry.grammarId,reason:"stale-atomic-write-temp"}),moved.push({relPath:entry.relPath,status:"quarantined",reasons:[]})}let batchRelDir;if(manifest.entries.length>0)atomicWriteSwarmFileSync(path133.join(batchAbs,"manifest.json"),`${JSON.stringify(manifest,null,2)}
1386
+ )`},{version:5,name:"create_edges_source_index",sql:"CREATE INDEX idx_edges_source ON edges(source)"},{version:6,name:"create_edges_target_index",sql:"CREATE INDEX idx_edges_target ON edges(target)"}],LATEST_SCHEMA_VERSION=MIGRATIONS2[MIGRATIONS2.length-1]?.version??0,_handles=new Map;_internals117={isIndexedStorageAvailable,removeRepoMemoryFiles,unlinkSync:unlinkSync21,cacheHandle,maxOpenHandles:MAX_OPEN_HANDLES,openHandleCount:()=>_handles.size,hasOpenHandle:(workspace)=>{try{return _handles.has(getRepoMemoryPath(workspace))}catch{return!1}}}});var NO_RECEIPT_PHASE_CLOSE_SCOPE_DETAIL="no exact receipt lifecycle scope exists for phase closure",CLOSE_SKILL_REVIEW_TIMEOUT_MS=120000,CLOSE_REFLECTION_TIMEOUT_MS=90000,ARCHIVE_ARTIFACTS,ACTIVE_STATE_TO_CLEAN,TERMINAL_STATE_FILES,KNOWLEDGE_FAMILY_ARTIFACTS,REQUIRED_ARTIFACTS,ACTIVE_STATE_DIRS_TO_CLEAN,ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS;var init_constants2=__esm(()=>{init_indexed_storage();ARCHIVE_ARTIFACTS=["plan.json","plan.md","plan-ledger.jsonl","context.md","events.jsonl","events-authority-index.json","handoff.md","handoff-prompt.md","handoff-consumed.md","escalation-report.md","close-lessons.md","knowledge.jsonl","knowledge-rejected.jsonl","knowledge-receipts-v2.jsonl","knowledge-receipts-v2.snapshot.json","knowledge-receipts-v2-archive.jsonl","run-memory.jsonl","repo-graph.json","repo-graph.fingerprint.json","doc-manifest.json","dark-matter.md","telemetry.jsonl","telemetry.jsonl.1","swarm.db","epic-state.json","turbo-state.json",REPO_MEMORY_FILENAME,"close-summary.md","session-reflection.md","spec.md","spec-staleness.json","spec-snapshot.md","background-delegations.jsonl","background-delegations.checkpoint.json","background-delegations.manifest.json","background-delegations-health.json","context-telemetry.jsonl","workspace-snapshot.digest"],ACTIVE_STATE_TO_CLEAN=["plan.json","plan.md","plan-ledger.jsonl","events.jsonl","events-authority-index.json","handoff.md","handoff-prompt.md","handoff-consumed.md","escalation-report.md","knowledge-rejected.jsonl","run-memory.jsonl","repo-graph.json","repo-graph.fingerprint.json","doc-manifest.json","dark-matter.md","telemetry.jsonl","telemetry.jsonl.1","session-reflection.md","spec.md","spec-staleness.json","spec-snapshot.md","swarm.db",REPO_MEMORY_FILENAME,"epic-state.json","turbo-state.json","workspace-snapshot.digest"],TERMINAL_STATE_FILES=["plan.json","plan-ledger.jsonl","spec-staleness.json","spec-snapshot.md"],KNOWLEDGE_FAMILY_ARTIFACTS=new Set(["knowledge.jsonl","knowledge-rejected.jsonl"]),REQUIRED_ARTIFACTS=new Set(["plan.json","plan-ledger.jsonl"]),ACTIVE_STATE_DIRS_TO_CLEAN=["coder-settlements","council","evidence","session","scopes","spec-archive","task-repairs","task-terminals","runs","epic"],ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS=[25,50,100,200,400,600,800,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000]});import*as fsSync12 from"node:fs";import{promises as fs80}from"node:fs";var closeReceiptLifecycleInternals,_internals118;var init_internals=__esm(()=>{init_audit_log();init_shell_audit_store();init_constants2();closeReceiptLifecycleInternals={recordPhaseCloseIntent:void 0,reconcilePhaseClose:void 0},_internals118={closeSnapshotCoordinationInitialization:void 0,closeRepoMemory:void 0,unlinkActiveStateFileWithRetry:void 0,unlink:fs80.unlink,unlinkSidecarSync:fsSync12.unlinkSync,sleep:void 0,collectGarbageBestEffort:void 0,ACTIVE_STATE_DIRS_TO_CLEAN,countSessionKnowledgeEntries:void 0,CLOSE_SKILL_REVIEW_TIMEOUT_MS,CLOSE_REFLECTION_TIMEOUT_MS,detectFullAuto:void 0,guaranteeAllPlansComplete:void 0,getGitRepositoryStatus:void 0,resetToMainAfterMerge:void 0,resetToRemoteBranch:void 0,copyDirRecursive:void 0,loadPluginConfigWithMeta:void 0,curateAndStoreSwarm:void 0,checkHivePromotions:void 0,runCuratorPostMortem:void 0,createCuratorLLMDelegate:void 0,resetSwarmStatePreservingSingletons:void 0,runFinalizeStage:void 0,runFinalizeRewardSweep:void 0,acquireFinalizeLock:void 0,runArchiveStage:void 0,archiveCloseSummary:void 0,runArchiveEvidenceRetention:void 0,runCleanStage:void 0,runAlignStage:void 0,runFinalizeDryRun:void 0,archiveEvidence:void 0,closePlanTerminalState:void 0,endAgentSession:void 0,flushAndDrainTelemetry:void 0,finalizeContextTelemetry:void 0,finalizeCoreEvents:void 0,finalizeShellAudit:(directory)=>{finalizeShellAuditForClose(directory,{lineTransform:redactDecisionLineForArchive})}}});function renderRecheckRefusal(reason,newDirtyPaths){let listed=newDirtyPaths.slice(0,10),overflow=newDirtyPaths.length-listed.length,swarmHint=newDirtyPaths.some((p)=>p.startsWith(".swarm/"))?"One or more changed paths are under .swarm/ — this project tracks swarm runtime state in git. Consider `git rm -r --cached .swarm/` and re-adding `.swarm/` to .git/info/exclude; close never confirms runtime state as destructive scope.":void 0;return[`\uD83D\uDED1 Git alignment aborted (fail-closed): ${reason} — this destructive scope was never confirmed${listed[0]?` (first: ${listed[0]})`:""}.`,...listed.map((p)=>` - ${p}`),...overflow>0?[` … and ${overflow} more`]:[],...swarmHint?[swarmHint]:[],"Nothing was reset or checked out; the session is finalized (finalize/archive/clean completed). Complete git alignment manually if still wanted."].join(`
1387
+ `)}async function guardResetWithRecheck(real,cwd,options){let recheck=recheckBeforeDestructive(cwd,options?.expectedDirtyPaths??[]);if(recheck.ok)return real(cwd,{pruneBranches:options?.pruneBranches});return log(`[close-align] re-check refused destructive reset: ${recheck.reason} (${recheck.newDirtyPaths.length} newly-dirty path(s))`),{success:!1,targetBranch:"",previousBranch:"",message:renderRecheckRefusal(recheck.reason,recheck.newDirtyPaths),branchDeleted:!1,changesDiscarded:!1,warnings:[],recheckRefused:!0}}async function runAlignStage(ctx){let pruneBranches=ctx.args.includes("--prune-branches"),gitAlignResult="",prunedBranches=[],gitStatus=_internals118.getGitRepositoryStatus(ctx.directory);if(gitStatus.isRepo){let aggressiveResult=await _internals118.resetToMainAfterMerge(ctx.directory,{pruneBranches,expectedDirtyPaths:ctx.purgeGateDirtyPaths??[]});if(aggressiveResult.recheckRefused)return gitAlignResult=aggressiveResult.message,ctx.warnings.push(aggressiveResult.message),{gitAlignResult,prunedBranches};if(aggressiveResult.success){gitAlignResult=aggressiveResult.message;for(let w of aggressiveResult.warnings)ctx.warnings.push(w);if(aggressiveResult.changesDiscarded)ctx.warnings.push("Uncommitted changes were discarded during git alignment")}else{let alignResult=await _internals118.resetToRemoteBranch(ctx.directory,{pruneBranches});if(gitAlignResult=alignResult.message,prunedBranches.push(...alignResult.prunedBranches),!alignResult.success)ctx.warnings.push(`Git alignment: ${alignResult.message}`);if(alignResult.alreadyAligned)gitAlignResult=`Already aligned with ${alignResult.targetBranch}`;for(let w of alignResult.warnings)ctx.warnings.push(w)}}else if(gitStatus.reason==="git_unavailable")gitAlignResult=`Git executable unavailable — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else if(gitStatus.reason==="git_error")gitAlignResult=`Git repository check failed — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else gitAlignResult="Not a git repository — skipped git alignment";return{gitAlignResult,prunedBranches}}var init_align_stage=__esm(()=>{init_logger();init_destructive_purge();init_internals()});import*as fsSync13 from"node:fs";import path130 from"node:path";function resolveDatabaseCtor(){return _internals119.DatabaseCtor??loadDatabaseCtor()}function safeRemoveTemp(tempPath){try{_internals119.rmSync(tempPath,{force:!0,recursive:!0,maxRetries:3,retryDelay:100})}catch{}}function buildVacuumIntoSql(destPath){return`VACUUM INTO '${destPath.replace(/\\/g,"/").replace(/'/g,"''")}'`}function rowString(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];return v===null||v===void 0?"":String(v)}return""}function rowNumber(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];if(typeof v==="number"&&Number.isFinite(v))return v;if(typeof v==="bigint")return Number(v);if(typeof v==="string"){let n=Number(v);if(Number.isFinite(n))return n}}return null}function captureRowCounts(db){let tableExists=(name)=>{let row=db.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name);return rowNumber(row,"c")!==null&&(rowNumber(row,"c")??0)>0},schemaMigrationsMax=null;if(tableExists("schema_migrations")){let row=db.query("SELECT MAX(version) AS m FROM schema_migrations").get();schemaMigrationsMax=rowNumber(row,"m")}let projectConstraints=tableExists("project_constraints")?rowNumber(db.query("SELECT COUNT(*) AS c FROM project_constraints").get(),"c")??0:0,qaGateProfile=tableExists("qa_gate_profile")?rowNumber(db.query("SELECT COUNT(*) AS c FROM qa_gate_profile").get(),"c")??0:0;return{schema_migrations_max_version:schemaMigrationsMax,project_constraints:projectConstraints,qa_gate_profile:qaGateProfile}}async function archiveSqliteSnapshot(opts){let maxSourceBytes=opts.maxSourceBytes??DEFAULT_MAX_SOURCE_BYTES2,busyTimeoutMs=opts.busyTimeoutMs??DEFAULT_BUSY_TIMEOUT_MS;if(!_internals119.existsSync(opts.sourcePath))return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"};let sourceBytes=0;for(let suffix of["","-wal","-shm"]){let sidecar=opts.sourcePath+suffix;if(!_internals119.existsSync(sidecar))continue;try{sourceBytes+=_internals119.statSync(sidecar).size}catch(err){if(suffix==="")return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`source stat failed: ${err instanceof Error?err.message:String(err)}`}}}if(sourceBytes>maxSourceBytes)return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"retained",method:"none",reason_code:"source_over_budget",detail:`source bytes ${sourceBytes} > budget ${maxSourceBytes}`};let destFinal=path130.join(opts.destDir,opts.destName),destTemp=path130.join(opts.destDir,`.${opts.destName}.tmp.${_internals119.now()}.${_internals119.randomSuffix()}`),Db;try{Db=resolveDatabaseCtor()}catch(err){return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`driver unavailable: ${err instanceof Error?err.message:String(err)}`}}let snapshotDb=null;try{snapshotDb=new Db(opts.sourcePath);try{snapshotDb.run(`PRAGMA busy_timeout = ${busyTimeoutMs};`),snapshotDb.run(buildVacuumIntoSql(destTemp))}finally{snapshotDb.close(),snapshotDb=null}}catch(err){if(snapshotDb)try{snapshotDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:err instanceof Error?err.message:String(err)}}let rowCounts,verifyDb=null;try{verifyDb=new Db(destTemp),verifyDb.run("PRAGMA query_only = ON;");let integrityRow=verifyDb.query("PRAGMA integrity_check").get(),integrity=rowString(integrityRow,"integrity_check");if(integrity!=="ok")return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:`integrity_check: ${integrity||"(empty)"}`};if((rowNumber(verifyDb.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='schema_migrations'").get(),"c")??0)<1)return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"schema_mismatch",detail:"schema_migrations table absent"};rowCounts=captureRowCounts(verifyDb),verifyDb.close(),verifyDb=null}catch(err){if(verifyDb)try{verifyDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:err instanceof Error?err.message:String(err)}}try{_internals119.renameSync(destTemp,destFinal)}catch(err){return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"publish_failed",detail:err instanceof Error?err.message:String(err),rowCounts}}return{requiredness:"required",attempt:"succeeded",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"ok",destPath:destFinal,rowCounts}}var DEFAULT_MAX_SOURCE_BYTES2=2147483648,DEFAULT_BUSY_TIMEOUT_MS=5000,_internals119;var init_archive_sqlite=__esm(()=>{init_sqlite_loader();_internals119={existsSync:fsSync13.existsSync,statSync:fsSync13.statSync,renameSync:fsSync13.renameSync,rmSync:fsSync13.rmSync,now:()=>Date.now(),randomSuffix:()=>Math.random().toString(36).slice(2,8),DatabaseCtor:null}});import{promises as fs81}from"node:fs";import path131 from"node:path";async function copyDirRecursiveWithFailures(src,dest){let count2=0,failures=[],entries=await fs81.readdir(src);await fs81.mkdir(dest,{recursive:!0});for(let entry of entries){let srcEntry=path131.join(src,entry),destEntry=path131.join(dest,entry);try{if((await fs81.stat(srcEntry)).isDirectory()){let subResult=await copyDirRecursiveWithFailures(srcEntry,destEntry);count2+=subResult.copied,failures.push(...subResult.failures)}else try{await fs81.copyFile(srcEntry,destEntry),count2++}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}return{copied:count2,failures}}async function copyDirRecursive(src,dest){return(await copyDirRecursiveWithFailures(src,dest)).copied}async function unlinkActiveStateFileWithRetry(filePath){for(let attempt=0;;attempt+=1)try{await _internals118.unlink(filePath);return}catch(error93){let code=error93?.code,delay2=ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS[attempt];if(code!=="EBUSY"&&code!=="EPERM"||delay2===void 0)throw error93;_internals118.collectGarbageBestEffort(),await _internals118.sleep(delay2)}}var init_fs_helpers=__esm(()=>{init_constants2();init_internals()});import*as fsSync14 from"node:fs";import{promises as fs82}from"node:fs";import path132 from"node:path";function emitCloseArchiveResult(ctx,cleanResult){let cleaned=new Set(cleanResult.cleanedFiles),failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,sqliteSnapshots=ctx.archiveResults.filter((r)=>r.method==="vacuum_into"&&r.attempt==="succeeded"),archiveEmpty=sqliteSnapshots.length>0&&sqliteSnapshots.every((r)=>(r.row_counts?.project_constraints??0)===0&&(r.row_counts?.qa_gate_profile??0)===0),archiveValid=!ctx.archiveStageFailed&&failedCount===0;try{telemetry.closeArchiveResult({archive_valid:archiveValid,archive_empty:archiveEmpty,file_count:ctx.archivedFileCount,bundle:`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`,artifacts:ctx.archiveResults.map((r)=>{let removed=cleaned.has(r.artifact);return{artifact:r.artifact,requiredness:r.requiredness,attempt:r.attempt,validation:r.validation,source_disposition:removed?"removed":r.source_disposition,method:r.method,reason_code:r.reason_code,...r.row_counts?{row_counts:r.row_counts}:{}}})})}catch(telemetryErr){log("[close-command] close_archive_result telemetry emit failed:",telemetryErr)}observeCloseArchive({directory:ctx.directory,archiveValid,archiveEmpty,activityPredictsContent:archiveActivityPredictsContent(ctx.directory)})}function archiveActivityPredictsContent(directory){try{for(let name of["knowledge-events.jsonl","telemetry.jsonl","evidence"]){let target=path132.join(directory,".swarm",name),stat13=fsSync14.statSync(target);if(target.endsWith("evidence")){if(fsSync14.readdirSync(target).length>0)return!0}else if(stat13.size>0)return!0}return!1}catch{return!1}}async function runArchiveStage(ctx){ctx.timestamp=new Date().toISOString().replace(/[:.]/g,"-"),ctx.archiveSuffix=Math.random().toString(36).slice(2,8),ctx.archiveDir=path132.join(ctx.swarmDir,"archive",`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`);try{await fs82.mkdir(ctx.archiveDir,{recursive:!0});try{await _internals118.flushAndDrainTelemetry()}catch(flushErr){let msg=flushErr instanceof Error?flushErr.message:String(flushErr);ctx.warnings.push(`Telemetry flush before archive failed: ${msg}`)}try{_internals118.finalizeContextTelemetry(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Context-map telemetry finalize before archive failed: ${msg}`)}try{_internals118.finalizeCoreEvents(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Core events finalize before archive failed: ${msg}`)}try{_internals118.finalizeShellAudit(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Shell audit finalize before archive failed: ${msg}`)}let linkedKnowledgeShared=isLinked(ctx.directory);if(linkedKnowledgeShared)ctx.warnings.push("Worktree is linked: shared knowledge (knowledge.jsonl, knowledge-rejected.jsonl) lives in the link store and is not archived or cleaned by /swarm close. Manage it via the link.");for(let artifact of ARCHIVE_ARTIFACTS){if(linkedKnowledgeShared&&KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact))continue;let srcPath=path132.join(ctx.swarmDir,artifact),destPath=path132.join(ctx.archiveDir,artifact),requiredness=REQUIRED_ARTIFACTS.has(artifact)?"required":"optional";if(artifact==="swarm.db"||artifact===REPO_MEMORY_FILENAME){let r=await archiveSqliteSnapshot({sourcePath:srcPath,destDir:ctx.archiveDir,destName:artifact}),result={artifact,requiredness,attempt:r.attempt,validation:r.validation,source_disposition:r.attempt==="succeeded"?"retained":r.source_disposition,method:r.method,reason_code:r.reason_code,detail:r.detail,row_counts:r.rowCounts};if(ctx.archiveResults.push(result),r.attempt==="succeeded"&&r.validation==="passed"){if(ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact)}else if(!(r.attempt==="not_attempted"&&r.source_disposition==="absent"))ctx.archiveFailureReasons.set(artifact,`${r.reason_code}: ${r.detail??""}`),ctx.warnings.push(`Failed to archive ${artifact} [${r.reason_code}]: ${r.detail??""}. Source preserved.`)}else try{if(await fs82.copyFile(srcPath,destPath),ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact);ctx.archiveResults.push({artifact,requiredness,attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno==="ENOENT")ctx.archiveResults.push({artifact,requiredness,attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"});else{let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness,attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}}}let dynamicArchiveArtifacts=(await fs82.readdir(ctx.swarmDir).catch(()=>[])).filter((name)=>/^post-mortem-[^/\\]+\.md$/.test(name)||/^drift-report-phase-\d+\.json$/.test(name));for(let artifact of dynamicArchiveArtifacts){let srcPath=path132.join(ctx.swarmDir,artifact),destPath=path132.join(ctx.archiveDir,artifact);try{await fs82.copyFile(srcPath,destPath),ctx.archivedFileCount++,ctx.archivedActiveStateFiles.add(artifact),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno!=="ENOENT"){let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}else ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"})}}for(let dirName of ACTIVE_STATE_DIRS_TO_CLEAN){let srcDir=path132.join(ctx.swarmDir,dirName),destDir=path132.join(ctx.archiveDir,dirName);try{let result=await copyDirRecursiveWithFailures(srcDir,destDir);if(ctx.archivedFileCount+=result.copied,result.failures.length===0)ctx.archivedActiveStateDirs.add(dirName);else{ctx.warnings.push(`Directory ${dirName} not fully archived (${result.failures.length} failure(s)). Source preserved.`);for(let failure of result.failures)ctx.warnings.push(` - ${failure}`)}}catch(err){let code=err.code;if(code!=="ENOENT")ctx.warnings.push(`Failed to archive directory ${dirName} [${code??"unknown"}]: ${err.message}. Source preserved.`)}}let succeededCount=ctx.archiveResults.filter((r)=>r.attempt==="succeeded").length,failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,absentCount=ctx.archiveResults.filter((r)=>r.source_disposition==="absent").length,bundleName=`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`;ctx.archiveResult=failedCount>0?`Archive partial: ${succeededCount} succeeded, ${failedCount} failed, ${absentCount} absent (see warnings). Bundle: .swarm/archive/${bundleName}/`:`Archived ${ctx.archivedFileCount} artifact(s) to .swarm/archive/${bundleName}/`}catch(archiveError){ctx.warnings.push(`Archive creation failed: ${archiveError instanceof Error?archiveError.message:String(archiveError)}`),ctx.archiveResult="Archive creation failed (see warnings)",ctx.archiveStageFailed=!0}await runArchiveEvidenceRetention({directory:ctx.directory,swarmDir:ctx.swarmDir,config:ctx.config,warnings:ctx.warnings})}async function runArchiveEvidenceRetention(ctx){let maxAgeDays=30,maxBundles=10,cacheMaxBytes,cacheMaxRecords;try{let{config:evidenceLoadedConfig}=_internals118.loadPluginConfigWithMeta(ctx.directory),evidenceCfg=evidenceLoadedConfig.evidence??{};if(typeof evidenceCfg.max_age_days==="number")maxAgeDays=evidenceCfg.max_age_days;if(typeof evidenceCfg.max_bundles==="number")maxBundles=evidenceCfg.max_bundles;if(typeof evidenceCfg.cache_max_bytes==="number")cacheMaxBytes=evidenceCfg.cache_max_bytes;if(typeof evidenceCfg.cache_max_records==="number")cacheMaxRecords=evidenceCfg.cache_max_records}catch{}try{await _internals118.archiveEvidence(ctx.directory,maxAgeDays,maxBundles,{report:!0,cacheMaxBytes,cacheMaxRecords})}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Evidence retention archive failed: ${msg}`),log("[close-command] archiveEvidence error:",error93)}}var init_archive_stage=__esm(()=>{init_learning_health();init_knowledge_link();init_telemetry();init_indexed_storage();init_logger();init_archive_sqlite();init_constants2();init_fs_helpers();init_internals()});import{createHash as createHash63}from"node:crypto";import*as fs83 from"node:fs";import*as path133 from"node:path";function collectCandidates(swarmRoot){let items=[],scannedEntries=0,truncated=!1,walk=(relDir,depth)=>{if(truncated)return;let absDir=relDir===""?swarmRoot:path133.join(swarmRoot,...relDir.split("/")),dirents;try{dirents=fs83.readdirSync(absDir,{withFileTypes:!0})}catch{return}for(let dirent of dirents){if(++scannedEntries>MAX_RESIDUE_SCAN_ENTRIES){truncated=!0;return}if(relDir===""&&RESIDUE_SKIP_DIRS.includes(dirent.name))continue;let rel=relDir===""?dirent.name:`${relDir}/${dirent.name}`;if(dirent.isDirectory()&&!dirent.isSymbolicLink()){if(depth+1<=RESIDUE_SCAN_DEPTH)walk(rel,depth+1);continue}let grammar=matchTempGrammar(dirent.name);if(!grammar)continue;let bytes=0,mtimeMs=0;if(!dirent.isSymbolicLink())try{let st=fs83.lstatSync(path133.join(swarmRoot,...rel.split("/")));if(!st.isFile())continue;bytes=st.size,mtimeMs=st.mtimeMs}catch{continue}items.push({relPath:rel,grammar,isSymlink:dirent.isSymbolicLink(),bytes,mtimeMs})}};return walk("",0),{items,scannedEntries,truncated}}async function inventorySwarmResidue(directory){let swarmRoot=path133.normalize(path133.resolve(directory,".swarm"));if(!fs83.existsSync(swarmRoot))return{swarmRoot,scannedEntries:0,truncated:!1,entries:[],summary:{matched:0,eligible:0,ambiguous:0,totalBytes:0,oldestAgeMs:0},gitState:"unknown"};if(fs83.lstatSync(swarmRoot).isSymbolicLink())throw Error(`Refusing to scan a symlinked .swarm root: ${swarmRoot}`);let projectRoot=path133.dirname(swarmRoot),{tracked}=_internals120.queryTracked(projectRoot,swarmRoot),lockTargets=_internals120.activeLockTargets(directory),{items,scannedEntries,truncated}=collectCandidates(swarmRoot),now2=_internals120.now(),entries=[];for(let item of items){let ageMs=Math.max(0,now2-item.mtimeMs);if(item.grammar.token==="constant"&&item.grammar.id!=="dot-tmp-prefix-legacy"){if(ageMs<RESIDUE_STALE_AGE_MS)continue}let abs=path133.normalize(path133.join(swarmRoot,...item.relPath.split("/"))),reasons=[];if(!item.grammar.quarantineEligible)reasons.push("constant-name-grammar");if(ageMs<RESIDUE_STALE_AGE_MS)reasons.push("recent");let trackedState;if(tracked===void 0){if(trackedState="unknown",item.grammar.quarantineEligible)reasons.push("tracked-state-unknown")}else if(trackedState=tracked.has(abs)?"tracked":"untracked",trackedState==="tracked")reasons.push("git-tracked");if(item.isSymlink)reasons.push("symlink");let lockHeld=lockTargets.has(abs)||(item.grammar.parsesTarget?lockTargets.has(path133.normalize(path133.join(path133.dirname(abs),parseTargetBasename(item.relPath.split("/").pop()??"")??""))):!1);if(lockHeld)reasons.push("active-lock");if(item.bytes>RESIDUE_HASH_MAX_BYTES)reasons.push("oversize");if(item.grammar.quarantineEligible&&item.grammar.parsesTarget){let targetBasename=parseTargetBasename(item.relPath.split("/").pop()??"");if(targetBasename){let targetAbs=path133.join(path133.dirname(abs),targetBasename),targetOk=!1;try{targetOk=fs83.lstatSync(targetAbs).isFile()}catch{targetOk=!1}if(!targetOk)reasons.push("target-absent")}}entries.push({relPath:item.relPath,grammarId:item.grammar.id,grammarEra:item.grammar.era,bytes:item.bytes,mtimeMs:item.mtimeMs,ageMs,isSymlink:item.isSymlink,tracked:trackedState,lockHeld,proposedAction:item.grammar.quarantineEligible&&reasons.length===0?"quarantine":"report_only",reasons})}entries.sort((a,b)=>b.ageMs-a.ageMs);let eligible=entries.filter((e)=>e.proposedAction==="quarantine");return{swarmRoot,scannedEntries,truncated,entries,summary:{matched:entries.length,eligible:eligible.length,ambiguous:entries.length-eligible.length,totalBytes:entries.reduce((sum,e)=>sum+e.bytes,0),oldestAgeMs:entries[0]?.ageMs??0},gitState:tracked===void 0?"unknown":"ok"}}function validateRelPath(rel,what){if(!rel||path133.isAbsolute(rel)||rel.split("/").some((s)=>s===".."||s===""||/[\0-\x1f]/.test(s)))throw Error(`unsafe ${what} in quarantine manifest: ${JSON.stringify(rel)}`);return rel}function sha256Bounded(absPath){try{return _internals120.sha256File(absPath)}catch{return}}async function quarantineSwarmResidue(directory,options){let inventory=await inventorySwarmResidue(directory),eligible=inventory.entries.filter((e)=>e.proposedAction==="quarantine"),preserved=inventory.entries.filter((e)=>e.proposedAction==="report_only").map((e)=>({relPath:e.relPath,status:"preserved",reasons:e.reasons}));if(options?.dryRun||eligible.length===0)return{inventory,quarantined:0,preserved};let swarmRoot=inventory.swarmRoot,batchId=`${new Date().toISOString().replace(/[:.]/g,"-")}-${Math.random().toString(36).slice(2,10)}`,batchAbs=path133.join(swarmRoot,"quarantine",batchId);fs83.mkdirSync(batchAbs,{recursive:!0});let manifest={schema_version:1,batch_id:batchId,created_at:new Date().toISOString(),trigger:options?.trigger??"manual",entries:[]},moved=[];for(let entry of eligible){let abs=path133.join(swarmRoot,...entry.relPath.split("/"));try{let st=fs83.lstatSync(abs);if(!st.isFile()||st.size!==entry.bytes||st.mtimeMs!==entry.mtimeMs){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["changed-since-scan"]});continue}}catch{preserved.push({relPath:entry.relPath,status:"preserved",reasons:["vanished"]});continue}let sha=sha256Bounded(abs);if(!sha){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["hash-failed"]});continue}let storedAbs=path133.join(batchAbs,...entry.relPath.split("/"));try{fs83.mkdirSync(path133.dirname(storedAbs),{recursive:!0}),_internals120.renameResidueEntry(abs,storedAbs)}catch(moveErr){let code=moveErr?.code??"unknown";preserved.push({relPath:entry.relPath,status:"preserved",reasons:[`move-failed:${code}`]});continue}manifest.entries.push({original_rel_path:entry.relPath,stored_rel_path:path133.posix.join("quarantine",batchId,entry.relPath),sha256:sha,bytes:entry.bytes,mtime_ms:entry.mtimeMs,grammar_id:entry.grammarId,reason:"stale-atomic-write-temp"}),moved.push({relPath:entry.relPath,status:"quarantined",reasons:[]})}let batchRelDir;if(manifest.entries.length>0)atomicWriteSwarmFileSync(path133.join(batchAbs,"manifest.json"),`${JSON.stringify(manifest,null,2)}
1388
1388
  `),batchRelDir=path133.posix.join("quarantine",batchId);else try{fs83.rmSync(batchAbs,{recursive:!0,force:!0})}catch{}try{telemetry.residueHealth({trigger:options?.trigger??"manual",scanned:inventory.scannedEntries,matched:inventory.summary.matched,eligible:inventory.summary.eligible,ambiguous:inventory.summary.ambiguous,quarantined:manifest.entries.length,preserved:preserved.length,total_bytes:inventory.summary.totalBytes,oldest_age_ms:inventory.summary.oldestAgeMs,grammar_counts:Object.fromEntries(Object.entries(inventory.entries.reduce((acc,e)=>{return acc[e.grammarId]=(acc[e.grammarId]??0)+1,acc},{})).sort())})}catch{}return{inventory,batchRelDir,quarantined:manifest.entries.length,preserved}}function listQuarantineBatches(swarmRoot){let quarantineRoot=path133.join(swarmRoot,"quarantine");try{return fs83.readdirSync(quarantineRoot,{withFileTypes:!0}).filter((d)=>d.isDirectory()&&!d.isSymbolicLink()).map((d)=>d.name).sort()}catch{return[]}}async function rollbackResidueQuarantine(directory,batchId){let swarmRoot=path133.normalize(path133.resolve(directory,".swarm")),batches=listQuarantineBatches(swarmRoot);if(batches.length===0)throw Error("No quarantine batches found under .swarm/quarantine/");let selected=batchId?batches.find((b)=>b===batchId||b.endsWith(`-${batchId}`))??(()=>{throw Error(`Quarantine batch not found: ${batchId}`)})():batches[batches.length-1],batchAbs=path133.join(swarmRoot,"quarantine",selected),manifestPath2=path133.join(batchAbs,"manifest.json"),manifest;try{manifest=JSON.parse(fs83.readFileSync(manifestPath2,"utf-8"))}catch{throw Error(`Quarantine batch has no readable manifest.json: ${selected}`)}if(manifest.schema_version!==1||!Array.isArray(manifest.entries))throw Error(`Quarantine manifest has an unsupported shape: ${selected}`);let items=[],allResolved=!0;for(let entry of manifest.entries){let originalRel=validateRelPath(entry.original_rel_path,"original_rel_path"),storedRel=validateRelPath(entry.stored_rel_path,"stored_rel_path"),originalAbs=path133.join(swarmRoot,...originalRel.split("/")),storedAbs=path133.join(swarmRoot,...storedRel.split("/"));if(!originalAbs.startsWith(swarmRoot+path133.sep)||!storedAbs.startsWith(batchAbs+path133.sep))throw Error(`Quarantine manifest path escapes its root: ${selected}`);if(!fs83.existsSync(storedAbs)){items.push({relPath:originalRel,status:"missing-copy"}),allResolved=!1;continue}if(fs83.existsSync(originalAbs)){if(sha256Bounded(originalAbs)===entry.sha256)fs83.unlinkSync(storedAbs),items.push({relPath:originalRel,status:"already-restored"});else items.push({relPath:originalRel,status:"collision"}),allResolved=!1;continue}fs83.mkdirSync(path133.dirname(originalAbs),{recursive:!0}),fs83.renameSync(storedAbs,originalAbs),items.push({relPath:originalRel,status:"restored"})}if(allResolved)try{fs83.rmSync(batchAbs,{recursive:!0,force:!0})}catch{}return{batchRelDir:path133.posix.join("quarantine",selected),items,drained:allResolved}}function formatAge(ms){if(ms<=0)return"0s";let minutes=Math.floor(ms/60000);if(minutes<60)return`${minutes}m`;let hours=Math.floor(minutes/60);if(hours<48)return`${hours}h`;return`${Math.floor(hours/24)}d`}function formatResidueInventoryLines(inv,options){let maxEntries=options?.maxEntries??10,s=inv.summary,lines=[];lines.push(`- Matched registered temp grammars: ${s.matched} file(s), ${s.totalBytes} byte(s), oldest ${formatAge(s.oldestAgeMs)} old`),lines.push(`- Eligible for quarantine (stale ≥ ${Math.round(RESIDUE_STALE_AGE_MS/60000)}m, untracked, unlocked, non-symlink): ${s.eligible}; preserved/ambiguous: ${s.ambiguous}${inv.gitState==="unknown"?" (git tracked-state unknown — nothing quarantined)":""}`);let byGrammar=new Map;for(let e of inv.entries){let g=byGrammar.get(e.grammarId)??{count:0,bytes:0};g.count++,g.bytes+=e.bytes,byGrammar.set(e.grammarId,g)}for(let[id,g]of[...byGrammar.entries()].sort((a,b)=>b[1].count-a[1].count))lines.push(` - ${id}: ${g.count} file(s), ${g.bytes} byte(s)`);for(let e of inv.entries.slice(0,maxEntries)){let flags=[`${formatAge(e.ageMs)} old`,e.tracked==="tracked"?"git-tracked":e.tracked,e.isSymlink?"symlink":null,e.lockHeld?"locked":null,...e.reasons].filter(Boolean),safeRel=e.relPath.replace(/`/g,"'");lines.push(` - \`${safeRel}\` [${e.grammarId}] → ${e.proposedAction==="quarantine"?"would quarantine":"preserve"} (${flags.join(", ")})`)}if(inv.entries.length>maxEntries)lines.push(` - … ${inv.entries.length-maxEntries} more (bounded report)`);if(inv.truncated)lines.push(` - scan truncated at ${MAX_RESIDUE_SCAN_ENTRIES} entries — inventory is partial`);return lines}var RESIDUE_STALE_AGE_MS=1800000,MAX_RESIDUE_SCAN_ENTRIES=20000,RESIDUE_SCAN_DEPTH=8,RESIDUE_HASH_MAX_BYTES=134217728,RESIDUE_SKIP_DIRS,_internals120;var init_swarm_residue=__esm(()=>{init_file_locks();init_telemetry();init_atomic_write();init_bun_compat();RESIDUE_SKIP_DIRS=Object.freeze(["archive","quarantine","locks"]),_internals120={now:()=>Date.now(),renameResidueEntry:(from,to)=>{fs83.renameSync(from,to)},queryTracked:(projectRoot,swarmRoot)=>{let result=bunSpawnSync(["git","-c","core.quotepath=false","ls-files","--",swarmRoot.split(path133.sep).join("/")],{cwd:projectRoot,stdin:"ignore",timeout:5000,envOverrides:{GIT_DIR:null,GIT_WORK_TREE:null,GIT_INDEX_FILE:null}});if(result.exitCode!==0)return{tracked:void 0};let out=new TextDecoder().decode(result.stdout),tracked=new Set;for(let line of out.split(/\r?\n/)){let t=line.trim();if(t)tracked.add(path133.normalize(path133.resolve(projectRoot,t)))}return{tracked}},activeLockTargets:(directory)=>{let targets=new Set;for(let lock of listActiveLocks(directory))targets.add(path133.normalize(path133.resolve(directory,lock.filePath)));return targets},sha256File:(absPath)=>{let hash4=createHash63("sha256"),fd=fs83.openSync(absPath,"r");try{let chunk=Buffer.alloc(1048576);for(;;){let read=fs83.readSync(fd,chunk,0,chunk.byteLength,null);if(read===0)break;hash4.update(chunk.subarray(0,read))}}finally{fs83.closeSync(fd)}return hash4.digest("hex")}}});import path134 from"node:path";function removeSqliteSidecarsAfterClose(swarmDir){for(let sidecar of["swarm.db-wal","swarm.db-shm"])try{_internals118.unlinkSidecarSync(path134.join(swarmDir,sidecar))}catch(error93){let code=error93?.code;if(code!=="ENOENT"&&code!=="EBUSY")log("[close-command] failed to remove sqlite sidecar:",error93)}}var init_db_helpers=__esm(()=>{init_logger();init_internals()});import{promises as fs84}from"node:fs";import path135 from"node:path";async function runCleanStage(ctx){let configBackupsRemoved=0,cleanedFiles=[],linkedKnowledgeShared=isLinked(ctx.directory);if(linkedKnowledgeShared){for(let artifact of KNOWLEDGE_FAMILY_ARTIFACTS)if(ctx.archivedActiveStateFiles.has(artifact))ctx.warnings.push(`[link-guard] Shared knowledge artifact "${artifact}" appears in `+"the archive set while this worktree is linked — archive stage "+"should have skipped it. Artifact will NOT be deleted.")}if(ctx.archivedActiveStateFiles.size>0)for(let artifact of ACTIVE_STATE_TO_CLEAN){if(linkedKnowledgeShared&&KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact))continue;if(!ctx.archivedActiveStateFiles.has(artifact)){let reason=ctx.archiveFailureReasons?.get(artifact);if(TERMINAL_STATE_FILES.includes(artifact)){ctx.warnings.push(reason?`${artifact} was not archived (${reason}); removing it anyway to prevent CLOSED-plan resurrection next session — no archive copy retained.`:`${artifact} was not archived; removing it anyway to prevent CLOSED-plan resurrection next session — no archive copy retained.`);continue}if(reason)ctx.warnings.push(`Preserved ${artifact} because it was not successfully archived: ${reason}.`);continue}let filePath=path135.join(ctx.swarmDir,artifact);if(artifact==="swarm.db"){try{await _internals118.closeSnapshotCoordinationInitialization(ctx.directory)}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Preserved swarm.db because snapshot coordination did not settle: ${reason}.`);continue}try{closeGroupCommitWriter(ctx.directory)}catch{}try{closeProjectDb(ctx.directory)}catch{}}if(artifact===REPO_MEMORY_FILENAME)try{_internals118.closeRepoMemory(ctx.directory)}catch{}try{await _internals118.unlinkActiveStateFileWithRetry(filePath),cleanedFiles.push(artifact)}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean active-state file ${artifact} [${errno??"unknown"}]: ${reason}`)}}if(artifact==="swarm.db")removeSqliteSidecarsAfterClose(ctx.swarmDir)}else ctx.warnings.push("Skipped active-state cleanup because no active-state files were archived. Files preserved to prevent data loss.");for(let artifact of ctx.archivedActiveStateFiles){if(!/^post-mortem-[^/\\]+\.md$/.test(artifact)&&!/^drift-report-phase-\d+\.json$/.test(artifact))continue;try{await fs84.unlink(path135.join(ctx.swarmDir,artifact)),cleanedFiles.push(artifact)}catch(err){let errno=err?.code;if(errno!=="ENOENT"){let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean active-state file ${artifact} [${errno??"unknown"}]: ${reason}`)}}}for(let dirName of ACTIVE_STATE_DIRS_TO_CLEAN){if(!ctx.archivedActiveStateDirs.has(dirName))continue;let dirPath=path135.join(ctx.swarmDir,dirName);try{await fs84.rm(dirPath,{recursive:!0,force:!0}),cleanedFiles.push(`${dirName}/`)}catch{}}try{let swarmFiles=await fs84.readdir(ctx.swarmDir),configBackups=swarmFiles.filter((f)=>f.startsWith("config-backup-")&&f.endsWith(".json"));for(let backup of configBackups)try{await fs84.unlink(path135.join(ctx.swarmDir,backup)),configBackupsRemoved++}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean config-backup ${backup} [${errno??"unknown"}]: ${reason}`)}}let ledgerSiblings=swarmFiles.filter((f)=>(f.startsWith("plan-ledger.archived-")||f.startsWith("plan-ledger.backup-"))&&f.endsWith(".jsonl"));for(let sibling of ledgerSiblings)try{await fs84.unlink(path135.join(ctx.swarmDir,sibling))}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean ledger sibling ${sibling} [${errno??"unknown"}]: ${reason}`)}}}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to read ${ctx.swarmDir} for stale-file cleanup [${errno??"unknown"}]: ${reason}`)}}let swarmPlanFilesRemoved=0,candidates=[path135.join(ctx.directory,".swarm","plan-export","SWARM_PLAN.json"),path135.join(ctx.directory,".swarm","plan-export","SWARM_PLAN.md"),path135.join(ctx.directory,".swarm","SWARM_PLAN.json"),path135.join(ctx.directory,".swarm","SWARM_PLAN.md"),path135.join(ctx.directory,"SWARM_PLAN.json"),path135.join(ctx.directory,"SWARM_PLAN.md")];for(let candidate of candidates)try{await fs84.unlink(candidate),swarmPlanFilesRemoved++}catch(err){if(err?.code!=="ENOENT")ctx.warnings.push(`Failed to remove ${candidate}: ${err instanceof Error?err.message:String(err)}`)}let residueQuarantined=0,residuePreserved=0;try{let residue=await quarantineSwarmResidue(ctx.directory,{trigger:"close"});if(residueQuarantined=residue.quarantined,residuePreserved=residue.preserved.length,residue.quarantined>0&&residue.batchRelDir)cleanedFiles.push(`${residue.quarantined} stale temp file(s) → ${residue.batchRelDir}/`),ctx.warnings.push(`Quarantined ${residue.quarantined} stale atomic-write temp file(s) to .swarm/${residue.batchRelDir}/ (recoverable; rollback: /swarm config doctor --rollback-residue-quarantine).`);if(residue.preserved.length>0){let sample=residue.preserved.slice(0,5).map((p)=>`\`${p.relPath}\``).join(", ");ctx.warnings.push(`Preserved ${residue.preserved.length} residue candidate(s) in place (recent/active/tracked/ambiguous): ${sample}${residue.preserved.length>5?" …":""}.`)}}catch(err){let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Atomic-write residue quarantine failed (status of individual candidates unknown — inspect .swarm/quarantine/): ${reason}`)}for(let terminalFile of TERMINAL_STATE_FILES)try{if(await fs84.unlink(path135.join(ctx.swarmDir,terminalFile)),!cleanedFiles.includes(terminalFile))cleanedFiles.push(terminalFile)}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to remove terminal-state file ${terminalFile} [${errno??"unknown"}]: ${reason}`)}}clearAllScopes(ctx.directory);let contextPath=path135.join(ctx.swarmDir,"context.md"),contextContent=["# Context","","## Status",`Session closed after: ${ctx.projectName}`,`Closed: ${new Date().toISOString()}`,`Finalization: ${ctx.isForced?"forced":ctx.planAlreadyDone?"plan-already-done":"normal"}`,"No active plan. Next session starts fresh.",""].join(`
1389
1389
  `);try{await atomicWriteSwarmFile(contextPath,contextContent)}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to reset context.md: ${msg}`),log("[close-command] Failed to write context.md:",error93)}return{cleanedFiles,configBackupsRemoved,swarmPlanFilesRemoved,residueQuarantined,residuePreserved}}var init_clean_stage=__esm(()=>{init_group_commit_writer();init_project_db();init_knowledge_link();init_scope_persistence();init_swarm_residue();init_indexed_storage();init_atomic_write();init_logger();init_constants2();init_db_helpers();init_internals()});import*as fsSync15 from"node:fs";import{promises as fs85}from"node:fs";import path136 from"node:path";async function runFinalizeDryRun(directory,swarmDir,planData,planExists){let existsInSwarm=(name)=>fsSync15.existsSync(path136.join(swarmDir,name)),phases=planData.phases??[],nonTerminalPhases=phases.filter((p)=>p.status!=="complete"&&p.status!=="completed"&&p.status!=="blocked"&&p.status!=="closed"),planAlreadyDone=planExists&&phases.length>0&&nonTerminalPhases.length===0,wouldArchive=ARCHIVE_ARTIFACTS.filter(existsInSwarm),dynamicArchive=(await fs85.readdir(swarmDir).catch(()=>[])).filter((name)=>/^post-mortem-[^/\\]+\.md$/.test(name)||/^drift-report-phase-\d+\.json$/.test(name)),wouldArchiveDirs=ACTIVE_STATE_DIRS_TO_CLEAN.filter(existsInSwarm),wouldRemoveTerminal=TERMINAL_STATE_FILES.filter(existsInSwarm),wouldCleanFiles=ACTIVE_STATE_TO_CLEAN.filter((f)=>existsInSwarm(f)&&!TERMINAL_STATE_FILES.includes(f)),gitNote=_internals118.getGitRepositoryStatus(directory).isRepo?"would align the working tree to main/remote (git reset), pruning merged branches only with --prune-branches":"would skip git alignment (not a git repository / git unavailable)",residueSection=[];try{let residueInventory=await inventorySwarmResidue(directory);if(residueInventory.summary.matched>0)residueSection=["","### Atomic-write residue (read-only inventory)",...formatResidueInventoryLines(residueInventory),"- A real close run QUARANTINES eligible items into `.swarm/quarantine/` (recoverable, manifest-backed — never deleted); every other candidate is preserved in place."]}catch{}return["## /swarm finalize — DRY RUN (no changes made)","","No lock is taken, no files are archived or deleted, no git command runs.","","### Plan",planExists?planAlreadyDone?"- Plan is already terminal — no phases/tasks would be force-closed.":nonTerminalPhases.length>0?`- Would mark ${nonTerminalPhases.length} non-terminal phase(s) as closed: ${nonTerminalPhases.map((p)=>`#${p.id} ${p.name}`).join(", ")}`:"- No phases present; nothing to close.":"- No plan.json — plan-free session; cleanup-only.","","### Would archive",wouldArchive.length>0||dynamicArchive.length>0||wouldArchiveDirs.length>0?[...wouldArchive.map((f)=>`- ${f}`),...dynamicArchive.map((f)=>`- ${f}`),...wouldArchiveDirs.map((d)=>`- ${d}/`)].join(`
1390
1390
  `):"- (nothing present to archive)","","### Would clean (removed after successful archive)",wouldCleanFiles.length>0||wouldArchiveDirs.length>0?[...wouldCleanFiles.map((f)=>`- ${f}`),...wouldArchiveDirs.map((d)=>`- ${d}/`)].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-swarm",
3
- "version": "7.197.1",
3
+ "version": "7.197.3",
4
4
  "description": "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",