opencode-swarm 7.159.2 → 7.159.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 (61) hide show
  1. package/dist/cli/{coder-settlement-hny3vh3e.js → coder-settlement-50p7dsya.js} +6 -6
  2. package/dist/cli/{config-doctor-00ex0s3k.js → config-doctor-a7drgs33.js} +2 -2
  3. package/dist/cli/{core-03tedwzg.js → core-madqgdsc.js} +1 -1
  4. package/dist/cli/{curation-policy-z0a5akng.js → curation-policy-ray8h55z.js} +4 -4
  5. package/dist/cli/{curator-n81nzdw8.js → curator-3sz7refy.js} +27 -27
  6. package/dist/cli/{curator-llm-factory-24bfn7h1.js → curator-llm-factory-pyp5kmra.js} +27 -27
  7. package/dist/cli/{evidence-summary-service-nz7y1w2a.js → evidence-summary-service-cwyjkdsa.js} +9 -9
  8. package/dist/cli/{gate-evidence-dxafmzrn.js → gate-evidence-95k5ap1z.js} +4 -4
  9. package/dist/cli/{guardrail-explain-b3k9xrx9.js → guardrail-explain-a13kbmrt.js} +28 -28
  10. package/dist/cli/{guardrail-log-t8c7acxg.js → guardrail-log-nerqk9qb.js} +3 -3
  11. package/dist/cli/{guardrail-reset-0ft2gf03.js → guardrail-reset-chbc0mep.js} +27 -27
  12. package/dist/cli/{hive-promoter-brq9cx7c.js → hive-promoter-4rtxhw7n.js} +27 -27
  13. package/dist/cli/{index-egc8d995.js → index-2fq4a3vk.js} +1 -1
  14. package/dist/cli/{index-bmst1sje.js → index-2jzmg2km.js} +6 -6
  15. package/dist/cli/{index-wzc6vzq6.js → index-40t6s98s.js} +2 -2
  16. package/dist/cli/{index-6sheh3yp.js → index-515nwvdp.js} +1 -1
  17. package/dist/cli/{index-qypnqmcj.js → index-5hfqc3h3.js} +5 -5
  18. package/dist/cli/{index-e1jcdpdg.js → index-6jp5yxye.js} +1 -1
  19. package/dist/cli/{index-w1rhyqw2.js → index-8fyebh3w.js} +1 -1
  20. package/dist/cli/{index-nmp47dmm.js → index-8zw60wya.js} +1 -1
  21. package/dist/cli/{index-q8yma345.js → index-9qw4sbg1.js} +2 -2
  22. package/dist/cli/{index-v7wm4mw8.js → index-bxpqq9th.js} +1 -1
  23. package/dist/cli/{index-1xcve0gc.js → index-ebxmfr4j.js} +1 -1
  24. package/dist/cli/{index-b2dh37cf.js → index-fnxmg8sz.js} +5 -5
  25. package/dist/cli/{index-ky2r092m.js → index-gk6gpe7r.js} +1 -1
  26. package/dist/cli/{index-caqjwnak.js → index-h96xp4t0.js} +1 -1
  27. package/dist/cli/{index-m0gfzxw1.js → index-m9m3emns.js} +2 -2
  28. package/dist/cli/{index-8gh97gkz.js → index-mqfs5f8a.js} +1 -1
  29. package/dist/cli/{index-vq4d1h7t.js → index-nhhek8yw.js} +1 -1
  30. package/dist/cli/{index-rq461prn.js → index-nvz4mp5w.js} +4 -4
  31. package/dist/cli/{index-8ahjx7vt.js → index-p3ym3y8b.js} +4 -4
  32. package/dist/cli/{index-mcan50mx.js → index-qxpfmryw.js} +3 -3
  33. package/dist/cli/{index-eh1gh043.js → index-rq4jcw64.js} +2 -2
  34. package/dist/cli/{index-k7kvrwbj.js → index-sn6mtxxc.js} +29 -29
  35. package/dist/cli/{index-dgt8z19x.js → index-t3wk7q51.js} +1 -1
  36. package/dist/cli/{index-9ev0bbqh.js → index-txwx9p21.js} +61 -61
  37. package/dist/cli/{index-200myvdx.js → index-v3ybemb1.js} +2 -2
  38. package/dist/cli/{index-1e9rzhmr.js → index-ve0xj03m.js} +1 -1
  39. package/dist/cli/{index-7tjamatf.js → index-wwpe4am7.js} +4 -4
  40. package/dist/cli/{index-y55hqgcj.js → index-xqjhbfbx.js} +4 -4
  41. package/dist/cli/{index-jd7mz4yg.js → index-xs32znyz.js} +1 -1
  42. package/dist/cli/{index-p2m1skjz.js → index-y2d381ce.js} +1 -1
  43. package/dist/cli/{index-b5s1n149.js → index-zswy6xgb.js} +3 -3
  44. package/dist/cli/index.js +27 -27
  45. package/dist/cli/{knowledge-escalator-rxagfxnk.js → knowledge-escalator-f80n84ch.js} +9 -9
  46. package/dist/cli/{knowledge-events-ymwdv799.js → knowledge-events-1d7v2krw.js} +7 -7
  47. package/dist/cli/{knowledge-link-n1825n09.js → knowledge-link-vm4caewt.js} +3 -3
  48. package/dist/cli/{knowledge-store-nxm4xvvq.js → knowledge-store-66yxeet7.js} +4 -4
  49. package/dist/cli/{knowledge-validator-gtmq35k8.js → knowledge-validator-p0xcx7jx.js} +6 -6
  50. package/dist/cli/{pending-delegations-zdgazhdf.js → pending-delegations-vad1z71d.js} +1 -1
  51. package/dist/cli/{pr-review-reentry-authorization-jgzb0pma.js → pr-review-reentry-authorization-kn3nny7h.js} +27 -27
  52. package/dist/cli/{pr-subscriptions-pxv24d5k.js → pr-subscriptions-482gzvt6.js} +2 -2
  53. package/dist/cli/{runner-fzgkhx6a.js → runner-sn7a6zd0.js} +4 -4
  54. package/dist/cli/{scan-cursor-fasdj7kj.js → scan-cursor-2v7995nb.js} +5 -5
  55. package/dist/cli/{schema-3x28z3rp.js → schema-dy8fqycb.js} +1 -1
  56. package/dist/cli/{scope-persistence-p8dnxfhx.js → scope-persistence-baty62vx.js} +5 -5
  57. package/dist/cli/{skill-generator-6tjyffgd.js → skill-generator-nwrvtqbz.js} +11 -11
  58. package/dist/cli/{worktree-collision-ownership-3bbn1n2r.js → worktree-collision-ownership-cy24p5mr.js} +3 -3
  59. package/dist/cli/{worktree-isolation-1470tnxc.js → worktree-isolation-8jbx0s8d.js} +27 -27
  60. package/dist/index.js +3 -3
  61. 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.159.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/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/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","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","drift:check":"bun run scripts/drift-check.ts","schema:generate":"bun run scripts/generate-config-schema.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check: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:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},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, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},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"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},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) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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 corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",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"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.159.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"},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/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","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","drift:check":"bun run scripts/drift-check.ts","schema:generate":"bun run scripts/generate-config-schema.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check: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:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},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, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},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"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},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) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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 corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",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"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -211,7 +211,7 @@ ${lines[i]}`),framingChecked=!0}else{let prefix=!framingChecked&&!fileEndsWithNe
211
211
  `)){if(line.trim()==="")continue;try{let parsed=JSON.parse(line);if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)&&predicate(parsed))matches.push(parsed)}catch{}}return matches}function selfHealAuthorityKeys(directory,keys){try{let state=loadAuthorityIndex(directory);if(state.kind==="corrupt")return;mergeAuthorityKeys(directory,state,keys)}catch{}}function getCoderRetryEscalationActions(directory,taskId,retryEpoch){let actions=new Set,prefix=`retry|${taskId}|${retryEpoch}|`,state=loadAuthorityIndex(directory);if(state.kind==="corrupt")throw Error("CORE_EVENT_AUTHORITY_INDEX_UNREADABLE");let heal=[];if(state.kind==="ok"){for(let key of Object.keys(state.index.entries))if(key.startsWith(prefix)){let action=key.slice(prefix.length);if(RETRY_ACTIONS.has(action))actions.add(action)}}for(let event of scanWindowFor(directory,(e)=>e.type===AUTHORITY_RETRY&&e.taskId===taskId&&e.retryEpoch===retryEpoch&&typeof e.action==="string"&&RETRY_ACTIONS.has(e.action))){let action=event.action;if(!actions.has(action)){actions.add(action);let key=authorityKeyFor(event);if(key)heal.push(key)}}if(heal.length>0)selfHealAuthorityKeys(directory,heal);return actions}function hasAuthorityEvent(directory,key,predicate){let state=loadAuthorityIndex(directory);if(state.kind==="corrupt")throw Error("CORE_EVENT_AUTHORITY_INDEX_UNREADABLE");if(state.kind==="ok"&&state.index.entries[key]!==void 0)return!0;if(scanWindowFor(directory,predicate).length>0)return selfHealAuthorityKeys(directory,[key]),!0;return!1}function hasSpecDriftAuditEvent(directory,kind,transitionId){return hasAuthorityEvent(directory,`drift|${kind}|${transitionId}`,(e)=>e.type===kind&&e.transitionId===transitionId)}function hasTaskRepairAuditEvent(directory,taskId,transitionId){return hasAuthorityEvent(directory,`repair|${taskId}|${transitionId}`,(e)=>e.type===AUTHORITY_REPAIR&&e.taskId===taskId&&e.transitionId===transitionId)}function foldPass(directory,trigger,forceFull,preloadedAuthorityState){let filePath=eventsFilePath(directory);if(!_internals12.existsSync(filePath))return;let view=readStoreFull(directory);if(view.manifest===null&&view.lines.length===0)return;let folded=view.manifest?cloneFolded(view.manifest.folded):emptyFolded(),now=_internals12.now(),agePruned=[],kept=[];for(let entry of view.lines){if(entry.event===null){agePruned.push(entry);continue}if(authorityKeyFor(entry.event)!==null){kept.push(entry);continue}let ts=eventTimestamp(entry.event);if(ts!==null&&now-Date.parse(ts)>_internals12.limits.ageMaxMs)agePruned.push(entry);else kept.push(entry)}let retained=[],bytes=Buffer.byteLength(JSON.stringify(view.manifest??emptyManifest()));for(let i=kept.length-1;i>=0;i-=1){let entry=kept[i],lineBytes=Buffer.byteLength(entry.line)+1;if(retained.length>=_internals12.limits.activeMaxEntries||bytes+lineBytes>_internals12.limits.activeMaxBytes)break;retained.push(entry),bytes+=lineBytes}retained.reverse();let retainedSet=new Set(retained),candidates=[];for(let entry of view.lines)if(entry.event===null)candidates.push(entry);else if(!retainedSet.has(entry))candidates.push(entry);let toFold=new Set,foldedBytes=0;for(let cand of candidates){let cb=Buffer.byteLength(cand.line)+1;if(!forceFull&&foldedBytes+cb>_internals12.limits.compactMaxBytes&&toFold.size>0)break;toFold.add(cand),foldedBytes+=cb}let indexKeys=[];for(let cand of toFold)if(cand.event!==null){let key=authorityKeyFor(cand.event);if(key)indexKeys.push(key)}if(indexKeys.length>0)mergeAuthorityKeys(directory,loadAuthorityIndex(directory),indexKeys);let agePrunedSet=new Set(agePruned),dropped=0;for(let cand of toFold)if(cand.event===null)folded.corrupt+=1;else if(foldLineInto(folded,cand.event),agePrunedSet.has(cand))dropped+=1;folded.dropped+=dropped,folded.corrupt+=view.corruptLines;let finalRetained=[];for(let entry of view.lines)if(!toFold.has(entry))finalRetained.push(entry);let manifest={...emptyManifest(),folded,updatedAt:new Date().toISOString()},outLines=[`${JSON.stringify(manifest)}`];for(let entry of finalRetained)outLines.push(entry.line);atomicReplace(directory,outLines.length>1?`${outLines.join(`
212
212
  `)}
213
213
  `:`${outLines[0]}
214
- `),emitHealth(directory,{trigger,accepted:folded.totalEvents+finalRetained.length,compacted:toFold.size-dropped,retained:finalRetained.length,dropped,corrupt:folded.corrupt,oldest:folded.oldestTimestamp,newest:folded.newestTimestamp,bytes:fileSizeOrZero(filePath),limitBytes:_internals12.limits.activeMaxBytes},preloadedAuthorityState)}function runMaintenance(directory){try{let filePath=eventsFilePath(directory);if(!_internals12.existsSync(filePath))return;let drainThreshold=_internals12.limits.activeMaxBytes+_internals12.limits.headerMaxBytes+2048;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory);foldPass(directory,"compaction",!1,authorityState);let prevSize=Number.POSITIVE_INFINITY;for(let pass=0;pass<64;pass+=1){let size=fileSizeOrZero(filePath);if(size<=drainThreshold)break;if(size>=prevSize)break;prevSize=size,foldPass(directory,"compaction",!1,authorityState)}return!0})}catch{warnThrottled("maintenance pass failed")}}function finalizeCoreEventsForClose(directory){try{let filePath=eventsFilePath(directory);if(!_internals12.existsSync(filePath))return;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory),prev=Number.POSITIVE_INFINITY;for(let pass=0;pass<1e4;pass+=1){let view=readStoreFull(directory);if(view.manifest!==null)break;if(view.lines.length===0)break;if(view.lines.length>=prev)break;prev=view.lines.length,foldPass(directory,"close",!1,authorityState)}return foldPass(directory,"close",!0,authorityState),!0})}catch{warnThrottled("finalize failed")}}function emitCoreEventsHealth(directory,payload,preloadedAuthorityState){let authorityCount=0,authorityEvicted=0,state=preloadedAuthorityState??loadAuthorityIndex(directory);if(state.kind==="ok")authorityCount=Object.keys(state.index.entries).length,authorityEvicted=state.index.evicted;try{telemetry.coreEventsHealth({trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,authority_index_count:authorityCount,authority_evicted_count:authorityEvicted,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes})}catch{}}function emitHealth(directory,payload,preloadedAuthorityState){_internals12.emitHealth(directory,payload,preloadedAuthorityState)}var CORE_EVENT_LIMITS,AUTHORITY_RETRY="coder_retry_circuit_breaker",AUTHORITY_REPAIR="task_workflow_repaired",AUTHORITY_DRIFT_ACK="spec_drift_acknowledged",AUTHORITY_DRIFT_REPAIR="spec_drift_repaired",PUBLICATION_LIVE_EVENT_TYPES,PUBLICATION_TERMINAL_EVENT_TYPES,RETRY_ACTIONS,MANIFEST_TYPE="swarm-events-manifest",MANIFEST_SCHEMA=1,BY_TYPE_MAX_KEYS=64,BY_TYPE_OTHER="__other__",_internals12,LOCK_RETRY_ATTEMPTS=20,LOCK_RETRY_DELAY_MS=5,LOCK_STALE_MS=300000,sleepScratch,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_appendCount=0,_lastWarnAt=0,CORE_EVENT_LOCKED="CORE_EVENT_STORE_LOCKED",CORE_EVENT_LINE_TOO_LARGE="CORE_EVENT_LINE_TOO_LARGE",CORE_EVENT_NO_STORE="CORE_EVENT_NO_STORE";var init_core_events=__esm(()=>{init_telemetry();init_logger();CORE_EVENT_LIMITS={activeMaxBytes:2097152,activeMaxEntries:20000,ageMaxMs:604800000,compactMaxBytes:524288,readMaxBytes:3145728,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:65536,authorityIndexMaxEntries:20000,maxLineBytes:262144},PUBLICATION_LIVE_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started"]),PUBLICATION_TERMINAL_EVENT_TYPES=new Set(["pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]),RETRY_ACTIONS=new Set(["sounding_board_consultation","simplification","user_escalation"]);_internals12={appendFileSync:fs10.appendFileSync,readFileSync:fs10.readFileSync,existsSync:fs10.existsSync,mkdirSync:fs10.mkdirSync,statSync:fs10.statSync,renameSync:fs10.renameSync,writeFileSync:fs10.writeFileSync,unlinkSync:fs10.unlinkSync,openSync:fs10.openSync,closeSync:fs10.closeSync,readSync:fs10.readSync,now:()=>Date.now(),limits:CORE_EVENT_LIMITS,emitHealth:emitCoreEventsHealth};sleepScratch=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"])});import{randomBytes as randomBytes2}from"node:crypto";import*as fs11 from"node:fs";import*as path16 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path16.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs11.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path16.normalize(path16.resolve(targetPath)),segments=resolved.split(path16.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path16.sep);try{let st=fs11.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path16.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path16.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path16.sep)){if(probe=path16.join(probe,seg),!fs11.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path16.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep2(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS2.length;attempt++)try{_internals13.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES2.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS2.length)syncSleep2(RENAME_RETRY_DELAYS_MS2[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path16.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals13.randomSuffix()}.tmp`;fs11.mkdirSync(path16.dirname(tempPath),{recursive:!0});try{let fd=fs11.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals13.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals13.fsyncSync(fd)}catch{}}finally{fs11.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals13.unlinkSync(tempPath)}catch{}}try{let dirFd=fs11.openSync(path16.dirname(resolvedTarget),"r");try{fs11.fsyncSync(dirFd)}finally{fs11.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve10)=>setImmediate(resolve10)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve10)=>setImmediate(resolve10)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_internals13;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:250"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:17944"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:629","src/plan/manager.ts:1785","src/plan/manager.ts:1831","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:197","src/tools/repo-graph/storage.ts:493","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1070","src/background/delegation-health.ts:390","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:140","src/tools/write-pr-review-artifact.ts:160","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1971","src/plan/manager.ts:2160"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:109","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:1145","src/hooks/skill-usage-log.ts:1650","src/hooks/skill-usage-pending.ts:816","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/pr-review-reentry-authorization.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals13={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs11.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs11.renameSync(from,to),unlinkSync:(p)=>fs11.unlinkSync(p),fsyncSync:(fd)=>fs11.fsyncSync(fd)}});import*as path17 from"node:path";function taskEvidenceRelPath(taskId){return path17.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path17.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash7}from"node:crypto";import*as fs12 from"node:fs";import*as path18 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path18.resolve(value).toLowerCase():path18.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs12.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs12.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path18.join(current,segment);let info;try{info=fs12.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs12.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs12.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs12.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path18.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash7("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs12.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs12.openSync(filePath,fs12.constants.O_RDONLY|(fs12.constants.O_NOFOLLOW??0));try{let openedStat=fs12.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs12.readFileSync(descriptor,"utf-8")}finally{fs12.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
214
+ `),emitHealth(directory,{trigger,accepted:folded.totalEvents+finalRetained.length,compacted:toFold.size-dropped,retained:finalRetained.length,dropped,corrupt:folded.corrupt,oldest:folded.oldestTimestamp,newest:folded.newestTimestamp,bytes:fileSizeOrZero(filePath),limitBytes:_internals12.limits.activeMaxBytes},preloadedAuthorityState)}function runMaintenance(directory){try{let filePath=eventsFilePath(directory);if(!_internals12.existsSync(filePath))return;let drainThreshold=_internals12.limits.activeMaxBytes+_internals12.limits.headerMaxBytes+2048;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory);foldPass(directory,"compaction",!1,authorityState);let prevSize=Number.POSITIVE_INFINITY;for(let pass=0;pass<64;pass+=1){let size=fileSizeOrZero(filePath);if(size<=drainThreshold)break;if(size>=prevSize)break;prevSize=size,foldPass(directory,"compaction",!1,authorityState)}return!0})}catch{warnThrottled("maintenance pass failed")}}function finalizeCoreEventsForClose(directory){try{let filePath=eventsFilePath(directory);if(!_internals12.existsSync(filePath))return;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory),prev=Number.POSITIVE_INFINITY;for(let pass=0;pass<1e4;pass+=1){let view=readStoreFull(directory);if(view.manifest!==null)break;if(view.lines.length===0)break;if(view.lines.length>=prev)break;prev=view.lines.length,foldPass(directory,"close",!1,authorityState)}return foldPass(directory,"close",!0,authorityState),!0})}catch{warnThrottled("finalize failed")}}function emitCoreEventsHealth(directory,payload,preloadedAuthorityState){let authorityCount=0,authorityEvicted=0,state=preloadedAuthorityState??loadAuthorityIndex(directory);if(state.kind==="ok")authorityCount=Object.keys(state.index.entries).length,authorityEvicted=state.index.evicted;try{telemetry.coreEventsHealth({trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,authority_index_count:authorityCount,authority_evicted_count:authorityEvicted,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes})}catch{}}function emitHealth(directory,payload,preloadedAuthorityState){_internals12.emitHealth(directory,payload,preloadedAuthorityState)}var CORE_EVENT_LIMITS,AUTHORITY_RETRY="coder_retry_circuit_breaker",AUTHORITY_REPAIR="task_workflow_repaired",AUTHORITY_DRIFT_ACK="spec_drift_acknowledged",AUTHORITY_DRIFT_REPAIR="spec_drift_repaired",PUBLICATION_LIVE_EVENT_TYPES,PUBLICATION_TERMINAL_EVENT_TYPES,RETRY_ACTIONS,MANIFEST_TYPE="swarm-events-manifest",MANIFEST_SCHEMA=1,BY_TYPE_MAX_KEYS=64,BY_TYPE_OTHER="__other__",_internals12,LOCK_RETRY_ATTEMPTS=20,LOCK_RETRY_DELAY_MS=5,LOCK_STALE_MS=300000,sleepScratch,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_appendCount=0,_lastWarnAt=0,CORE_EVENT_LOCKED="CORE_EVENT_STORE_LOCKED",CORE_EVENT_LINE_TOO_LARGE="CORE_EVENT_LINE_TOO_LARGE",CORE_EVENT_NO_STORE="CORE_EVENT_NO_STORE";var init_core_events=__esm(()=>{init_telemetry();init_logger();CORE_EVENT_LIMITS={activeMaxBytes:2097152,activeMaxEntries:20000,ageMaxMs:604800000,compactMaxBytes:524288,readMaxBytes:3145728,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:65536,authorityIndexMaxEntries:20000,maxLineBytes:262144},PUBLICATION_LIVE_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started"]),PUBLICATION_TERMINAL_EVENT_TYPES=new Set(["pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]),RETRY_ACTIONS=new Set(["sounding_board_consultation","simplification","user_escalation"]);_internals12={appendFileSync:fs10.appendFileSync,readFileSync:fs10.readFileSync,existsSync:fs10.existsSync,mkdirSync:fs10.mkdirSync,statSync:fs10.statSync,renameSync:fs10.renameSync,writeFileSync:fs10.writeFileSync,unlinkSync:fs10.unlinkSync,openSync:fs10.openSync,closeSync:fs10.closeSync,readSync:fs10.readSync,now:()=>Date.now(),limits:CORE_EVENT_LIMITS,emitHealth:emitCoreEventsHealth};sleepScratch=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"])});import{randomBytes as randomBytes2}from"node:crypto";import*as fs11 from"node:fs";import*as path16 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path16.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs11.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path16.normalize(path16.resolve(targetPath)),segments=resolved.split(path16.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path16.sep);try{let st=fs11.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path16.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path16.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path16.sep)){if(probe=path16.join(probe,seg),!fs11.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path16.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep2(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS2.length;attempt++)try{_internals13.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES2.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS2.length)syncSleep2(RENAME_RETRY_DELAYS_MS2[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path16.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals13.randomSuffix()}.tmp`;fs11.mkdirSync(path16.dirname(tempPath),{recursive:!0});try{let fd=fs11.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals13.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals13.fsyncSync(fd)}catch{}}finally{fs11.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals13.unlinkSync(tempPath)}catch{}}try{let dirFd=fs11.openSync(path16.dirname(resolvedTarget),"r");try{fs11.fsyncSync(dirFd)}finally{fs11.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve10)=>setImmediate(resolve10)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve10)=>setImmediate(resolve10)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_internals13;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:250"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:17944"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:629","src/plan/manager.ts:1785","src/plan/manager.ts:1831","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:197","src/tools/repo-graph/storage.ts:493","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1070","src/background/delegation-health.ts:390","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:140","src/tools/write-pr-review-artifact.ts:160","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1971","src/plan/manager.ts:2160"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:109","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1670","src/hooks/skill-usage-pending.ts:816","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/pr-review-reentry-authorization.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals13={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs11.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs11.renameSync(from,to),unlinkSync:(p)=>fs11.unlinkSync(p),fsyncSync:(fd)=>fs11.fsyncSync(fd)}});import*as path17 from"node:path";function taskEvidenceRelPath(taskId){return path17.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path17.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash7}from"node:crypto";import*as fs12 from"node:fs";import*as path18 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path18.resolve(value).toLowerCase():path18.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs12.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs12.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path18.join(current,segment);let info;try{info=fs12.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs12.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs12.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs12.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path18.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash7("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs12.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs12.openSync(filePath,fs12.constants.O_RDONLY|(fs12.constants.O_NOFOLLOW??0));try{let openedStat=fs12.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs12.readFileSync(descriptor,"utf-8")}finally{fs12.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
215
215
  `)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function deriveReceiptRole(event){switch(event.type){case"accepted_mutation":case"dispatch_attempted":case"dispatch_no_mutation":if(typeof event.agentType==="string"&&event.agentType.trim().length>0)return{normalizedRole:event.agentType.trim(),testEngineerExempt:event.agentType==="coder"?event.context?.testEngineerExempt===!0:null};return null;case"stage_b_completed":case"gate_recorded":return{normalizedRole:event.gate,testEngineerExempt:null};default:return null}}function shouldAppendReceipt(current,next,role){if(next.required_gates.length===0)return!1;let currentGeneration=current?.workflow?.generation??-1,nextGeneration=next.workflow?.generation??-1;if(current===null)return!0;if(JSON.stringify(current.required_gates)!==JSON.stringify(next.required_gates))return!0;if((current.test_engineer_exempt??null)!==role.testEngineerExempt)return!0;return currentGeneration!==nextGeneration}async function appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,next,event){let role=deriveReceiptRole(event);if(!role||!shouldAppendReceipt(current,next,role))return;let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!0),receipts=await readTaskGateRequirementsReceipts(directory,taskId),latest=receipts.at(-1),baseReceipt={schemaVersion:1,taskId,generation:next.workflow?.generation??0,normalizedRole:role.normalizedRole,testEngineerExempt:role.testEngineerExempt,requiredGates:[...next.required_gates],sourceEvent:event.type,sourceTransitionId:event.transitionId??null,recordedAt:new Date().toISOString(),previousChainHash:latest?.chainHash??null},receipt={...baseReceipt,chainHash:computeChainHash(baseReceipt)};if(latest&&latest.generation===receipt.generation&&latest.normalizedRole===receipt.normalizedRole&&latest.testEngineerExempt===receipt.testEngineerExempt&&JSON.stringify(latest.requiredGates)===JSON.stringify(receipt.requiredGates)&&latest.sourceTransitionId===receipt.sourceTransitionId)return;let lines=[...receipts,receipt].map((entry)=>JSON.stringify(entry));assertSafeRequirementsParent(directory,!1),await atomicWriteFile(filePath,`${lines.join(`
216
216
  `)}
217
217
  `),assertSafeRequirementsParent(directory,!1)}var MAX_TASK_GATE_REQUIREMENTS_BYTES=262144,TaskGateRequirementsReceiptSchema;var init_task_gate_requirements=__esm(()=>{init_zod();init_utils2();init_project_boundary();init_task_file();TaskGateRequirementsReceiptSchema=exports_external.object({schemaVersion:exports_external.literal(1),taskId:exports_external.string().min(1).max(120),generation:exports_external.number().int().min(0),normalizedRole:exports_external.string().min(1).max(120),testEngineerExempt:exports_external.boolean().nullable(),requiredGates:exports_external.array(exports_external.string()).min(1).max(16),sourceEvent:exports_external.string().min(1).max(120),sourceTransitionId:exports_external.string().min(1).max(200).nullable(),recordedAt:exports_external.string().min(1).max(128),previousChainHash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),chainHash:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});function checkUnsafeChars(taskId){if(!taskId||taskId.length===0)return"Invalid task ID: empty string";if(/\0/.test(taskId))return"Invalid task ID: contains null bytes";for(let i=0;i<taskId.length;i++)if(taskId.charCodeAt(i)<32)return"Invalid task ID: contains control characters";if(taskId.includes("..")||taskId.includes("/")||taskId.includes("\\"))return"Invalid task ID: path traversal detected";return}function isStrictTaskId(taskId){if(!taskId)return!1;if(checkUnsafeChars(taskId))return!1;return STRICT_TASK_ID_PATTERN.test(taskId)}function assertStrictTaskId(taskId){if(!isStrictTaskId(taskId))throw Error(`Invalid taskId: "${taskId}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3").`)}function sanitizeTaskId(taskId){let unsafeMsg=checkUnsafeChars(taskId);if(unsafeMsg)throw Error(unsafeMsg);if(STRICT_TASK_ID_PATTERN.test(taskId)||RETRO_TASK_ID_REGEX.test(taskId)||INTERNAL_TOOL_ID_REGEX.test(taskId)||GENERAL_TASK_ID_REGEX.test(taskId))return taskId;throw Error(`Invalid task ID: must be alphanumeric (ASCII) with optional hyphens, underscores, or dots, got "${taskId}"`)}function validateTaskIdFormat(taskId){if(!STRICT_TASK_ID_PATTERN.test(taskId))return`Invalid taskId "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}var STRICT_TASK_ID_PATTERN,RETRO_TASK_ID_REGEX,INTERNAL_TOOL_ID_REGEX,GENERAL_TASK_ID_REGEX;var init_task_id=__esm(()=>{STRICT_TASK_ID_PATTERN=/^\d+\.\d+(\.\d+)*$/,RETRO_TASK_ID_REGEX=/^retro-\d+$/,INTERNAL_TOOL_ID_REGEX=/^(?:sast_scan|quality_budget|syntax_check|placeholder_scan|sbom_generate|build|secretscan)$/,GENERAL_TASK_ID_REGEX=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/});import*as path19 from"node:path";function isControlCharacter(character){let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159}function isBidiControlCharacter(character){return BIDI_CONTROL_CHARACTERS.test(character)}function getPathFlavor(pathLib=path19){return pathLib.sep==="\\"?"win32":"posix"}function pathImplementation(flavor){return flavor==="win32"?path19.win32:path19.posix}function normalizePathIdentity(value,flavor=getPathFlavor()){let normalized=pathImplementation(flavor).normalize(flavor==="win32"?value.replace(/\//g,"\\"):value);return flavor==="win32"?normalized.toLowerCase():normalized}function pathIdentitiesEqual(a,b,flavor=getPathFlavor()){return normalizePathIdentity(a,flavor)===normalizePathIdentity(b,flavor)}function isPathIdentityWithin(target,container,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetIdentity=normalizePathIdentity(target,flavor),containerIdentity=normalizePathIdentity(container,flavor);if(targetIdentity===containerIdentity)return!0;let relative5=pathImpl.relative(containerIdentity,targetIdentity);return relative5.length>0&&relative5!==".."&&!relative5.startsWith(`..${pathImpl.sep}`)&&!pathImpl.isAbsolute(relative5)}function isPathWithinDeclaredScope(filePath,scopeEntries,cwd=process.cwd(),flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),resolvedFile=pathImpl.resolve(cwd,filePath);return scopeEntries.some((scope)=>isPathIdentityWithin(resolvedFile,pathImpl.resolve(cwd,scope),flavor))}function isOnDifferentPathRoot(target,cwd,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetRoot=pathImpl.parse(pathImpl.normalize(target)).root,cwdRoot=pathImpl.parse(pathImpl.normalize(cwd)).root;return!pathIdentitiesEqual(targetRoot,cwdRoot,flavor)}function unsafePathTextReason(value){if([...value].some(isControlCharacter))return"control characters are not allowed in paths";if([...value].some(isBidiControlCharacter))return"bidirectional control characters are not allowed in paths";return null}function sanitizeDiagnosticText(value,maxLength=256){let rendered=String(value).split("").map((character)=>isControlCharacter(character)||isBidiControlCharacter(character)?"?":character).join("").replace(/\s+/gu," ").trim();if(rendered.length<=maxLength)return rendered;return`${rendered.slice(0,Math.max(0,maxLength-1))}…`}var BIDI_CONTROL_CHARACTERS;var init_path_identity=__esm(()=>{BIDI_CONTROL_CHARACTERS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u});import*as fs13 from"node:fs";import*as path20 from"node:path";function recoveryDir(directory){return path20.join(directory,".swarm",RECOVERY_DIR_NAME)}function recordPath(directory,sessionId,laneId){let safeSession=sessionId.replace(/[^a-zA-Z0-9._-]/g,"_"),safeLane=laneId.replace(/[^a-zA-Z0-9._-]/g,"_");return path20.join(recoveryDir(directory),`${safeSession}-${safeLane}.json`)}function isRecoveryRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return!1;let record2=value,validStatus=record2.status==="failed"||record2.status==="partial"||record2.status==="conflict";return typeof record2.laneId==="string"&&typeof record2.sessionId==="string"&&typeof record2.worktreePath==="string"&&validStatus&&typeof record2.reason==="string"&&typeof record2.recordedAt==="number"&&Number.isFinite(record2.recordedAt)&&typeof record2.replayHint==="string"&&(record2.branchName===void 0||typeof record2.branchName==="string")&&(record2.conflictFiles===void 0||Array.isArray(record2.conflictFiles)&&record2.conflictFiles.every((file2)=>typeof file2==="string"))}function readRecoveryRecords(directory){let dir=recoveryDir(directory),entries;try{entries=fs13.readdirSync(dir,{withFileTypes:!0})}catch{return{records:[],errored:fs13.existsSync(dir)}}let records=[],errored=!1;for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let full=path20.join(dir,entry.name);try{let parsed=JSON.parse(fs13.readFileSync(full,"utf-8"));if(isRecoveryRecord(parsed))records.push(parsed);else errored=!0}catch{errored=!0}}return{records,errored}}function writeRecoveryRecord(directory,record2){try{let dir=recoveryDir(directory);fs13.mkdirSync(dir,{recursive:!0});let filePath=recordPath(directory,record2.sessionId,record2.laneId),payload={...record2,recordedAt:record2.recordedAt??Date.now()},tmpPath=`${filePath}.tmp.${Date.now()}`;fs13.writeFileSync(tmpPath,JSON.stringify(payload,null,2),"utf-8"),fs13.renameSync(tmpPath,filePath)}catch{}}function listRecoveryRecords(directory){return readRecoveryRecords(directory).records}function hasRecoveryRecordForBranch(directory,branchName){return listRecoveryRecords(directory).some((r)=>r.branchName===branchName)}function clearRecoveryRecord(directory,laneId,sessionId){try{let filePath=recordPath(directory,sessionId,laneId);if(fs13.existsSync(filePath))fs13.unlinkSync(filePath)}catch{}}function recoveryReadErrored(directory){return readRecoveryRecords(directory).errored}var RECOVERY_DIR_NAME="recovery";var init_recovery=()=>{};function isGitBinaryMissing(err,cwd){return classifySpawnFailure(err,cwd)==="binary-missing"}function isSpawnCwdMissing(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-missing"}function isSpawnCwdUnreadable(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-unreadable"}var GitUnavailableError,GitBinaryMissingError,GitSpawnCwdError;var init_git_binary_missing_error=__esm(()=>{init_bun_compat();init_bun_compat();GitUnavailableError=class GitUnavailableError extends Error{};GitBinaryMissingError=class GitBinaryMissingError extends GitUnavailableError{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}};GitSpawnCwdError=class GitSpawnCwdError extends GitUnavailableError{name="GitSpawnCwdError";cwd;fault;constructor(cwd,fault,options){super(fault==="missing"?`git could not start: working directory no longer exists: ${cwd}`:`git could not start: working directory could not be inspected (permission denied): ${cwd}`,options);this.cwd=cwd,this.fault=fault}}});function isSwarmSessionId(sessionId){return typeof sessionId==="string"&&SESSION_ID_PATTERN.test(sessionId)}function isPlainSegment(segment){return typeof segment==="string"&&segment.length>0&&segment!=="."&&segment!==".."}function buildSwarmBranchName(sessionId,id,purpose,legacyLane){let[standardPrefix,legacyLanePrefix]=SWARM_WORKTREE_BRANCH_PREFIXES;return legacyLane?`${legacyLanePrefix}${sessionId}/${id}`:`${standardPrefix}${purpose}/${sessionId}/${id}`}function matchSwarmLanePath(lanePath){if(typeof lanePath!=="string"||lanePath==="")return;let segments=lanePath.split(/[\\/]+/).filter((s)=>s.length>0);if(segments.length<3)return;let[base,sessionId,id]=segments.slice(-3);if(!(process.platform==="win32"?base.toLowerCase()===SWARM_WORKTREE_DIR_NAME.toLowerCase():base===SWARM_WORKTREE_DIR_NAME))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{sessionId,id}}function matchSwarmLaneBranch(branch){if(typeof branch!=="string"||branch==="")return;let segments=branch.split("/");if(segments[0]==="swarm-lane"){if(segments.length!==3)return;let[,sessionId,id]=segments;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose:"lane",sessionId,id,style:"legacy-lane"}}if(segments[0]==="swarm"){if(segments.length!==4)return;let[,purpose,sessionId,id]=segments;if(!isPlainSegment(purpose))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose,sessionId,id,style:"purpose"}}return}var SWARM_WORKTREE_BRANCH_PREFIXES,SESSION_ID_PATTERN;var init_swarm_branch=__esm(()=>{init_constants();SWARM_WORKTREE_BRANCH_PREFIXES=["swarm/","swarm-lane/"],SESSION_ID_PATTERN=/^ses_[A-Za-z0-9]+$/});import{createHash as createHash8}from"node:crypto";function derivePlanId(plan){return`${plan.swarm}-${plan.title}`.replace(/[^a-zA-Z0-9-_]/g,"_")}function derivePlanIdentityHash(plan){return createHash8("sha256").update(JSON.stringify([plan.swarm,plan.title]),"utf8").digest("hex")}var init_utils3=()=>{};import*as crypto3 from"node:crypto";import*as fs14 from"node:fs";import*as path21 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path21.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path21.join(directory,".swarm",PLAN_JSON_FILENAME)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs14.openSync(tempPath,"w");try{fs14.writeFileSync(fd,data,"utf8"),fs14.fsyncSync(fd)}finally{fs14.closeSync(fd)}fs14.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs14.openSync(directory,"r"),fs14.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs14.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function computePlanHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs14.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs14.existsSync(ledgerPath)}async function getLatestLedgerSeq(directory){let ledgerPath=getLedgerPath(directory);if(!fs14.existsSync(ledgerPath))return 0;try{let lines=fs14.readFileSync(ledgerPath,"utf8").trim().split(`
@@ -634,7 +634,7 @@ ACTION: ${correction.action}`}var GUIDANCE_TEMPLATES,ACTION_TEMPLATES;var init_c
634
634
  `);return{text:firstNewline>=0?content.slice(firstNewline+1):"",truncated:!0}}finally{_internals49.closeSync(fd)}}catch{return{text:"",truncated:!0}}}function parseEntriesFromText(text){let entries=[];for(let line of text.split(`
635
635
  `)){let trimmed=line.trim();if(!trimmed)continue;try{let entry=parseSkillUsageEntry(JSON.parse(trimmed));if(entry)entries.push(entry)}catch{}}return entries}function filterEntries(entries,options){if(!options)return entries;return entries.filter((e)=>{if(options.sessionID!==void 0&&e.sessionID!==options.sessionID)return!1;if(options.skillPath!==void 0&&e.skillPath!==options.skillPath)return!1;if(options.agentName!==void 0&&e.agentName!==options.agentName)return!1;if(options.taskID!==void 0&&e.taskID!==options.taskID)return!1;if(options.dateRange!==void 0){if(e.timestamp<options.dateRange.start)return!1;if(e.timestamp>options.dateRange.end)return!1}return!0})}function readSkillUsageEntriesWithCoverage(directory,options){let slice=readLogSlice(directory),entries=filterEntries(parseEntriesFromText(slice.text),options),manifest=readPendingManifest(directory).coverage;return{entries,coverage:{...manifest,truncatedRead:slice.truncated,complete:manifest.complete&&!slice.truncated}}}function readSkillUsageEntries(directory,options){return readSkillUsageEntriesWithCoverage(directory,options).entries}function readSkillUsageEntriesTail(directory,filters,maxBytes=TAIL_BYTES_DEFAULT){let logPath=resolveLogPath(directory);if(!_internals49.existsSync(logPath))return[];try{let normalizedMaxBytes=Number.isFinite(maxBytes)?maxBytes:TAIL_BYTES_DEFAULT,boundedMaxBytes=Math.min(Math.max(1,normalizedMaxBytes),MAX_TAIL_BYTES),stat8=_internals49.statSync(logPath),start=Math.max(0,stat8.size-boundedMaxBytes),fd=_internals49.openSync(logPath,"r");try{let readLen=stat8.size-start;if(readLen===0)return[];let buf=Buffer.alloc(readLen);_internals49.readSync(fd,buf,0,buf.length,start);let content=buf.toString("utf-8"),usable;if(start>0){let firstNewline=content.indexOf(`
636
636
  `);usable=firstNewline>=0?content.slice(firstNewline+1):""}else usable=content;let entries=[];for(let line of usable.split(`
637
- `)){if(!line.trim())continue;try{let entry=parseSkillUsageEntry(JSON.parse(line));if(!entry)continue;if(filters.sessionID!==void 0&&entry.sessionID!==filters.sessionID)continue;entries.push(entry)}catch{}}return entries}finally{_internals49.closeSync(fd)}}catch{return[]}}function computeComplianceByVersion(entries,skillPath){let map2=new Map,normalizedTarget=skillPath.replace(/^file:/,"").replace(/\\/g,"/");for(let e of entries){let p=e.skillPath;if(p.startsWith("file:"))p=p.slice(5);let normalized=p.replace(/\\/g,"/");if(normalized!==normalizedTarget&&!normalizedTarget.endsWith(`/${normalized}`)&&!normalized.endsWith(`/${normalizedTarget}`))continue;let version2=e.skillVersion,stats2=map2.get(version2);if(!stats2)stats2={compliant:0,violation:0,total:0,rate:0},map2.set(version2,stats2);if(stats2.total+=1,e.complianceVerdict==="compliant")stats2.compliant+=1;if(normalizeComplianceVerdict(e.complianceVerdict)==="violated")stats2.violation+=1}for(let stats2 of map2.values())stats2.rate=stats2.total===0?0:stats2.compliant/stats2.total;return map2}function canonicalSkillPath(skillPath){return(skillPath.startsWith("file:")?skillPath.slice(5):skillPath).replace(/\\/g,"/")}function retentionKey(skillPath){return canonicalSkillPath(skillPath)}function compareNewestFirst(a,b){if(a.timestamp!==b.timestamp)return a.timestamp<b.timestamp?1:-1;if(a.id!==b.id)return a.id<b.id?-1:1;return 0}function compareOldestFirst(a,b){if(a.timestamp!==b.timestamp)return a.timestamp<b.timestamp?-1:1;if(a.id!==b.id)return a.id<b.id?-1:1;return 0}function applyRetention(entries,maxEntriesPerSkill){let total=entries.length;if(total===0)return{kept:[],dropped:0,skillsDropped:0};let newestMs=Number.NEGATIVE_INFINITY;for(let entry of entries){let ms=Date.parse(entry.timestamp);if(!Number.isNaN(ms)&&ms>newestMs)newestMs=ms}let aged=entries;if(newestMs!==Number.NEGATIVE_INFINITY){let cutoff=newestMs-SKILL_USAGE_LIMITS.maxAgeMs;aged=entries.filter((entry)=>{let ms=Date.parse(entry.timestamp);return Number.isNaN(ms)?!0:ms>=cutoff})}let perSkillCap=Math.max(1,maxEntriesPerSkill),groups=new Map;for(let entry of aged){let key=retentionKey(entry.skillPath),list=groups.get(key);if(list)list.push(entry);else groups.set(key,[entry])}let ordered=[];for(let list of groups.values())list.sort(compareNewestFirst),ordered.push(list.length>perSkillCap?list.slice(0,perSkillCap):list);let floor=SKILL_USAGE_LIMITS.floorPerSkill,reservedTotal=0;for(let list of ordered)reservedTotal+=Math.min(list.length,floor);let kept=[],skillsDropped=0;if(reservedTotal>SKILL_USAGE_LIMITS.maxEntries){ordered.sort((a,b)=>compareNewestFirst(a[0],b[0]));let used=0,admitting=!0;for(let list of ordered){let share=Math.min(list.length,floor);if(admitting&&used+share<=SKILL_USAGE_LIMITS.maxEntries){for(let i=0;i<share;i++)kept.push(list[i]);used+=share}else admitting=!1,skillsDropped+=1}}else{let leftovers=[];for(let list of ordered){let share=Math.min(list.length,floor);for(let i=0;i<share;i++)kept.push(list[i]);for(let i=share;i<list.length;i++)leftovers.push(list[i])}let budget=SKILL_USAGE_LIMITS.maxEntries-kept.length;if(budget>0&&leftovers.length>0){leftovers.sort(compareNewestFirst);let take=Math.min(budget,leftovers.length);for(let i=0;i<take;i++)kept.push(leftovers[i])}}kept.sort(compareNewestFirst);let bytes=0,cut=kept.length;for(let i=0;i<kept.length;i++)if(bytes+=JSON.stringify(kept[i]).length+1,bytes>SKILL_USAGE_LIMITS.maxBytes){cut=i;break}let bounded=cut<kept.length?kept.slice(0,cut):kept;return{kept:bounded,dropped:total-bounded.length,skillsDropped}}function needsMigration(doc2){return doc2.migrated!==!0}function toEnqueueInput(entry){if(!isActionableVerdict(entry.complianceVerdict))return null;return{id:entry.id,skillPath:canonicalSkillPath(entry.skillPath),verdict:entry.complianceVerdict,timestamp:entry.timestamp}}function rewriteWithoutMarkers(resolved){let dir=path60.dirname(resolved),tmpPath=path60.join(dir,`skill-usage-${Date.now()}.tmp`);try{_internals49.writeFileSync(tmpPath,"","utf-8");let buffer="";if(_internals49.streamLogLines(resolved,SKILL_USAGE_LIMITS.migrationChunkBytes,(line)=>{let parsed;try{parsed=JSON.parse(line)}catch{return}if(parseFeedbackMarker(parsed))return;if(buffer+=`${line}
637
+ `)){if(!line.trim())continue;try{let entry=parseSkillUsageEntry(JSON.parse(line));if(!entry)continue;if(filters.sessionID!==void 0&&entry.sessionID!==filters.sessionID)continue;entries.push(entry)}catch{}}return entries}finally{_internals49.closeSync(fd)}}catch{return[]}}function computeComplianceByVersion(entries,skillPath){let map2=new Map,normalizedTarget=skillPath.replace(/^file:/,"").replace(/\\/g,"/");for(let e of entries){let p=e.skillPath;if(p.startsWith("file:"))p=p.slice(5);let normalized=p.replace(/\\/g,"/");if(normalized!==normalizedTarget&&!normalizedTarget.endsWith(`/${normalized}`)&&!normalized.endsWith(`/${normalizedTarget}`))continue;let version2=e.skillVersion,stats2=map2.get(version2);if(!stats2)stats2={compliant:0,violation:0,total:0,rate:0},map2.set(version2,stats2);if(stats2.total+=1,e.complianceVerdict==="compliant")stats2.compliant+=1;if(normalizeComplianceVerdict(e.complianceVerdict)==="violated")stats2.violation+=1}for(let stats2 of map2.values())stats2.rate=stats2.total===0?0:stats2.compliant/stats2.total;return map2}function canonicalSkillPath(skillPath){return(skillPath.startsWith("file:")?skillPath.slice(5):skillPath).replace(/\\/g,"/")}function retentionKey(skillPath){return canonicalSkillPath(skillPath)}function compareNewestFirst(a,b){if(a.timestamp!==b.timestamp)return a.timestamp<b.timestamp?1:-1;if(a.id!==b.id)return a.id<b.id?-1:1;return 0}function compareOldestFirst(a,b){if(a.timestamp!==b.timestamp)return a.timestamp<b.timestamp?-1:1;if(a.id!==b.id)return a.id<b.id?-1:1;return 0}function applyRetention(entries,maxEntriesPerSkill){let total=entries.length;if(total===0)return{kept:[],dropped:0,skillsDropped:0};let newestMs=Number.NEGATIVE_INFINITY;for(let entry of entries){let ms=Date.parse(entry.timestamp);if(!Number.isNaN(ms)&&ms>newestMs)newestMs=ms}let aged=entries;if(newestMs!==Number.NEGATIVE_INFINITY){let cutoff=Math.min(newestMs,Date.now())-SKILL_USAGE_LIMITS.maxAgeMs;aged=entries.filter((entry)=>{let ms=Date.parse(entry.timestamp);return Number.isNaN(ms)?!0:ms>=cutoff})}let perSkillCap=Math.max(1,maxEntriesPerSkill),groups=new Map;for(let entry of aged){let key=retentionKey(entry.skillPath),list=groups.get(key);if(list)list.push(entry);else groups.set(key,[entry])}let ordered=[];for(let list of groups.values())list.sort(compareNewestFirst),ordered.push(list.length>perSkillCap?list.slice(0,perSkillCap):list);let floor=SKILL_USAGE_LIMITS.floorPerSkill,reservedTotal=0;for(let list of ordered)reservedTotal+=Math.min(list.length,floor);let kept=[],skillsDropped=0;if(reservedTotal>SKILL_USAGE_LIMITS.maxEntries){ordered.sort((a,b)=>compareNewestFirst(a[0],b[0]));let used=0,admitting=!0;for(let list of ordered){let share=Math.min(list.length,floor);if(admitting&&used+share<=SKILL_USAGE_LIMITS.maxEntries){for(let i=0;i<share;i++)kept.push(list[i]);used+=share}else admitting=!1,skillsDropped+=1}}else{let leftovers=[];for(let list of ordered){let share=Math.min(list.length,floor);for(let i=0;i<share;i++)kept.push(list[i]);for(let i=share;i<list.length;i++)leftovers.push(list[i])}let budget=SKILL_USAGE_LIMITS.maxEntries-kept.length;if(budget>0&&leftovers.length>0){leftovers.sort(compareNewestFirst);let take=Math.min(budget,leftovers.length);for(let i=0;i<take;i++)kept.push(leftovers[i])}}kept.sort(compareNewestFirst);let bytes=0,cut=kept.length;for(let i=0;i<kept.length;i++)if(bytes+=JSON.stringify(kept[i]).length+1,bytes>SKILL_USAGE_LIMITS.maxBytes){cut=i;break}let bounded=cut<kept.length?kept.slice(0,cut):kept;return{kept:bounded,dropped:total-bounded.length,skillsDropped}}function needsMigration(doc2){return doc2.migrated!==!0}function toEnqueueInput(entry){if(!isActionableVerdict(entry.complianceVerdict))return null;return{id:entry.id,skillPath:canonicalSkillPath(entry.skillPath),verdict:entry.complianceVerdict,timestamp:entry.timestamp}}function rewriteWithoutMarkers(resolved){let dir=path60.dirname(resolved),tmpPath=path60.join(dir,`skill-usage-${Date.now()}.tmp`);try{_internals49.writeFileSync(tmpPath,"","utf-8");let buffer="";if(_internals49.streamLogLines(resolved,SKILL_USAGE_LIMITS.migrationChunkBytes,(line)=>{let parsed;try{parsed=JSON.parse(line)}catch{return}if(parseFeedbackMarker(parsed))return;if(buffer+=`${line}
638
638
  `,buffer.length>=SKILL_USAGE_LIMITS.migrationChunkBytes)_internals49.appendFileSync(tmpPath,buffer,"utf-8"),buffer=""}),buffer.length>0)_internals49.appendFileSync(tmpPath,buffer,"utf-8");return _internals49.renameSync(tmpPath,resolved),!0}catch(err){try{if(_internals49.existsSync(tmpPath))_internals49.unlinkSync(tmpPath)}catch{}return log("[skill-usage-log] marker-drop rewrite failed (markers retained):",err instanceof Error?err.message:String(err)),!1}}function stagePendingDocument(doc2){return{version:doc2.version,migrated:doc2.migrated,records:doc2.records.map((record2)=>({...record2})),counters:{...doc2.counters},coverage:{...doc2.coverage}}}function adoptStagedDocument(target,staged){target.version=staged.version,target.migrated=staged.migrated,target.records=staged.records,target.counters=staged.counters,target.coverage=staged.coverage}function migrateLegacyLog(directory,doc2){let staged=stagePendingDocument(doc2),resolved=resolveLogPath(directory);if(!_internals49.existsSync(resolved)){staged.migrated=!0,savePendingDocument(directory,staged),adoptStagedDocument(doc2,staged);return}let chunk=SKILL_USAGE_LIMITS.migrationChunkBytes,candidates=[],markerCount=0,corruptLines=0,trimmed=0,trimCandidates=(limit)=>{if(candidates.length<=limit)return;candidates.sort((a,b)=>a.timestamp<b.timestamp?1:-1),trimmed+=candidates.length-limit,candidates=candidates.slice(0,limit)};if(_internals49.streamLogLines(resolved,chunk,(line)=>{let parsed;try{parsed=JSON.parse(line)}catch{corruptLines+=1;return}if(parseFeedbackMarker(parsed)){markerCount+=1;return}let entry=parseSkillUsageEntry(parsed);if(!entry)return;let input=toEnqueueInput(entry);if(!input)return;if(candidates.push(input),candidates.length>MIGRATION_MAX_CANDIDATES)trimCandidates(MIGRATION_MAX_CANDIDATES)},()=>{corruptLines+=1}),markerCount>0&&candidates.length>0){let candidateIds=new Set(candidates.map((c)=>c.id)),acked=new Set;if(_internals49.streamLogLines(resolved,chunk,(line)=>{let parsed;try{parsed=JSON.parse(line)}catch{return}let marker=parseFeedbackMarker(parsed);if(!marker)return;for(let id of marker.processedEntryIds)if(candidateIds.has(id))acked.add(id)}),acked.size>0)candidates=candidates.filter((c)=>!acked.has(c.id))}if(trimCandidates(SKILL_USAGE_LIMITS.queueMaxRecords),mergePendingRecords(staged,candidates,new Date().toISOString()),staged.counters.corrupt+=corruptLines,staged.counters.dropped+=trimmed,enforceQueueBounds(staged),staged.migrated=!0,savePendingDocument(directory,staged),adoptStagedDocument(doc2,staged),markerCount>0)rewriteWithoutMarkers(resolved);emitSkillUsageHealth(doc2,"migration",{bytes:queueByteSize(doc2),limitBytes:SKILL_USAGE_LIMITS.queueMaxBytes})}function ensureMigrated(directory,doc2){if(!needsMigration(doc2))return!0;try{migrateLegacyLog(directory,doc2)}catch(err){doc2.counters.corrupt+=1,criticalWarn(`[skill-usage-log] legacy skill-usage migration failed; the feedback_applied markers are RETAINED and compaction of .swarm/skill-usage.jsonl is skipped until it succeeds: ${err instanceof Error?err.message:String(err)}`)}return doc2.migrated===!0}function collectForCompaction(resolved,maxEntriesPerSkill){let buffer=[],total=0,markerCount=0,corruptLines=0,normalized=!1;_internals49.streamLogLines(resolved,SKILL_USAGE_LIMITS.migrationChunkBytes,(line)=>{let parsed;try{parsed=JSON.parse(line)}catch{corruptLines+=1;return}if(parseFeedbackMarker(parsed)){markerCount+=1;return}let entry=parseSkillUsageEntry(parsed);if(!entry){corruptLines+=1;return}total+=1;let canonical=canonicalSkillPath(entry.skillPath);if(canonical!==entry.skillPath)entry.skillPath=canonical,normalized=!0;if(buffer.push(entry),buffer.length>SKILL_USAGE_LIMITS.maxEntries*2)buffer=applyRetention(buffer,maxEntriesPerSkill).kept},()=>{corruptLines+=1});let final=applyRetention(buffer,maxEntriesPerSkill);return{kept:final.kept,total,markerCount,corruptLines,skillsDropped:final.skillsDropped,normalized}}function pruneSkillUsageLog(directory,maxEntriesPerSkill=500){let resolved=resolveLogPath(directory);if(!_internals49.existsSync(resolved))return{pruned:0,remaining:0};let handle=acquireSkillUsageLock(directory);if(!handle)return{pruned:0,remaining:readSkillUsageEntriesWithCoverage(directory).entries.length};try{let{doc:doc2}=loadPendingDocument(directory),migrated=ensureMigrated(directory,doc2);if(_suppressedOptionalAppends>0)doc2.counters.pressure+=_suppressedOptionalAppends,_suppressedOptionalAppends=0;let input=collectForCompaction(resolved,maxEntriesPerSkill);doc2.counters.corrupt+=input.corruptLines;let dropped=input.total-input.kept.length;if(!migrated){if(input.corruptLines>0)try{savePendingDocument(directory,doc2)}catch{}return{pruned:0,remaining:input.total}}if(!(dropped>0||input.markerCount>0||input.normalized||input.corruptLines>0))return{pruned:0,remaining:input.total};let surviving=input.kept.slice().sort(compareOldestFirst),dir=path60.dirname(resolved),tmpPath=path60.join(dir,`skill-usage-${Date.now()}.tmp`),content=surviving.map((e)=>JSON.stringify(e)).join(`
639
639
  `),stagedManifest=stagePendingDocument(doc2);if(stagedManifest.counters.compacted+=1,stagedManifest.counters.dropped+=dropped,stagedManifest.counters.skills_dropped+=input.skillsDropped,stagedManifest.coverage.entriesDropped+=dropped,stagedManifest.coverage.skillsDropped+=input.skillsDropped,dropped>0)stagedManifest.coverage.complete=!1;stagedManifest.coverage.oldestRetained=surviving.length>0?surviving[0].timestamp:null,stagedManifest.coverage.newestRetained=surviving.length>0?surviving[surviving.length-1].timestamp:null;try{savePendingDocument(directory,stagedManifest)}catch(err){let msg=err instanceof Error?err.message:String(err);return criticalWarn("[skill-usage-log] compaction manifest write failed; skipping the rewrite so no history is dropped without its coverage record:",msg),{pruned:0,remaining:input.total,error:msg}}try{_internals49.writeFileSync(tmpPath,surviving.length>0?`${content}
640
640
  `:"","utf-8"),_internals49.renameSync(tmpPath,resolved)}catch(writeErr){let msg=writeErr instanceof Error?writeErr.message:String(writeErr);try{if(_internals49.existsSync(tmpPath))_internals49.writeFileSync(tmpPath,"","utf-8")}catch{}return{pruned:0,remaining:input.total,error:msg}}return adoptStagedDocument(doc2,stagedManifest),emitSkillUsageHealth(doc2,"compaction",{bytes:content.length+(surviving.length>0?1:0),limitBytes:SKILL_USAGE_LIMITS.maxBytes}),{pruned:dropped,remaining:surviving.length}}finally{releaseSkillUsageLock(handle)}}async function resolveSourceKnowledgeIds(directory,skillPath){try{let cleanPath=skillPath;if(cleanPath.startsWith("file:"))cleanPath=cleanPath.slice(5);if(/\.\.[/\\]/.test(cleanPath))return[];let absolute=path60.normalize(path60.isAbsolute(cleanPath)?cleanPath:path60.resolve(directory,cleanPath)),baseDir=path60.normalize(path60.resolve(directory));if(!(process.platform==="win32"?absolute.toLowerCase().startsWith((baseDir+path60.sep).toLowerCase()):absolute.startsWith(baseDir+path60.sep)))return[];if(!_internals49.existsSync(absolute))return[];let content=_internals49.readFileSync(absolute,"utf-8");return parseGeneratedFromKnowledge(content)}catch(err){return log("[skill-usage-log] resolveSourceKnowledgeIds failed (fail-open):",err instanceof Error?err.message:String(err)),[]}}function parseGeneratedFromKnowledge(content){let frontmatterMatch=content.match(/^---\s*\n([\s\S]*?)\n---/);if(!frontmatterMatch)return[];let body=frontmatterMatch[1],ids=[],sectionRegex=/generated_from_knowledge\s*:\s*\n((?:\s+-\s+\S+[^\n]*\n?)+)/,sectionMatch=body.match(sectionRegex);if(!sectionMatch)return[];let lines=sectionMatch[1].split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-swarm",
3
- "version": "7.159.2",
3
+ "version": "7.159.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",