opencode-swarm 7.171.1 → 7.171.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{coder-settlement-vxpmxk46.js → coder-settlement-9e696204.js} +3 -3
- package/dist/cli/{config-doctor-vwy3c9g9.js → config-doctor-zr748h4m.js} +2 -2
- package/dist/cli/{core-2znms60v.js → core-aa3jmzcs.js} +1 -1
- package/dist/cli/{curator-llm-factory-exke3rag.js → curator-llm-factory-nshzhgs4.js} +19 -19
- package/dist/cli/{curator-kc80aj6d.js → curator-xgpxtaf1.js} +19 -19
- package/dist/cli/{evidence-summary-service-g3gr1pfs.js → evidence-summary-service-5e2323zr.js} +6 -6
- package/dist/cli/{gate-evidence-8mwsj2b7.js → gate-evidence-5htpsr5y.js} +2 -2
- package/dist/cli/{guardrail-explain-pkbjswtd.js → guardrail-explain-d0h0p73g.js} +20 -20
- package/dist/cli/{guardrail-log-qx1tpeda.js → guardrail-log-heejmjce.js} +3 -3
- package/dist/cli/{guardrail-reset-v91p8ca6.js → guardrail-reset-rdqxeqy0.js} +19 -19
- package/dist/cli/{hive-promoter-02vxb018.js → hive-promoter-n262tkm3.js} +19 -19
- package/dist/cli/{index-cdee25pp.js → index-04ph4jp2.js} +1 -1
- package/dist/cli/{index-8nbzfbjg.js → index-0yffa3np.js} +5 -5
- package/dist/cli/{index-6mjtptnb.js → index-11gz0few.js} +1 -1
- package/dist/cli/{index-7pae558g.js → index-2ryy0cwt.js} +2 -2
- package/dist/cli/{index-m1j1rth6.js → index-5a8q4qr5.js} +1 -1
- package/dist/cli/{index-d5pk5b95.js → index-7hnjs7tf.js} +2 -2
- package/dist/cli/{index-d6bs0p6d.js → index-9txyxbqc.js} +3 -3
- package/dist/cli/{index-ztxh3nmf.js → index-9vfp6g53.js} +21 -21
- package/dist/cli/{index-9cp6bhx9.js → index-d79q2f8z.js} +3 -3
- package/dist/cli/{index-4sf357vj.js → index-dsgc303n.js} +1 -1
- package/dist/cli/{index-s7h6txsk.js → index-e7yv4xw1.js} +2 -2
- package/dist/cli/{index-xefajbqv.js → index-f1rj1j8t.js} +73 -56
- package/dist/cli/{index-3zzyxs7q.js → index-gq2zdxep.js} +3 -3
- package/dist/cli/{index-5vgd9st3.js → index-j6rq132j.js} +2 -2
- package/dist/cli/{index-2j0pd6sj.js → index-jr6pypmj.js} +19 -19
- package/dist/cli/{index-rdjmbeex.js → index-mazy938h.js} +1 -1
- package/dist/cli/{index-rkj71ej6.js → index-ph94evsh.js} +3 -3
- package/dist/cli/{index-4rq1d5k5.js → index-q2yk70rs.js} +1 -1
- package/dist/cli/{index-xm0131fx.js → index-qcy7eg6z.js} +1 -1
- package/dist/cli/{index-wn9gf91x.js → index-qdy4a48x.js} +1 -1
- package/dist/cli/{index-5134766r.js → index-r60cw2jt.js} +4 -4
- package/dist/cli/{index-3jwamrzw.js → index-rrc08h4q.js} +1 -1
- package/dist/cli/{index-dr1ym009.js → index-vqb65csb.js} +3 -3
- package/dist/cli/{index-vs7b2pqm.js → index-wfh89qct.js} +1 -1
- package/dist/cli/index.js +19 -19
- package/dist/cli/{knowledge-escalator-4j6xgcvj.js → knowledge-escalator-kn74r5w8.js} +6 -6
- package/dist/cli/{knowledge-events-5ax1g356.js → knowledge-events-7gpw741m.js} +4 -4
- package/dist/cli/{knowledge-store-2nrtfb5x.js → knowledge-store-3f9kke7z.js} +1 -1
- package/dist/cli/{knowledge-validator-efcax8g9.js → knowledge-validator-c2z68v8v.js} +2 -2
- package/dist/cli/{pending-delegations-29qj2kya.js → pending-delegations-d5c07rb7.js} +2 -2
- package/dist/cli/{pr-subscriptions-t51vcrvd.js → pr-subscriptions-krv0jvds.js} +1 -1
- package/dist/cli/{pr-workflow-gate-03367gvd.js → pr-workflow-gate-hmdht1he.js} +19 -19
- package/dist/cli/{scan-cursor-nhxpv6tj.js → scan-cursor-b57xxs3q.js} +2 -2
- package/dist/cli/{schema-ht5hmsce.js → schema-r8tv8dqm.js} +1 -1
- package/dist/cli/{scope-persistence-6qebaksv.js → scope-persistence-0sc90mpj.js} +5 -5
- package/dist/cli/{skill-generator-tfm4kawf.js → skill-generator-syxa1mxm.js} +7 -7
- package/dist/cli/{snapshot-coordination-init-zgfjjv9p.js → snapshot-coordination-init-x18mwxyv.js} +19 -19
- package/dist/cli/{worktree-collision-ownership-6mgm8p9g.js → worktree-collision-ownership-1tzw8qzp.js} +2 -2
- package/dist/cli/{worktree-isolation-02rr7t21.js → worktree-isolation-ez0e48v3.js} +19 -19
- package/dist/index.js +2 -2
- package/dist/retention/dir-prune.d.ts +5 -1
- 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.171.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},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 recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, 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 with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, 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_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_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 scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.171.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",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},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 recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, 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 with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, 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_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_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 scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -1477,7 +1477,7 @@ ${inv.staleActiveSkills.slice(0,10).map((s)=>`- ${s.slug} | ${s.reasons.join(",
|
|
|
1477
1477
|
`),events=[],truncated=!1,badSuffix=null,lastCompleteSeq=0;for(let i=0;i<lines.length;i++){let line=lines[i];if(line.length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{truncated=!0,badSuffix=lines.slice(i).join(`
|
|
1478
1478
|
`);break}if(computeEventHash(parsed)!==parsed.hashAfter){truncated=!0,badSuffix=lines.slice(i).join(`
|
|
1479
1479
|
`);break}events.push(parsed),lastCompleteSeq=parsed.seq}let state=events.length===0?null:events[events.length-1].toState;return{events,state,truncated,badSuffix,lastCompleteSeq}}function quarantineSuffix(directory,skillSlug,badSuffix){assertProjectRoot(directory);let dir=path130.join(directory,".swarm","evolution","skills");if(!existsSync65(dir))mkdirSync39(dir,{recursive:!0});let hash4=computeStateHash(badSuffix).slice(0,12),stamp=Date.now(),quarantinePath=path130.join(dir,`lifecycle-quarantine.${skillSlug}.${stamp}.${hash4}`);return writeFileSyncAsync(quarantinePath,badSuffix,"utf8"),quarantinePath}function writeStateProjection(directory,skillSlug,candidateId,replay){assertProjectRoot(directory);let target=stateProjectionPath(directory,skillSlug,candidateId);ensureCandidateDir(directory,skillSlug,candidateId);let projection={v:1,candidateId,skillSlug,state:replay.state,lastCompleteSeq:replay.lastCompleteSeq,truncated:replay.truncated,eventCount:replay.events.length,updatedAt:new Date().toISOString()},tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;_internals109.writeFileFsyncedThenRename(tempPath,target,`${JSON.stringify(projection,null,2)}
|
|
1480
|
-
`)}function writeArtifact(directory,skillSlug,candidateId,fileName,content){assertProjectRoot(directory);let dir=ensureCandidateDir(directory,skillSlug,candidateId),target=path130.join(dir,fileName),tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;return _internals109.writeFileFsyncedThenRename(tempPath,target,content),target}function readArtifact(directory,skillSlug,candidateId,fileName){let target=path130.join(candidateDir(directory,skillSlug,candidateId),fileName);if(!existsSync65(target))return null;return readFileSync44(target,"utf8")}var SLUG_PATTERN3,_internals109;var init_store2=__esm(()=>{init_lock();init_project_boundary();SLUG_PATTERN3=/^[a-z0-9][a-z0-9-]{0,63}$/;_internals109={withEvidenceLock,writeFileFsyncedThenRename:writeFileFsyncedThenRename2,writeFileSync:writeFileSyncAsync,readFileSync:readFileSync44,renameSync:renameSync27,unlinkSync:unlinkSync24,existsSync:existsSync65,statSync:statSync44}});function isLegalTransition(from,to){return(from===null?INITIAL_TRANSITIONS:LEGAL_TRANSITIONS[from]).includes(to)}function assertTransition(from,to){if(!isLegalTransition(from,to))throw new IllegalTransitionError(from,to)}async function recordTransition(input){let replay=replayCandidate(input.directory,input.skillSlug,input.candidateId),fromState=replay.state;if(replay.truncated&&replay.badSuffix)quarantineSuffix(input.directory,input.skillSlug,replay.badSuffix),fromState=replay.events.length===0?null:replay.events[replay.events.length-1].toState;if(assertTransition(fromState,input.toState),input.toState==="validation_running"){if(replay.events.some((e)=>e.toState==="accepted_pending_approval"||e.toState==="rejected"||e.toState==="inconclusive"))throw Error(`candidate ${input.candidateId} already completed validation — start a new candidate to re-test`)}let event=await appendEvent2(input.directory,{candidateId:input.candidateId,skillSlug:input.skillSlug,eventType:input.eventType,fromState,toState:input.toState,actor:input.actor,origin:input.origin,contentHashBefore:input.contentHashBefore??null,contentHashAfter:input.contentHashAfter??null,reason:input.reason,evidenceRefs:input.evidenceRefs??[],...input.payload?{payload:input.payload}:{}});return writeStateProjection(input.directory,input.skillSlug,input.candidateId,{...replayCandidate(input.directory,input.skillSlug,input.candidateId),events:[...replay.events,event]}),{event,fromState,replayTruncated:replay.truncated}}function currentCandidateState(directory,skillSlug,candidateId){let replay=replayCandidate(directory,skillSlug,candidateId);if(replay.truncated&&replay.badSuffix)quarantineSuffix(directory,skillSlug,replay.badSuffix);return{state:replay.events.length===0?null:replay.events[replay.events.length-1].toState,lastEvent:replay.events.length===0?null:replay.events[replay.events.length-1],truncated:replay.truncated}}function isTerminal2(state){return state==="rejected"||state==="expired"||state==="rolled_back"}var IllegalTransitionError,LEGAL_TRANSITIONS,INITIAL_TRANSITIONS;var init_lifecycle=__esm(()=>{init_store2();IllegalTransitionError=class IllegalTransitionError extends Error{from;to;constructor(from,to){super(`illegal skill-opt transition: ${from??"<none>"} → ${to}`);this.from=from;this.to=to;this.name="IllegalTransitionError"}};LEGAL_TRANSITIONS={discovered:["drafted"],drafted:["smoke_validated","rejected"],smoke_validated:["validation_running","rejected"],validation_running:["accepted_pending_approval","rejected","inconclusive"],accepted_pending_approval:["activated","expired","rolled_back"],rejected:[],inconclusive:["drafted","rejected"],activated:["rolled_back"],expired:[],rolled_back:[]},INITIAL_TRANSITIONS=["discovered"]});import{mkdirSync as mkdirSync40,readdirSync as readdirSync14,renameSync as renameSync28,rmSync as rmSync14,statSync as statSync45}from"node:fs";import*as path131 from"node:path";function sanitizeSummaryId(id){if(!id||id.length===0)throw Error("Invalid summary ID: empty string");if(/\0/.test(id))throw Error("Invalid summary ID: contains null bytes");for(let i=0;i<id.length;i++)if(id.charCodeAt(i)<32)throw Error("Invalid summary ID: contains control characters");if(id.includes("..")||id.includes("../")||id.includes("..\\"))throw Error("Invalid summary ID: path traversal detected");if(!SUMMARY_ID_REGEX.test(id))throw Error(`Invalid summary ID: must match pattern ^S\\d+$, got "${id}"`);return id}async function storeSummary(directory,id,fullOutput,summaryText,maxStoredBytes){let sanitizedId=sanitizeSummaryId(id),preCheckEntry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},serializedSize=Buffer.byteLength(JSON.stringify(preCheckEntry),"utf8");if(serializedSize>maxStoredBytes)throw Error(`Summary entry size (${serializedSize} bytes) exceeds maximum (${maxStoredBytes} bytes)`);let relativePath2=path131.join("summaries",`${sanitizedId}.json`),summaryPath=validateSwarmPath(directory,relativePath2),summaryDir=path131.dirname(summaryPath),entry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},entryJson=JSON.stringify(entry);mkdirSync40(summaryDir,{recursive:!0});let tempPath=path131.join(summaryDir,`${sanitizedId}.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,entryJson),renameSync28(tempPath,summaryPath),invalidateCachedArtifact(summaryPath)}catch(error93){try{rmSync14(tempPath,{force:!0})}catch{}throw error93}}async function loadFullOutput(directory,id){let sanitizedId=sanitizeSummaryId(id),relativePath2=path131.join("summaries",`${sanitizedId}.json`);validateSwarmPath(directory,relativePath2);let content=await readSwarmFileAsync(directory,relativePath2);if(content===null)return null;try{let parsed=JSON.parse(content);if(typeof parsed.fullOutput==="string")return parsed.fullOutput;return warn(`Summary entry ${sanitizedId} missing valid fullOutput field`),null}catch(error93){return warn(`Summary entry validation failed for ${sanitizedId}: ${error93 instanceof Error?error93.message:String(error93)}`),null}}async function listStaleSummaryIds(directory,retentionDays,options){let summariesBasePath=validateSwarmPath(directory,"summaries"),retentionFiles=[];try{retentionFiles=readdirSync14(summariesBasePath).filter((name)=>name.endsWith(".json")&&/^S.+$/.test(name.slice(0,-5)))}catch{retentionFiles=[]}let cutoffTime=(options?.now??Date.now())-retentionDays*24*60*60*1000,stale=[];for(let filename of retentionFiles){let id=filename.slice(0,-5),relativePath2=path131.join("summaries",filename),summaryPath=validateSwarmPath(directory,relativePath2),content=await readSwarmFileAsync(directory,relativePath2);if(content===null)continue;try{let timestamp=JSON.parse(content).timestamp;if(typeof timestamp==="number"&&Number.isFinite(timestamp)&×tamp<cutoffTime||typeof timestamp!=="number"&&(()=>{try{return statSync45(summaryPath).mtimeMs<cutoffTime}catch{return!1}})())stale.push(id)}catch(error93){warn(`Failed to inspect summary ${id} for retention: ${error93 instanceof Error?error93.message:String(error93)}`)}}return stale}async function cleanupSummaries(directory,retentionDays,options){let staleIds=await listStaleSummaryIds(directory,retentionDays,options),deleted=[];for(let id of staleIds)try{rmSync14(validateSwarmPath(directory,path131.join("summaries",`${id}.json`))),deleted.push(id)}catch(error93){warn(`Failed to cleanup summary ${id}: ${error93 instanceof Error?error93.message:String(error93)}`)}return deleted}var SUMMARY_ID_REGEX;var init_manager3=__esm(()=>{init_utils2();init_caps();init_utils();init_bun_compat();init_swarm_artifact_cache();SUMMARY_ID_REGEX=/^S\d+$/});import*as fs76 from"node:fs";import*as path132 from"node:path";function subtreeNewestFileMtime(root,maxScan){let budget=maxScan,newest=null,stack=[root];while(stack.length>0){if(budget<=0)return Number.POSITIVE_INFINITY;let dir=stack.pop(),names;try{names=fs76.readdirSync(dir)}catch{return Number.POSITIVE_INFINITY}for(let name of names){if(budget<=0)return Number.POSITIVE_INFINITY;let entryPath=path132.join(dir,name),stat15;try{stat15=fs76.lstatSync(entryPath)}catch{continue}if(budget-=1,stat15.isSymbolicLink())continue;if(stat15.isDirectory()){stack.push(entryPath);continue}if(stat15.isFile()&&stat15.mtimeMs>(newest??-1/0))newest=stat15.mtimeMs}}return newest}function effectiveEntryMtime(entryPath,ownMtimeMs){let newest=subtreeNewestFileMtime(entryPath,SUBTREE_SCAN_CAP);if(newest===null)return ownMtimeMs;return newest}function listPruneCandidates(dir,maxScan){let candidates=[],refusedSymlinks=[],names;try{names=fs76.readdirSync(dir)}catch{return{candidates:[],refusedSymlinks:[]}}for(let name of names.slice(0,maxScan)){let entryPath=path132.join(dir,name);try{let stat15=fs76.lstatSync(entryPath);if(stat15.isSymbolicLink()){refusedSymlinks.push(name);continue}candidates.push({name,mtimeMs:stat15.isDirectory()?effectiveEntryMtime(entryPath,stat15.mtimeMs):stat15.mtimeMs})}catch{}}return{candidates,refusedSymlinks}}async function pruneDirectory(dir,opts){let now2=opts.now??Date.now(),maxScan=opts.maxScan??1e5,{candidates}=listPruneCandidates(dir,maxScan);if(candidates.length===0)return 0;candidates.sort((a,b)=>a.mtimeMs===b.mtimeMs?a.name<b.name?-1:a.name>b.name?1:0:a.mtimeMs-b.mtimeMs);let cutoff=opts.maxAgeMs!==void 0?now2-opts.maxAgeMs:null,victims=[];for(let candidate of candidates){if(candidate.mtimeMs>now2)continue;if(cutoff!==null&&candidate.mtimeMs<cutoff)victims.push(candidate)}if(opts.maxEntries!==void 0){let keepNewest=opts.maxEntries,excess=candidates.length-keepNewest;for(let i=0;i<excess;i++){let candidate=candidates[i];if(candidate.mtimeMs>now2)continue;if(!victims.includes(candidate))victims.push(candidate)}}let pruned=0;if(opts.dryRun!==!0){for(let victim of victims)try{fs76.rmSync(path132.join(dir,victim.name),{recursive:!0,force:!0}),pruned+=1}catch{}return pruned}return victims.length}var SUBTREE_SCAN_CAP=2000;var init_dir_prune=()=>{};import*as fs77 from"node:fs";import*as path133 from"node:path";function familiesFor(swarmRoot,now2){let age=(days)=>days*DAY_MS,f=(label,rel,opts)=>({label,dir:path133.join(swarmRoot,rel),maxAgeMs:opts.maxAgeDays!==void 0?age(opts.maxAgeDays):void 0,maxEntries:opts.maxEntries});return[f("pr-feedback-events","pr-feedback-events",{maxAgeDays:30}),f("pr-review-reentry-shadows",path133.join("pr-review","reentry-authorizations"),{maxAgeDays:30}),f("pr-review-run-artifacts","pr-review",{maxAgeDays:30,maxEntries:PR_REVIEW_KEEP_NEWEST_RUNS}),f("review-receipts","review-receipts",{maxAgeDays:30,maxEntries:REVIEW_RECEIPTS_KEEP_NEWEST}),f("lane-results","lane-results",{maxAgeDays:30,maxEntries:LANE_RESULTS_KEEP_NEWEST_BATCHES}),f("capsules","capsules",{maxAgeDays:30}),f("runs","runs",{maxAgeDays:30}),f("skills-proposals",path133.join("skills","proposals"),{maxAgeDays:14}),f("skill-improver-proposals",path133.join("skill-improver","proposals"),{maxAgeDays:30}),f("recovery","recovery",{maxAgeDays:30})]}async function runRetentionSweep(projectRoot,options={}){if(options.enabled===!1)return{pruned:{},disabled:!0,errors:{}};let now2=options.now??Date.now(),dryRun=options.dryRun===!0,swarmRoot=path133.join(projectRoot,".swarm"),result={pruned:{},dryRun,errors:{}};try{let resolvedRoot=fs77.realpathSync(projectRoot),resolvedSwarm=fs77.realpathSync(swarmRoot);if(!resolvedSwarm.startsWith(resolvedRoot+path133.sep)&&resolvedSwarm!==resolvedRoot)return result.errors.containment=".swarm resolves outside the project root; refusing sweep",result}catch(error93){if((typeof error93==="object"&&error93!==null&&"code"in error93?String(error93.code):"")!=="ENOENT")result.errors.containment=error93 instanceof Error?error93.message:String(error93);return result}let cancelled=(label)=>{if(options.shouldContinue&&!options.shouldContinue())return result.errors.sweep_cancelled=`sweep cancelled by shouldContinue token before ${label}`,!0;return!1};for(let family of familiesFor(swarmRoot,now2)){if(cancelled(family.label))return result;try{let pruned=await pruneDirectory(family.dir,{maxAgeMs:family.maxAgeMs,maxEntries:family.maxEntries,now:now2,dryRun});if(pruned>0)result.pruned[family.label]=pruned}catch(error93){result.errors[family.label]=error93 instanceof Error?error93.message:String(error93)}}if(cancelled("review-receipts-index"))return result;try{let dropped=await pruneDanglingReceiptIndexEntries(projectRoot,{dryRun});if(dropped>0)result.pruned["review-receipts-index"]=dropped}catch(error93){result.errors["review-receipts-index"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("epic-diagnostics"))return result;for(let[label,rel]of[["epic-divergence",path133.join("epic","divergence.jsonl")],["epic-calibration",path133.join("epic","calibration.json")]])try{let filePath=path133.join(swarmRoot,rel),stat15=await fs77.promises.stat(filePath).catch(()=>null);if(stat15&&stat15.mtimeMs<=now2&&stat15.mtimeMs<now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS){if(!dryRun)await fs77.promises.unlink(filePath).catch(()=>{return});result.pruned[label]=1}}catch(error93){result.errors[label]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("doc-drift-imported"))return result;try{let legacy=await fs77.promises.readdir(swarmRoot).then((names)=>names.filter((n)=>/^doc-drift-phase-\d+\.json\.imported$/.test(n))).catch(()=>[]),legacyPruned=0;for(let name of legacy){let filePath=path133.join(swarmRoot,name),stat15=await fs77.promises.stat(filePath).catch(()=>null);if(stat15&&stat15.mtimeMs<=now2&&stat15.mtimeMs<now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS){if(!dryRun)await fs77.promises.unlink(filePath).catch(()=>{return});legacyPruned+=1}}if(legacyPruned>0)result.pruned["doc-drift-imported"]=legacyPruned}catch(error93){result.errors["doc-drift-imported"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("legacy-ledger-archives"))return result;try{let names=(await fs77.promises.readdir(swarmRoot)).filter((name)=>/^plan-ledger\.legacy-archive\.[0-9a-f]{64}\.jsonl$/.test(name)),entries=(await Promise.all(names.map(async(name)=>{let filePath=path133.join(swarmRoot,name),stat15=await fs77.promises.lstat(filePath).catch(()=>null);return stat15?.isFile()&&!stat15.isSymbolicLink()?{name,filePath,mtimeMs:stat15.mtimeMs}:null}))).filter((entry)=>entry!==null).sort((a,b)=>b.mtimeMs-a.mtimeMs||a.name.localeCompare(b.name)),removed=0;for(let[index,entry]of entries.entries()){if(index<LEGACY_LEDGER_ARCHIVES_KEEP_NEWEST)continue;if(entry.mtimeMs>now2||entry.mtimeMs>=now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS)continue;if(!dryRun)await fs77.promises.unlink(entry.filePath).catch(()=>{return});removed++}if(removed>0)result.pruned["legacy-ledger-archives"]=removed}catch(error93){result.errors["legacy-ledger-archives"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("evolution-terminal-candidates"))return result;try{let evolutionRoot=path133.join(swarmRoot,"evolution","skills"),pruned=await pruneEvolutionCandidates(evolutionRoot,now2,dryRun);if(pruned>0)result.pruned["evolution-terminal-candidates"]=pruned}catch(error93){result.errors["evolution-terminal-candidates"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("evolution-scratch"))return result;try{let evalPruned=0;if(await walkEvolution(path133.join(swarmRoot,"evolution","skills"),async(entryPath,stat15)=>{let base=path133.basename(entryPath),isEvalInput=base==="_eval-input"&&stat15.isDirectory(),isQuarantine=base.startsWith("lifecycle-quarantine.");if(!isEvalInput&&!isQuarantine)return;let horizon=isEvalInput?7*DAY_MS:DEFAULT_FAMILY_AGE_DAYS*DAY_MS;if(stat15.mtimeMs<=now2&&stat15.mtimeMs<now2-horizon){if(!dryRun)fs77.rmSync(entryPath,{recursive:!0,force:!0});evalPruned+=1}}),evalPruned>0)result.pruned["evolution-scratch"]=evalPruned}catch(error93){result.errors["evolution-scratch"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("summaries-retention"))return result;try{let retentionDays=options.summariesRetentionDays??DEFAULT_SUMMARIES_RETENTION_DAYS,before=dryRun?await countStaleSummaries(projectRoot,retentionDays,now2):0;if(dryRun){if(before>0)result.pruned["summaries-retention"]=before}else{let deleted=await cleanupSummaries(projectRoot,retentionDays,{now:now2});if(deleted.length>0)result.pruned["summaries-retention"]=deleted.length}}catch(error93){result.errors["summaries-retention"]=error93 instanceof Error?error93.message:String(error93)}if(Object.keys(result.errors).length>0)log("retention sweep: per-family failures (non-fatal)",result.errors);return result}async function candidateIsTerminal(candidateDir2){let ledger=await readTailJsonlDetailed(path133.join(candidateDir2,"lifecycle.jsonl"),{maxEntries:1,maxBytes:65536});if(!ledger.tailTruncated){let last=ledger.records[ledger.records.length-1];if(last){let state=last.toState??last.type??"";if(isTerminal2(state))return!0}}try{let stateJson=JSON.parse(await fs77.promises.readFile(path133.join(candidateDir2,"state.json"),"utf-8"));if(isTerminal2(stateJson.state??null))return!0}catch{}return!1}async function pruneEvolutionCandidates(evolutionRoot,now2,dryRun){let pruned=0,skillDirs=await fs77.promises.readdir(evolutionRoot).catch(()=>[]);for(let skillSlug of skillDirs){let skillDir=path133.join(evolutionRoot,skillSlug);if(!await isRealDirectory(skillDir))continue;let candidates=await fs77.promises.readdir(skillDir).catch(()=>[]);for(let candidateId of candidates){let candidateDir2=path133.join(skillDir,candidateId),stat15=await fs77.promises.stat(candidateDir2).catch(()=>null);if(!stat15||!stat15.isDirectory())continue;let newest=subtreeNewestFileMtime(candidateDir2,SUBTREE_SCAN_CAP),effectiveMtime=newest===null?stat15.mtimeMs:newest;if(effectiveMtime>now2)continue;let ageMs=now2-effectiveMtime;if(!(await candidateIsTerminal(candidateDir2)&&ageMs>DEFAULT_FAMILY_AGE_DAYS*DAY_MS||ageMs>EVOLUTION_BACKSTOP_AGE_DAYS*DAY_MS))continue;if(!dryRun)fs77.rmSync(candidateDir2,{recursive:!0,force:!0});pruned+=1}}return pruned}async function walkEvolution(root,visit){let entries=await fs77.promises.readdir(root).catch(()=>[]);for(let name of entries){let entryPath=path133.join(root,name),stat15=await fs77.promises.lstat(entryPath).catch(()=>null);if(!stat15||stat15.isSymbolicLink())continue;if(stat15.isDirectory())await walkEvolution(entryPath,visit);await visit(entryPath,stat15)}}async function isRealDirectory(dir){try{let stat15=fs77.lstatSync(dir);return stat15.isDirectory()&&!stat15.isSymbolicLink()}catch{return!1}}async function countStaleSummaries(projectRoot,retentionDays,now2){return(await listStaleSummaryIds(projectRoot,retentionDays,{now:now2})).length}var DAY_MS=86400000,DEFAULT_FAMILY_AGE_DAYS=30,DEFAULT_SUMMARIES_RETENTION_DAYS=7,EVOLUTION_BACKSTOP_AGE_DAYS=90,PR_REVIEW_KEEP_NEWEST_RUNS=50,LANE_RESULTS_KEEP_NEWEST_BATCHES=100,REVIEW_RECEIPTS_KEEP_NEWEST=1000,LEGACY_LEDGER_ARCHIVES_KEEP_NEWEST=16;var init_sweep=__esm(()=>{init_review_receipt();init_lifecycle();init_manager3();init_logger();init_dir_prune();init_jsonl_cap()});import{closeSync as closeSync21,existsSync as existsSync66,fsyncSync as fsyncSync8,mkdirSync as mkdirSync41,openSync as openSync21,unlinkSync as unlinkSync25}from"node:fs";import{rename as fsRename}from"node:fs/promises";import*as path134 from"node:path";async function renameWithTransientRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS;attempt++)try{await _internals110.rename(tempPath,targetPath);return}catch(error93){lastError=error93;let code=error93.code;if(code==="ENOENT"&&attempt>0&&!existsSync66(tempPath)&&existsSync66(targetPath))return;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS-1)await new Promise((resolve59)=>setTimeout(resolve59,SNAPSHOT_RENAME_RETRY_DELAY_MS))}throw lastError}function serializeAgentSession(s){let gateLog={},rawGateLog=s.gateLog??new Map;for(let[taskId,gates]of rawGateLog)gateLog[taskId]=Array.from(gates??[]);let reviewerCallCount={},rawReviewerCallCount=s.reviewerCallCount??new Map;for(let[phase,count]of rawReviewerCallCount)reviewerCallCount[String(phase)]=count;let partialGateWarningsIssuedForTask=Array.from(s.partialGateWarningsIssuedForTask??new Set),completionGateWarnedForTask=Array.from(s.completionGateWarnedForTask??new Set),catastrophicPhaseWarnings=Array.from(s.catastrophicPhaseWarnings??new Set),phaseAgentsDispatched=Array.from(s.phaseAgentsDispatched??new Set),lastCompletedPhaseAgentsDispatched=Array.from(s.lastCompletedPhaseAgentsDispatched??new Set),stageBCompletion={};if(s.stageBCompletion)for(let[taskId,agents]of s.stageBCompletion)stageBCompletion[taskId]=Array.from(agents);let modifiedFilesByTask=Object.create(null);for(let[taskId,files]of s.modifiedFilesByTask??new Map)modifiedFilesByTask[taskId]=[...files];let windows={},rawWindows=s.windows??{};for(let[key2,win]of Object.entries(rawWindows))windows[key2]={id:win.id,agentName:win.agentName,startedAtMs:win.startedAtMs,toolCalls:win.toolCalls,consecutiveErrors:win.consecutiveErrors,hardLimitHit:win.hardLimitHit,lastSuccessTimeMs:win.lastSuccessTimeMs,recentToolCalls:win.recentToolCalls,warningIssued:win.warningIssued,warningReason:win.warningReason,transientRetryCount:win.transientRetryCount??0};return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,...s.turboStrategy!==void 0&&{turboStrategy:s.turboStrategy},leanTurboActive:s.leanTurboActive??!1,...s.leanTurboCurrentPhase!==void 0&&{leanTurboCurrentPhase:s.leanTurboCurrentPhase},epicModeActive:s.epicModeActive??!1,gateLog,reviewerCallCount,lastGateFailure:s.lastGateFailure??null,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],taskWorkflowStates:Object.fromEntries(s.taskWorkflowStates??new Map),...Object.keys(modifiedFilesByTask).length>0&&{modifiedFilesByTask},...s.scopeViolationDetected!==void 0&&{scopeViolationDetected:s.scopeViolationDetected},model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,sessionRehydratedAt:s.sessionRehydratedAt??0,...Object.keys(stageBCompletion).length>0&&{stageBCompletion},...s.maxConcurrencyOverride!==void 0&&{maxConcurrencyOverride:s.maxConcurrencyOverride},...s.autoProceedOverride!==void 0&&{autoProceedOverride:s.autoProceedOverride},...s.autoProceedNudgeDone!==void 0&&{autoProceedNudgeDone:s.autoProceedNudgeDone},...s.cachedCohortId!==void 0&&{cachedCohortId:s.cachedCohortId},...s.lastObservedModel!==void 0&&{lastObservedModel:s.lastObservedModel},...s.lastObservedProviderID!==void 0&&{lastObservedProviderID:s.lastObservedProviderID}}}async function writeSnapshot2(directory,state){try{let{ensureSnapshotCoordinationReady}=await Promise.resolve().then(() => (init_snapshot_coordination_init(),exports_snapshot_coordination_init));await ensureSnapshotCoordinationReady(directory);let snapshot={version:3,writtenAt:Date.now(),workflowSchema:TASK_WORKFLOW_SCHEMA_MARKER,toolAggregates:Object.fromEntries(state.toolAggregates),activeAgent:Object.fromEntries([...state.activeAgent].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),delegationChains:Object.fromEntries([...state.delegationChains].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),agentSessions:{}};for(let[sessionId,sessionState]of state.agentSessions){if(!isSnapshotSessionOwnedLocally(sessionId))continue;snapshot.agentSessions[sessionId]=serializeAgentSession(sessionState)}writeSnapshotRows(directory,snapshot,{onlyLocallyOwnedSessions:!0});let canonicalSnapshot=readSnapshotRows(directory)??snapshot;await writeSnapshotProjection(directory,canonicalSnapshot)}catch(error93){log("[snapshot-writer] write failed",{error:error93 instanceof Error?error93.message:String(error93)})}}async function writeSnapshotProjection(directory,snapshot){let content=JSON.stringify(snapshot,null,2),resolvedPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),dir=path134.dirname(resolvedPath);mkdirSync41(dir,{recursive:!0});let tempPath=`${resolvedPath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;await bunWrite(tempPath,content);try{let fd=openSync21(tempPath,"r+");try{fsyncSync8(fd)}finally{closeSync21(fd)}}catch{}try{await renameWithTransientRetry(tempPath,resolvedPath)}finally{try{unlinkSync25(tempPath)}catch{}}invalidateCachedArtifact(resolvedPath)}function createSnapshotWriterHook(directory){return(_input,_output)=>{return _writeInFlight=_writeInFlight.then(()=>_internals110.writeSnapshot(directory,swarmState),()=>_internals110.writeSnapshot(directory,swarmState)),_writeInFlight}}async function flushPendingSnapshot(directory){_writeInFlight=_writeInFlight.then(()=>_internals110.writeSnapshot(directory,swarmState),()=>_internals110.writeSnapshot(directory,swarmState)),await _writeInFlight}var SNAPSHOT_PROJECTION_FILE="session/state.sqlite-projection.json",_writeInFlight,SNAPSHOT_RENAME_MAX_ATTEMPTS=3,SNAPSHOT_RENAME_RETRY_DELAY_MS=50,_internals110;var init_snapshot_writer=__esm(()=>{init_gate_evidence();init_utils2();init_state2();init_utils();init_bun_compat();init_swarm_artifact_cache();init_snapshot_store();_writeInFlight=Promise.resolve();_internals110={writeSnapshot:writeSnapshot2,createSnapshotWriterHook,flushPendingSnapshot,rename:fsRename}});import{renameSync as renameSync29}from"node:fs";function deserializeTaskWorkflowStates(raw){let m=new Map;if(!raw||typeof raw!=="object")return m;for(let[taskId,stateVal]of Object.entries(raw))if(VALID_TASK_WORKFLOW_STATES.includes(stateVal))m.set(taskId,stateVal);return m}function deserializeModifiedFilesByTask(raw){let entries=new Map;if(!raw||typeof raw!=="object")return entries;let serializedEntries=Object.entries(raw);if(serializedEntries.length>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS)return entries;for(let[taskId,files]of serializedEntries){if(!taskId.trim()||!Array.isArray(files))continue;let validFiles=files.filter((file3)=>typeof file3==="string"&&file3.length>0);entries.set(taskId,[...new Set(validFiles)])}return entries}function deserializeAgentSession(s){let lastGateFailure=s.lastGateFailure?{tool:s.lastGateFailure.tool,taskId:s.lastGateFailure.taskId,timestamp:s.lastGateFailure.timestamp,...typeof s.lastGateFailure.code==="string"&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.lastGateFailure.code)&&{code:s.lastGateFailure.code}}:null,taskWorkflowStates=deserializeTaskWorkflowStates(s.taskWorkflowStates),modifiedFilesByTask=deserializeModifiedFilesByTask(s.modifiedFilesByTask),gateLog=new Map;if(s.gateLog)for(let[taskId,gates]of Object.entries(s.gateLog))gateLog.set(taskId,new Set(gates??[]));let reviewerCallCount=new Map;if(s.reviewerCallCount)for(let[phase,count]of Object.entries(s.reviewerCallCount)){let numPhase=Number(phase);if(Number.isFinite(numPhase))reviewerCallCount.set(numPhase,count)}let partialGateWarningsIssuedForTask=new Set(s.partialGateWarningsIssuedForTask??[]),completionGateWarnedForTask=new Set(s.completionGateWarnedForTask??[]),catastrophicPhaseWarnings=new Set(s.catastrophicPhaseWarnings??[]),phaseAgentsDispatched=new Set(s.phaseAgentsDispatched??[]),lastCompletedPhaseAgentsDispatched=new Set(s.lastCompletedPhaseAgentsDispatched??[]),stageBCompletion=new Map;if(s.stageBCompletion)for(let[taskId,agents]of Object.entries(s.stageBCompletion))stageBCompletion.set(taskId,new Set(agents));let windows={};for(let[key2,win]of Object.entries(s.windows??{})){if(!win||typeof win!=="object")continue;windows[key2]={...win,transientRetryCount:"transientRetryCount"in win?win.transientRetryCount??0:0}}return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,turboStrategy:s.turboStrategy==="lean"||s.turboStrategy==="standard"?s.turboStrategy:void 0,leanTurboActive:s.leanTurboActive??!1,leanTurboCurrentPhase:typeof s.leanTurboCurrentPhase==="number"?s.leanTurboCurrentPhase:void 0,epicModeActive:s.epicModeActive??!1,gateLog,reviewerCallCount,lastGateFailure,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],taskWorkflowStates,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:s.scopeViolationDetected,modifiedFilesByTask,modifiedFilesThisCoderTask:s.currentTaskId&&s.currentTaskId.trim()!==""&&modifiedFilesByTask.has(s.currentTaskId)?[...modifiedFilesByTask.get(s.currentTaskId)??[]]:[],loopDetectionWindow:[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,maxConcurrencyOverride:typeof s.maxConcurrencyOverride==="number"?Math.min(64,Math.max(1,s.maxConcurrencyOverride)):void 0,autoProceedOverride:s.autoProceedOverride,autoProceedNudgeDone:s.autoProceedNudgeDone,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,sessionRehydratedAt:s.sessionRehydratedAt??0,stageBCompletion,prSubscriptions:new Map,cachedCohortId:typeof s.cachedCohortId==="string"?s.cachedCohortId:void 0,lastObservedModel:typeof s.lastObservedModel==="string"?s.lastObservedModel:void 0,lastObservedProviderID:typeof s.lastObservedProviderID==="string"?s.lastObservedProviderID:void 0}}async function readSnapshot(directory){for(let relativePath2 of[SNAPSHOT_PROJECTION_FILE,"session/state.json"])try{let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())continue;let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3){try{let quarantinePath=validateSwarmPath(directory,`${relativePath2}.quarantine`);renameSync29(resolvedPath,quarantinePath)}catch{}continue}return parsed}catch{}return null}async function readSnapshotFileStrict(directory,relativePath2){let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())throw Error(`snapshot ${relativePath2} is empty`);let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3)throw Error(`snapshot ${relativePath2} has an unsupported version`);if(!parsed.toolAggregates||!parsed.activeAgent||!parsed.delegationChains||!parsed.agentSessions)throw Error(`snapshot ${relativePath2} has an invalid shape`);return parsed}async function rehydrateState(snapshot,directory){if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);if(swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.agentSessions.clear(),snapshot.toolAggregates)for(let[key2,value]of Object.entries(snapshot.toolAggregates))swarmState.toolAggregates.set(key2,value);let now2=Date.now();if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS)session[field.name]=field.resetValue;if(session.fullAutoMode){let runStillActive=!1;if(directory)try{runStillActive=loadFullAutoRunState(directory,sessionId)?.status==="running"}catch{runStillActive=!1}if(!runStillActive)session.fullAutoMode=!1}swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key2,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key2))swarmState.activeAgent.set(key2,value)}if(snapshot.delegationChains){for(let[key2,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key2))swarmState.delegationChains.set(key2,value)}}async function loadSnapshot(directory){try{await buildRehydrationCache(directory);let snapshot=await readSnapshot(directory);if(snapshot!==null){await rehydrateState(snapshot,directory);for(let session of swarmState.agentSessions.values())applyRehydrationCache(session)}}catch{}}var TRANSIENT_SESSION_FIELDS,VALID_TASK_WORKFLOW_STATES;var init_snapshot_reader=__esm(()=>{init_state3();init_utils2();init_state2();init_bun_compat();init_logger();init_snapshot_writer();TRANSIENT_SESSION_FIELDS=[{name:"revisionLimitHit",resetValue:!1},{name:"coderRevisions",resetValue:0},{name:"selfFixAttempted",resetValue:!1},{name:"lastGateFailure",resetValue:null},{name:"architectWriteCount",resetValue:0},{name:"selfCodingWarnedAtCount",resetValue:0},{name:"pendingAdvisoryMessages",resetValue:[]},{name:"model_fallback_index",resetValue:0},{name:"modelFallbackExhausted",resetValue:!1},{name:"scopeViolationDetected",resetValue:!1},{name:"delegationActive",resetValue:!1},{name:"autoProceedOverride",resetValue:void 0},{name:"autoProceedNudgeDone",resetValue:void 0}],VALID_TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"]});var exports_snapshot_coordination_init={};__export(exports_snapshot_coordination_init,{startSnapshotCoordinationInitialization:()=>startSnapshotCoordinationInitialization,retrySnapshotCoordinationInitialization:()=>retrySnapshotCoordinationInitialization,markSnapshotCoordinationClosing:()=>markSnapshotCoordinationClosing,getSnapshotCoordinationStatus:()=>getSnapshotCoordinationStatus,ensureSnapshotCoordinationReady:()=>ensureSnapshotCoordinationReady,closeSnapshotCoordinationInitialization:()=>closeSnapshotCoordinationInitialization,beginSnapshotCoordinationReset:()=>beginSnapshotCoordinationReset,_snapshotCoordinationInternals:()=>_snapshotCoordinationInternals});import{createHash as createHash59,randomUUID as randomUUID21}from"node:crypto";import{existsSync as existsSync67,readFileSync as readFileSync45,renameSync as renameSync30}from"node:fs";function isRetryableArchiveError(error93){let code=error93?.code;return code==="EBUSY"||code==="EPERM"||code==="EACCES"}async function archiveLegacySnapshotIfPresent(legacyPath,expectedSnapshot){if(!existsSync67(legacyPath))return;if(expectedSnapshot)try{if(JSON.stringify(JSON.parse(readFileSync45(legacyPath,"utf8")))!==JSON.stringify(expectedSnapshot)){advisoryWarn("[opencode-swarm] Legacy snapshot changed after SQLite coordination; preserving it for explicit recovery.");return}}catch{return}let canonicalArchive=`${legacyPath}.imported`,archivePath=existsSync67(canonicalArchive)?`${canonicalArchive}.${randomUUID21()}`:canonicalArchive,lastError;for(let attempt=1;attempt<=ARCHIVE_RETRY_ATTEMPTS;attempt+=1)try{_snapshotCoordinationInternals.renameLegacySnapshot(legacyPath,archivePath);return}catch(error93){if(lastError=error93,!isRetryableArchiveError(error93)||attempt===ARCHIVE_RETRY_ATTEMPTS)break;await new Promise((resolve59)=>setTimeout(resolve59,ARCHIVE_RETRY_DELAY_MS))}advisoryWarn(`[opencode-swarm] SQLite snapshot is authoritative, but the legacy shadow could not be archived: ${lastError instanceof Error?lastError.message:String(lastError)}`)}function evictSettledEntries(){while(entries.size>=MAX_READY_ROOTS){let victim=[...entries].find(([,entry])=>entry.settled);if(!victim)return!1;entries.delete(victim[0])}return!0}async function initializeSnapshotCoordination(directory){let legacyArchiveAttempted=!1,snapshot=readSnapshotRows(directory);if(!snapshot){let legacyPath=validateSwarmPath(directory,"session/state.json"),projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),source=existsSync67(projectionPath)?SNAPSHOT_PROJECTION_FILE:existsSync67(legacyPath)?"session/state.json":null;if(source){let candidate=await readSnapshotFileStrict(directory,source),serialized2=JSON.stringify(candidate),outcome=importSnapshotRowsOnce(directory,candidate,createHash59("sha256").update(serialized2).digest("hex"),source);if(snapshot=readSnapshotRows(directory),outcome==="imported"&&source==="session/state.json")legacyArchiveAttempted=!0,await archiveLegacySnapshotIfPresent(legacyPath,candidate)}}if(!snapshot)return;if(!legacyArchiveAttempted)await archiveLegacySnapshotIfPresent(validateSwarmPath(directory,"session/state.json"),snapshot);await rehydrateState(snapshot,directory);for(let session of swarmState.agentSessions.values())applyRehydrationCache(session);try{await _snapshotCoordinationInternals.writeProjection(directory,snapshot)}catch(error93){advisoryWarn(`[opencode-swarm] SQLite snapshot is ready, but its compatibility projection could not be written: ${error93 instanceof Error?error93.message:String(error93)}`)}}function startSnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),existing=entries.get(root);if(existing?.state==="closing")return Promise.reject(Error("coordination initialization is closing for reset-session"));if(existing&&!existing.settled)return existing.underlying;if(existing?.state==="succeeded")return existing.underlying;if(!evictSettledEntries()){let error93=Error(`SQLite snapshot coordination capacity exhausted (${MAX_READY_ROOTS} unsettled roots)`);return advisoryWarn(`[opencode-swarm] ${error93.message}; initialization refused.`),Promise.reject(error93)}let attemptId=nextAttemptId++,generation=(existing?.generation??0)+1,entry={attemptId,generation,state:"running",settled:!1,underlying:Promise.resolve()},underlying=_snapshotCoordinationInternals.initialize(root).then(()=>{if(entries.get(root)===entry&&entry.state!=="closing")entry.state="succeeded"}).catch((error93)=>{throw entry.state="failed",entry.error=error93 instanceof Error?error93.message:String(error93),error93}).finally(()=>{entry.settled=!0});return entry.underlying=underlying,entries.set(root,entry),withTimeout(underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization timed out")).catch((error93)=>{if(!entry.settled&&entries.get(root)===entry)entry.state="timed_out",entry.error=error93 instanceof Error?error93.message:String(error93),advisoryWarn("[opencode-swarm] SQLite coordination initialization is still running; authority operations remain fail-closed.")}),underlying}async function ensureSnapshotCoordinationReady(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(!entry)return startSnapshotCoordinationInitialization(root);if(entry.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry.state==="timed_out"&&!entry.settled)throw Error("coordination initialization remains unsettled after timeout");if(await entry.underlying,entry.state!=="succeeded")throw Error(entry.error??"coordination initialization failed")}function retrySnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(entry?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry&&!entry.settled)throw Error("coordination initialization is still unsettled; recovery refused");return entries.delete(root),startSnapshotCoordinationInitialization(root)}function getSnapshotCoordinationStatus(directory){let entry=entries.get(canonicalProjectKey(directory));if(!entry)return{state:"idle",settled:!0};return{state:entry.state,attemptId:entry.attemptId,generation:entry.generation,settled:entry.settled,...entry.error?{error:entry.error.slice(0,512)}:{}}}async function beginSnapshotCoordinationReset(directory){let root=canonicalProjectKey(directory),prior=entries.get(root),closeError,priorUnsettled=!1;if(prior){prior.state="closing";try{await withTimeout(prior.underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization close timed out"))}catch(error93){if(closeError=error93 instanceof Error?error93:Error(String(error93)),priorUnsettled=!prior.settled,priorUnsettled)prior.underlying.catch(()=>{return})}}let guard={attemptId:nextAttemptId++,generation:(prior?.generation??0)+1,state:"closing",settled:!0,underlying:Promise.resolve(),...closeError?{error:closeError.message}:{}};entries.set(root,guard);let released=!1;return{release:()=>{if(released)return;released=!0;let removeGuard=()=>{if(entries.get(root)===guard)entries.delete(root)};if(!prior||prior.settled){removeGuard();return}prior.underlying.then(removeGuard,removeGuard)},...closeError?{closeError}:{},...priorUnsettled?{priorUnsettled:!0}:{}}}async function closeSnapshotCoordinationInitialization(directory){let guard=await beginSnapshotCoordinationReset(directory);try{if(guard.closeError)throw guard.closeError}finally{guard.release()}}function markSnapshotCoordinationClosing(directory){let entry=entries.get(canonicalProjectKey(directory));if(entry)entry.state="closing"}var READY_TIMEOUT_MS=1e4,MAX_READY_ROOTS=32,ARCHIVE_RETRY_ATTEMPTS=3,ARCHIVE_RETRY_DELAY_MS=25,entries,nextAttemptId=1,_snapshotCoordinationInternals;var init_snapshot_coordination_init=__esm(()=>{init_canonical_project();init_utils2();init_warning_buffer();init_state2();init_timeout();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();entries=new Map;_snapshotCoordinationInternals={entries,initialize:initializeSnapshotCoordination,renameLegacySnapshot:renameSync30,writeProjection:writeSnapshotProjection,timeoutMs:READY_TIMEOUT_MS}});import*as fsSync15 from"node:fs";import{promises as fs78}from"node:fs";import path135 from"node:path";async function archiveCloseSummary(ctx,closeSummaryPath,summaryWritten){if(!summaryWritten||ctx.archiveStageFailed||!ctx.archiveDir)return;try{await fs78.copyFile(closeSummaryPath,path135.join(ctx.archiveDir,"close-summary.md"))}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to archive close-summary.md: ${msg}`),log("[close-command] Failed to archive close-summary.md:",error93)}}async function handleCloseCommand(directory,args2,options={}){let swarmDir=path135.join(directory,".swarm");try{if(fsSync15.lstatSync(swarmDir).isSymbolicLink())return"❌ Refused: .swarm/ is a symlink or junction. Refusing to operate on a redirected directory for safety."}catch(err){if(err?.code!=="ENOENT")throw err}let planPath=validateSwarmPath(directory,"plan.json"),planExists=!1,planData={title:path135.basename(directory)||"Ad-hoc session",phases:[]};try{let content=await fs78.readFile(planPath,"utf-8");planData=JSON.parse(content),planExists=!0}catch(error93){if(error93?.code!=="ENOENT")return`❌ Failed to read plan.json: ${error93 instanceof Error?error93.message:String(error93)}`;try{let recovered=(await peekPlanFromLedger(directory)).plan;if(recovered)planData=recovered,planExists=!0}catch(recoveryError){return`❌ Failed to recover plan from the authoritative ledger: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`}if(!planExists){if(!await fs78.access(swarmDir).then(()=>!0).catch(()=>!1))return`❌ No .swarm/ directory found in ${directory}. Run /swarm close from the project root, or run /swarm plan first.`}}if(args2.includes("--dry-run"))return _internals97.runFinalizeDryRun(directory,swarmDir,planData,planExists);let finalizeLock={acquired:!1};if(finalizeLock=await _internals97.acquireFinalizeLock(directory),!finalizeLock.acquired)return"❌ Another /swarm finalize is already running for this project. If you are certain no other run is active, wait for the lock to expire or remove the stale lock and retry.";try{if(await closeSnapshotCoordinationInitialization(directory),!planExists){let archiveDir=path135.join(swarmDir,"archive");try{if((await fs78.readdir(archiveDir)).some((entry)=>entry.startsWith("swarm-"))){if(![...ACTIVE_STATE_TO_CLEAN,...ACTIVE_STATE_DIRS_TO_CLEAN].some((entry)=>fsSync15.existsSync(path135.join(swarmDir,entry))))return`✅ Already finalized — nothing to do.
|
|
1480
|
+
`)}function writeArtifact(directory,skillSlug,candidateId,fileName,content){assertProjectRoot(directory);let dir=ensureCandidateDir(directory,skillSlug,candidateId),target=path130.join(dir,fileName),tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;return _internals109.writeFileFsyncedThenRename(tempPath,target,content),target}function readArtifact(directory,skillSlug,candidateId,fileName){let target=path130.join(candidateDir(directory,skillSlug,candidateId),fileName);if(!existsSync65(target))return null;return readFileSync44(target,"utf8")}var SLUG_PATTERN3,_internals109;var init_store2=__esm(()=>{init_lock();init_project_boundary();SLUG_PATTERN3=/^[a-z0-9][a-z0-9-]{0,63}$/;_internals109={withEvidenceLock,writeFileFsyncedThenRename:writeFileFsyncedThenRename2,writeFileSync:writeFileSyncAsync,readFileSync:readFileSync44,renameSync:renameSync27,unlinkSync:unlinkSync24,existsSync:existsSync65,statSync:statSync44}});function isLegalTransition(from,to){return(from===null?INITIAL_TRANSITIONS:LEGAL_TRANSITIONS[from]).includes(to)}function assertTransition(from,to){if(!isLegalTransition(from,to))throw new IllegalTransitionError(from,to)}async function recordTransition(input){let replay=replayCandidate(input.directory,input.skillSlug,input.candidateId),fromState=replay.state;if(replay.truncated&&replay.badSuffix)quarantineSuffix(input.directory,input.skillSlug,replay.badSuffix),fromState=replay.events.length===0?null:replay.events[replay.events.length-1].toState;if(assertTransition(fromState,input.toState),input.toState==="validation_running"){if(replay.events.some((e)=>e.toState==="accepted_pending_approval"||e.toState==="rejected"||e.toState==="inconclusive"))throw Error(`candidate ${input.candidateId} already completed validation — start a new candidate to re-test`)}let event=await appendEvent2(input.directory,{candidateId:input.candidateId,skillSlug:input.skillSlug,eventType:input.eventType,fromState,toState:input.toState,actor:input.actor,origin:input.origin,contentHashBefore:input.contentHashBefore??null,contentHashAfter:input.contentHashAfter??null,reason:input.reason,evidenceRefs:input.evidenceRefs??[],...input.payload?{payload:input.payload}:{}});return writeStateProjection(input.directory,input.skillSlug,input.candidateId,{...replayCandidate(input.directory,input.skillSlug,input.candidateId),events:[...replay.events,event]}),{event,fromState,replayTruncated:replay.truncated}}function currentCandidateState(directory,skillSlug,candidateId){let replay=replayCandidate(directory,skillSlug,candidateId);if(replay.truncated&&replay.badSuffix)quarantineSuffix(directory,skillSlug,replay.badSuffix);return{state:replay.events.length===0?null:replay.events[replay.events.length-1].toState,lastEvent:replay.events.length===0?null:replay.events[replay.events.length-1],truncated:replay.truncated}}function isTerminal2(state){return state==="rejected"||state==="expired"||state==="rolled_back"}var IllegalTransitionError,LEGAL_TRANSITIONS,INITIAL_TRANSITIONS;var init_lifecycle=__esm(()=>{init_store2();IllegalTransitionError=class IllegalTransitionError extends Error{from;to;constructor(from,to){super(`illegal skill-opt transition: ${from??"<none>"} → ${to}`);this.from=from;this.to=to;this.name="IllegalTransitionError"}};LEGAL_TRANSITIONS={discovered:["drafted"],drafted:["smoke_validated","rejected"],smoke_validated:["validation_running","rejected"],validation_running:["accepted_pending_approval","rejected","inconclusive"],accepted_pending_approval:["activated","expired","rolled_back"],rejected:[],inconclusive:["drafted","rejected"],activated:["rolled_back"],expired:[],rolled_back:[]},INITIAL_TRANSITIONS=["discovered"]});import{mkdirSync as mkdirSync40,readdirSync as readdirSync14,renameSync as renameSync28,rmSync as rmSync14,statSync as statSync45}from"node:fs";import*as path131 from"node:path";function sanitizeSummaryId(id){if(!id||id.length===0)throw Error("Invalid summary ID: empty string");if(/\0/.test(id))throw Error("Invalid summary ID: contains null bytes");for(let i=0;i<id.length;i++)if(id.charCodeAt(i)<32)throw Error("Invalid summary ID: contains control characters");if(id.includes("..")||id.includes("../")||id.includes("..\\"))throw Error("Invalid summary ID: path traversal detected");if(!SUMMARY_ID_REGEX.test(id))throw Error(`Invalid summary ID: must match pattern ^S\\d+$, got "${id}"`);return id}async function storeSummary(directory,id,fullOutput,summaryText,maxStoredBytes){let sanitizedId=sanitizeSummaryId(id),preCheckEntry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},serializedSize=Buffer.byteLength(JSON.stringify(preCheckEntry),"utf8");if(serializedSize>maxStoredBytes)throw Error(`Summary entry size (${serializedSize} bytes) exceeds maximum (${maxStoredBytes} bytes)`);let relativePath2=path131.join("summaries",`${sanitizedId}.json`),summaryPath=validateSwarmPath(directory,relativePath2),summaryDir=path131.dirname(summaryPath),entry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},entryJson=JSON.stringify(entry);mkdirSync40(summaryDir,{recursive:!0});let tempPath=path131.join(summaryDir,`${sanitizedId}.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,entryJson),renameSync28(tempPath,summaryPath),invalidateCachedArtifact(summaryPath)}catch(error93){try{rmSync14(tempPath,{force:!0})}catch{}throw error93}}async function loadFullOutput(directory,id){let sanitizedId=sanitizeSummaryId(id),relativePath2=path131.join("summaries",`${sanitizedId}.json`);validateSwarmPath(directory,relativePath2);let content=await readSwarmFileAsync(directory,relativePath2);if(content===null)return null;try{let parsed=JSON.parse(content);if(typeof parsed.fullOutput==="string")return parsed.fullOutput;return warn(`Summary entry ${sanitizedId} missing valid fullOutput field`),null}catch(error93){return warn(`Summary entry validation failed for ${sanitizedId}: ${error93 instanceof Error?error93.message:String(error93)}`),null}}async function listStaleSummaryIds(directory,retentionDays,options){let summariesBasePath=validateSwarmPath(directory,"summaries"),retentionFiles=[];try{retentionFiles=readdirSync14(summariesBasePath).filter((name)=>name.endsWith(".json")&&/^S.+$/.test(name.slice(0,-5)))}catch{retentionFiles=[]}let cutoffTime=(options?.now??Date.now())-retentionDays*24*60*60*1000,stale=[];for(let filename of retentionFiles){let id=filename.slice(0,-5),relativePath2=path131.join("summaries",filename),summaryPath=validateSwarmPath(directory,relativePath2),content=await readSwarmFileAsync(directory,relativePath2);if(content===null)continue;try{let timestamp=JSON.parse(content).timestamp;if(typeof timestamp==="number"&&Number.isFinite(timestamp)&×tamp<cutoffTime||typeof timestamp!=="number"&&(()=>{try{return statSync45(summaryPath).mtimeMs<cutoffTime}catch{return!1}})())stale.push(id)}catch(error93){warn(`Failed to inspect summary ${id} for retention: ${error93 instanceof Error?error93.message:String(error93)}`)}}return stale}async function cleanupSummaries(directory,retentionDays,options){let staleIds=await listStaleSummaryIds(directory,retentionDays,options),deleted=[];for(let id of staleIds)try{rmSync14(validateSwarmPath(directory,path131.join("summaries",`${id}.json`))),deleted.push(id)}catch(error93){warn(`Failed to cleanup summary ${id}: ${error93 instanceof Error?error93.message:String(error93)}`)}return deleted}var SUMMARY_ID_REGEX;var init_manager3=__esm(()=>{init_utils2();init_caps();init_utils();init_bun_compat();init_swarm_artifact_cache();SUMMARY_ID_REGEX=/^S\d+$/});import*as fs76 from"node:fs";import*as path132 from"node:path";function subtreeNewestFileMtime(root,maxScan){let budget=maxScan,newest=null,stack=[root];while(stack.length>0){if(budget<=0)return Number.POSITIVE_INFINITY;let dir=stack.pop(),names;try{names=fs76.readdirSync(dir)}catch{return Number.POSITIVE_INFINITY}for(let name of names){if(budget<=0)return Number.POSITIVE_INFINITY;let entryPath=path132.join(dir,name),stat15;try{stat15=fs76.lstatSync(entryPath)}catch{continue}if(budget-=1,stat15.isSymbolicLink())continue;if(stat15.isDirectory()){stack.push(entryPath);continue}if(stat15.isFile()&&stat15.mtimeMs>(newest??-1/0))newest=stat15.mtimeMs}}return newest}function effectiveEntryMtime(entryPath,ownMtimeMs){let newest=subtreeNewestFileMtime(entryPath,SUBTREE_SCAN_CAP);if(newest===null)return ownMtimeMs;return newest}function listPruneCandidates(dir,maxScan,includeEntry=()=>!0){let candidates=[],refusedSymlinks=[],names;try{names=fs76.readdirSync(dir)}catch{return{candidates:[],refusedSymlinks:[]}}for(let name of names.slice(0,maxScan)){let entryPath=path132.join(dir,name);try{let stat15=fs76.lstatSync(entryPath);if(stat15.isSymbolicLink()){refusedSymlinks.push(name);continue}if(!includeEntry(name,stat15))continue;candidates.push({name,mtimeMs:stat15.isDirectory()?effectiveEntryMtime(entryPath,stat15.mtimeMs):stat15.mtimeMs})}catch{}}return{candidates,refusedSymlinks}}async function pruneDirectory(dir,opts){let now2=opts.now??Date.now(),maxScan=opts.maxScan??1e5,{candidates}=listPruneCandidates(dir,maxScan,opts.includeEntry);if(candidates.length===0)return 0;candidates.sort((a,b)=>a.mtimeMs===b.mtimeMs?a.name<b.name?-1:a.name>b.name?1:0:a.mtimeMs-b.mtimeMs);let cutoff=opts.maxAgeMs!==void 0?now2-opts.maxAgeMs:null,victims=[];for(let candidate of candidates){if(candidate.mtimeMs>now2)continue;if(cutoff!==null&&candidate.mtimeMs<cutoff)victims.push(candidate)}if(opts.maxEntries!==void 0){let keepNewest=opts.maxEntries,excess=candidates.length-keepNewest;for(let i=0;i<excess;i++){let candidate=candidates[i];if(candidate.mtimeMs>now2)continue;if(!victims.includes(candidate))victims.push(candidate)}}let pruned=0;if(opts.dryRun!==!0){for(let victim of victims)try{fs76.rmSync(path132.join(dir,victim.name),{recursive:!0,force:!0}),pruned+=1}catch{}return pruned}return victims.length}var SUBTREE_SCAN_CAP=2000;var init_dir_prune=()=>{};import*as fs77 from"node:fs";import*as path133 from"node:path";function familiesFor(swarmRoot,now2){let age=(days)=>days*DAY_MS,f=(label,rel,opts)=>({label,dir:path133.join(swarmRoot,rel),maxAgeMs:opts.maxAgeDays!==void 0?age(opts.maxAgeDays):void 0,maxEntries:opts.maxEntries,includeEntry:opts.includeEntry});return[f("pr-feedback-events","pr-feedback-events",{maxAgeDays:30}),f("pr-workflow-gates","pr-workflow-gates",{maxAgeDays:30,includeEntry:isPrWorkflowGateStateProjection}),f("pr-workflow-gate-sidecars","pr-workflow-gates",{maxAgeDays:30,includeEntry:isPrWorkflowGateSidecar}),f("pr-review-reentry-shadows",path133.join("pr-review","reentry-authorizations"),{maxAgeDays:30}),f("pr-review-run-artifacts","pr-review",{maxAgeDays:30,maxEntries:PR_REVIEW_KEEP_NEWEST_RUNS}),f("review-receipts","review-receipts",{maxAgeDays:30,maxEntries:REVIEW_RECEIPTS_KEEP_NEWEST}),f("lane-results","lane-results",{maxAgeDays:30,maxEntries:LANE_RESULTS_KEEP_NEWEST_BATCHES}),f("capsules","capsules",{maxAgeDays:30}),f("runs","runs",{maxAgeDays:30}),f("skills-proposals",path133.join("skills","proposals"),{maxAgeDays:14}),f("skill-improver-proposals",path133.join("skill-improver","proposals"),{maxAgeDays:30}),f("recovery","recovery",{maxAgeDays:30})]}async function runRetentionSweep(projectRoot,options={}){if(options.enabled===!1)return{pruned:{},disabled:!0,errors:{}};let now2=options.now??Date.now(),dryRun=options.dryRun===!0,swarmRoot=path133.join(projectRoot,".swarm"),result={pruned:{},dryRun,errors:{}};try{let resolvedRoot=fs77.realpathSync(projectRoot),resolvedSwarm=fs77.realpathSync(swarmRoot);if(!resolvedSwarm.startsWith(resolvedRoot+path133.sep)&&resolvedSwarm!==resolvedRoot)return result.errors.containment=".swarm resolves outside the project root; refusing sweep",result}catch(error93){if((typeof error93==="object"&&error93!==null&&"code"in error93?String(error93.code):"")!=="ENOENT")result.errors.containment=error93 instanceof Error?error93.message:String(error93);return result}let cancelled=(label)=>{if(options.shouldContinue&&!options.shouldContinue())return result.errors.sweep_cancelled=`sweep cancelled by shouldContinue token before ${label}`,!0;return!1};for(let family of familiesFor(swarmRoot,now2)){if(cancelled(family.label))return result;try{let pruned=await pruneDirectory(family.dir,{maxAgeMs:family.maxAgeMs,maxEntries:family.maxEntries,now:now2,dryRun,includeEntry:family.includeEntry});if(pruned>0)result.pruned[family.label]=pruned}catch(error93){result.errors[family.label]=error93 instanceof Error?error93.message:String(error93)}}if(cancelled("review-receipts-index"))return result;try{let dropped=await pruneDanglingReceiptIndexEntries(projectRoot,{dryRun});if(dropped>0)result.pruned["review-receipts-index"]=dropped}catch(error93){result.errors["review-receipts-index"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("epic-diagnostics"))return result;for(let[label,rel]of[["epic-divergence",path133.join("epic","divergence.jsonl")],["epic-calibration",path133.join("epic","calibration.json")]])try{let filePath=path133.join(swarmRoot,rel),stat15=await fs77.promises.stat(filePath).catch(()=>null);if(stat15&&stat15.mtimeMs<=now2&&stat15.mtimeMs<now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS){if(!dryRun)await fs77.promises.unlink(filePath).catch(()=>{return});result.pruned[label]=1}}catch(error93){result.errors[label]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("doc-drift-imported"))return result;try{let legacy=await fs77.promises.readdir(swarmRoot).then((names)=>names.filter((n)=>/^doc-drift-phase-\d+\.json\.imported$/.test(n))).catch(()=>[]),legacyPruned=0;for(let name of legacy){let filePath=path133.join(swarmRoot,name),stat15=await fs77.promises.stat(filePath).catch(()=>null);if(stat15&&stat15.mtimeMs<=now2&&stat15.mtimeMs<now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS){if(!dryRun)await fs77.promises.unlink(filePath).catch(()=>{return});legacyPruned+=1}}if(legacyPruned>0)result.pruned["doc-drift-imported"]=legacyPruned}catch(error93){result.errors["doc-drift-imported"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("legacy-ledger-archives"))return result;try{let names=(await fs77.promises.readdir(swarmRoot)).filter((name)=>/^plan-ledger\.legacy-archive\.[0-9a-f]{64}\.jsonl$/.test(name)),entries=(await Promise.all(names.map(async(name)=>{let filePath=path133.join(swarmRoot,name),stat15=await fs77.promises.lstat(filePath).catch(()=>null);return stat15?.isFile()&&!stat15.isSymbolicLink()?{name,filePath,mtimeMs:stat15.mtimeMs}:null}))).filter((entry)=>entry!==null).sort((a,b)=>b.mtimeMs-a.mtimeMs||a.name.localeCompare(b.name)),removed=0;for(let[index,entry]of entries.entries()){if(index<LEGACY_LEDGER_ARCHIVES_KEEP_NEWEST)continue;if(entry.mtimeMs>now2||entry.mtimeMs>=now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS)continue;if(!dryRun)await fs77.promises.unlink(entry.filePath).catch(()=>{return});removed++}if(removed>0)result.pruned["legacy-ledger-archives"]=removed}catch(error93){result.errors["legacy-ledger-archives"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("evolution-terminal-candidates"))return result;try{let evolutionRoot=path133.join(swarmRoot,"evolution","skills"),pruned=await pruneEvolutionCandidates(evolutionRoot,now2,dryRun);if(pruned>0)result.pruned["evolution-terminal-candidates"]=pruned}catch(error93){result.errors["evolution-terminal-candidates"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("evolution-scratch"))return result;try{let evalPruned=0;if(await walkEvolution(path133.join(swarmRoot,"evolution","skills"),async(entryPath,stat15)=>{let base=path133.basename(entryPath),isEvalInput=base==="_eval-input"&&stat15.isDirectory(),isQuarantine=base.startsWith("lifecycle-quarantine.");if(!isEvalInput&&!isQuarantine)return;let horizon=isEvalInput?7*DAY_MS:DEFAULT_FAMILY_AGE_DAYS*DAY_MS;if(stat15.mtimeMs<=now2&&stat15.mtimeMs<now2-horizon){if(!dryRun)fs77.rmSync(entryPath,{recursive:!0,force:!0});evalPruned+=1}}),evalPruned>0)result.pruned["evolution-scratch"]=evalPruned}catch(error93){result.errors["evolution-scratch"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("summaries-retention"))return result;try{let retentionDays=options.summariesRetentionDays??DEFAULT_SUMMARIES_RETENTION_DAYS,before=dryRun?await countStaleSummaries(projectRoot,retentionDays,now2):0;if(dryRun){if(before>0)result.pruned["summaries-retention"]=before}else{let deleted=await cleanupSummaries(projectRoot,retentionDays,{now:now2});if(deleted.length>0)result.pruned["summaries-retention"]=deleted.length}}catch(error93){result.errors["summaries-retention"]=error93 instanceof Error?error93.message:String(error93)}if(Object.keys(result.errors).length>0)log("retention sweep: per-family failures (non-fatal)",result.errors);return result}async function candidateIsTerminal(candidateDir2){let ledger=await readTailJsonlDetailed(path133.join(candidateDir2,"lifecycle.jsonl"),{maxEntries:1,maxBytes:65536});if(!ledger.tailTruncated){let last=ledger.records[ledger.records.length-1];if(last){let state=last.toState??last.type??"";if(isTerminal2(state))return!0}}try{let stateJson=JSON.parse(await fs77.promises.readFile(path133.join(candidateDir2,"state.json"),"utf-8"));if(isTerminal2(stateJson.state??null))return!0}catch{}return!1}async function pruneEvolutionCandidates(evolutionRoot,now2,dryRun){let pruned=0,skillDirs=await fs77.promises.readdir(evolutionRoot).catch(()=>[]);for(let skillSlug of skillDirs){let skillDir=path133.join(evolutionRoot,skillSlug);if(!await isRealDirectory(skillDir))continue;let candidates=await fs77.promises.readdir(skillDir).catch(()=>[]);for(let candidateId of candidates){let candidateDir2=path133.join(skillDir,candidateId),stat15=await fs77.promises.stat(candidateDir2).catch(()=>null);if(!stat15||!stat15.isDirectory())continue;let newest=subtreeNewestFileMtime(candidateDir2,SUBTREE_SCAN_CAP),effectiveMtime=newest===null?stat15.mtimeMs:newest;if(effectiveMtime>now2)continue;let ageMs=now2-effectiveMtime;if(!(await candidateIsTerminal(candidateDir2)&&ageMs>DEFAULT_FAMILY_AGE_DAYS*DAY_MS||ageMs>EVOLUTION_BACKSTOP_AGE_DAYS*DAY_MS))continue;if(!dryRun)fs77.rmSync(candidateDir2,{recursive:!0,force:!0});pruned+=1}}return pruned}async function walkEvolution(root,visit){let entries=await fs77.promises.readdir(root).catch(()=>[]);for(let name of entries){let entryPath=path133.join(root,name),stat15=await fs77.promises.lstat(entryPath).catch(()=>null);if(!stat15||stat15.isSymbolicLink())continue;if(stat15.isDirectory())await walkEvolution(entryPath,visit);await visit(entryPath,stat15)}}async function isRealDirectory(dir){try{let stat15=fs77.lstatSync(dir);return stat15.isDirectory()&&!stat15.isSymbolicLink()}catch{return!1}}async function countStaleSummaries(projectRoot,retentionDays,now2){return(await listStaleSummaryIds(projectRoot,retentionDays,{now:now2})).length}var DAY_MS=86400000,DEFAULT_FAMILY_AGE_DAYS=30,DEFAULT_SUMMARIES_RETENTION_DAYS=7,EVOLUTION_BACKSTOP_AGE_DAYS=90,PR_REVIEW_KEEP_NEWEST_RUNS=50,LANE_RESULTS_KEEP_NEWEST_BATCHES=100,REVIEW_RECEIPTS_KEEP_NEWEST=1000,LEGACY_LEDGER_ARCHIVES_KEEP_NEWEST=16,PR_WORKFLOW_GATE_STATE_STEM="[A-Za-z0-9_.-]+-[0-9a-f]{12}",PR_WORKFLOW_GATE_STATE_NAME,PR_WORKFLOW_GATE_SIDECAR_NAME,isPrWorkflowGateStateProjection=(name,stat15)=>stat15.isFile()&&PR_WORKFLOW_GATE_STATE_NAME.test(name),isPrWorkflowGateSidecar=(name,stat15)=>stat15.isFile()&&PR_WORKFLOW_GATE_SIDECAR_NAME.test(name);var init_sweep=__esm(()=>{init_review_receipt();init_lifecycle();init_manager3();init_logger();init_dir_prune();init_jsonl_cap();PR_WORKFLOW_GATE_STATE_NAME=new RegExp(`^${PR_WORKFLOW_GATE_STATE_STEM}\\.json$`),PR_WORKFLOW_GATE_SIDECAR_NAME=new RegExp(`^${PR_WORKFLOW_GATE_STATE_STEM}\\.json(?:\\.imported(?:\\.[0-9]+)?|\\.sqlite-projection)$`)});import{closeSync as closeSync21,existsSync as existsSync66,fsyncSync as fsyncSync8,mkdirSync as mkdirSync41,openSync as openSync21,unlinkSync as unlinkSync25}from"node:fs";import{rename as fsRename}from"node:fs/promises";import*as path134 from"node:path";async function renameWithTransientRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS;attempt++)try{await _internals110.rename(tempPath,targetPath);return}catch(error93){lastError=error93;let code=error93.code;if(code==="ENOENT"&&attempt>0&&!existsSync66(tempPath)&&existsSync66(targetPath))return;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS-1)await new Promise((resolve59)=>setTimeout(resolve59,SNAPSHOT_RENAME_RETRY_DELAY_MS))}throw lastError}function serializeAgentSession(s){let gateLog={},rawGateLog=s.gateLog??new Map;for(let[taskId,gates]of rawGateLog)gateLog[taskId]=Array.from(gates??[]);let reviewerCallCount={},rawReviewerCallCount=s.reviewerCallCount??new Map;for(let[phase,count]of rawReviewerCallCount)reviewerCallCount[String(phase)]=count;let partialGateWarningsIssuedForTask=Array.from(s.partialGateWarningsIssuedForTask??new Set),completionGateWarnedForTask=Array.from(s.completionGateWarnedForTask??new Set),catastrophicPhaseWarnings=Array.from(s.catastrophicPhaseWarnings??new Set),phaseAgentsDispatched=Array.from(s.phaseAgentsDispatched??new Set),lastCompletedPhaseAgentsDispatched=Array.from(s.lastCompletedPhaseAgentsDispatched??new Set),stageBCompletion={};if(s.stageBCompletion)for(let[taskId,agents]of s.stageBCompletion)stageBCompletion[taskId]=Array.from(agents);let modifiedFilesByTask=Object.create(null);for(let[taskId,files]of s.modifiedFilesByTask??new Map)modifiedFilesByTask[taskId]=[...files];let windows={},rawWindows=s.windows??{};for(let[key2,win]of Object.entries(rawWindows))windows[key2]={id:win.id,agentName:win.agentName,startedAtMs:win.startedAtMs,toolCalls:win.toolCalls,consecutiveErrors:win.consecutiveErrors,hardLimitHit:win.hardLimitHit,lastSuccessTimeMs:win.lastSuccessTimeMs,recentToolCalls:win.recentToolCalls,warningIssued:win.warningIssued,warningReason:win.warningReason,transientRetryCount:win.transientRetryCount??0};return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,...s.turboStrategy!==void 0&&{turboStrategy:s.turboStrategy},leanTurboActive:s.leanTurboActive??!1,...s.leanTurboCurrentPhase!==void 0&&{leanTurboCurrentPhase:s.leanTurboCurrentPhase},epicModeActive:s.epicModeActive??!1,gateLog,reviewerCallCount,lastGateFailure:s.lastGateFailure??null,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],taskWorkflowStates:Object.fromEntries(s.taskWorkflowStates??new Map),...Object.keys(modifiedFilesByTask).length>0&&{modifiedFilesByTask},...s.scopeViolationDetected!==void 0&&{scopeViolationDetected:s.scopeViolationDetected},model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,sessionRehydratedAt:s.sessionRehydratedAt??0,...Object.keys(stageBCompletion).length>0&&{stageBCompletion},...s.maxConcurrencyOverride!==void 0&&{maxConcurrencyOverride:s.maxConcurrencyOverride},...s.autoProceedOverride!==void 0&&{autoProceedOverride:s.autoProceedOverride},...s.autoProceedNudgeDone!==void 0&&{autoProceedNudgeDone:s.autoProceedNudgeDone},...s.cachedCohortId!==void 0&&{cachedCohortId:s.cachedCohortId},...s.lastObservedModel!==void 0&&{lastObservedModel:s.lastObservedModel},...s.lastObservedProviderID!==void 0&&{lastObservedProviderID:s.lastObservedProviderID}}}async function writeSnapshot2(directory,state){try{let{ensureSnapshotCoordinationReady}=await Promise.resolve().then(() => (init_snapshot_coordination_init(),exports_snapshot_coordination_init));await ensureSnapshotCoordinationReady(directory);let snapshot={version:3,writtenAt:Date.now(),workflowSchema:TASK_WORKFLOW_SCHEMA_MARKER,toolAggregates:Object.fromEntries(state.toolAggregates),activeAgent:Object.fromEntries([...state.activeAgent].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),delegationChains:Object.fromEntries([...state.delegationChains].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),agentSessions:{}};for(let[sessionId,sessionState]of state.agentSessions){if(!isSnapshotSessionOwnedLocally(sessionId))continue;snapshot.agentSessions[sessionId]=serializeAgentSession(sessionState)}writeSnapshotRows(directory,snapshot,{onlyLocallyOwnedSessions:!0});let canonicalSnapshot=readSnapshotRows(directory)??snapshot;await writeSnapshotProjection(directory,canonicalSnapshot)}catch(error93){log("[snapshot-writer] write failed",{error:error93 instanceof Error?error93.message:String(error93)})}}async function writeSnapshotProjection(directory,snapshot){let content=JSON.stringify(snapshot,null,2),resolvedPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),dir=path134.dirname(resolvedPath);mkdirSync41(dir,{recursive:!0});let tempPath=`${resolvedPath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;await bunWrite(tempPath,content);try{let fd=openSync21(tempPath,"r+");try{fsyncSync8(fd)}finally{closeSync21(fd)}}catch{}try{await renameWithTransientRetry(tempPath,resolvedPath)}finally{try{unlinkSync25(tempPath)}catch{}}invalidateCachedArtifact(resolvedPath)}function createSnapshotWriterHook(directory){return(_input,_output)=>{return _writeInFlight=_writeInFlight.then(()=>_internals110.writeSnapshot(directory,swarmState),()=>_internals110.writeSnapshot(directory,swarmState)),_writeInFlight}}async function flushPendingSnapshot(directory){_writeInFlight=_writeInFlight.then(()=>_internals110.writeSnapshot(directory,swarmState),()=>_internals110.writeSnapshot(directory,swarmState)),await _writeInFlight}var SNAPSHOT_PROJECTION_FILE="session/state.sqlite-projection.json",_writeInFlight,SNAPSHOT_RENAME_MAX_ATTEMPTS=3,SNAPSHOT_RENAME_RETRY_DELAY_MS=50,_internals110;var init_snapshot_writer=__esm(()=>{init_gate_evidence();init_utils2();init_state2();init_utils();init_bun_compat();init_swarm_artifact_cache();init_snapshot_store();_writeInFlight=Promise.resolve();_internals110={writeSnapshot:writeSnapshot2,createSnapshotWriterHook,flushPendingSnapshot,rename:fsRename}});import{renameSync as renameSync29}from"node:fs";function deserializeTaskWorkflowStates(raw){let m=new Map;if(!raw||typeof raw!=="object")return m;for(let[taskId,stateVal]of Object.entries(raw))if(VALID_TASK_WORKFLOW_STATES.includes(stateVal))m.set(taskId,stateVal);return m}function deserializeModifiedFilesByTask(raw){let entries=new Map;if(!raw||typeof raw!=="object")return entries;let serializedEntries=Object.entries(raw);if(serializedEntries.length>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS)return entries;for(let[taskId,files]of serializedEntries){if(!taskId.trim()||!Array.isArray(files))continue;let validFiles=files.filter((file3)=>typeof file3==="string"&&file3.length>0);entries.set(taskId,[...new Set(validFiles)])}return entries}function deserializeAgentSession(s){let lastGateFailure=s.lastGateFailure?{tool:s.lastGateFailure.tool,taskId:s.lastGateFailure.taskId,timestamp:s.lastGateFailure.timestamp,...typeof s.lastGateFailure.code==="string"&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.lastGateFailure.code)&&{code:s.lastGateFailure.code}}:null,taskWorkflowStates=deserializeTaskWorkflowStates(s.taskWorkflowStates),modifiedFilesByTask=deserializeModifiedFilesByTask(s.modifiedFilesByTask),gateLog=new Map;if(s.gateLog)for(let[taskId,gates]of Object.entries(s.gateLog))gateLog.set(taskId,new Set(gates??[]));let reviewerCallCount=new Map;if(s.reviewerCallCount)for(let[phase,count]of Object.entries(s.reviewerCallCount)){let numPhase=Number(phase);if(Number.isFinite(numPhase))reviewerCallCount.set(numPhase,count)}let partialGateWarningsIssuedForTask=new Set(s.partialGateWarningsIssuedForTask??[]),completionGateWarnedForTask=new Set(s.completionGateWarnedForTask??[]),catastrophicPhaseWarnings=new Set(s.catastrophicPhaseWarnings??[]),phaseAgentsDispatched=new Set(s.phaseAgentsDispatched??[]),lastCompletedPhaseAgentsDispatched=new Set(s.lastCompletedPhaseAgentsDispatched??[]),stageBCompletion=new Map;if(s.stageBCompletion)for(let[taskId,agents]of Object.entries(s.stageBCompletion))stageBCompletion.set(taskId,new Set(agents));let windows={};for(let[key2,win]of Object.entries(s.windows??{})){if(!win||typeof win!=="object")continue;windows[key2]={...win,transientRetryCount:"transientRetryCount"in win?win.transientRetryCount??0:0}}return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,turboStrategy:s.turboStrategy==="lean"||s.turboStrategy==="standard"?s.turboStrategy:void 0,leanTurboActive:s.leanTurboActive??!1,leanTurboCurrentPhase:typeof s.leanTurboCurrentPhase==="number"?s.leanTurboCurrentPhase:void 0,epicModeActive:s.epicModeActive??!1,gateLog,reviewerCallCount,lastGateFailure,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],taskWorkflowStates,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:s.scopeViolationDetected,modifiedFilesByTask,modifiedFilesThisCoderTask:s.currentTaskId&&s.currentTaskId.trim()!==""&&modifiedFilesByTask.has(s.currentTaskId)?[...modifiedFilesByTask.get(s.currentTaskId)??[]]:[],loopDetectionWindow:[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,maxConcurrencyOverride:typeof s.maxConcurrencyOverride==="number"?Math.min(64,Math.max(1,s.maxConcurrencyOverride)):void 0,autoProceedOverride:s.autoProceedOverride,autoProceedNudgeDone:s.autoProceedNudgeDone,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,sessionRehydratedAt:s.sessionRehydratedAt??0,stageBCompletion,prSubscriptions:new Map,cachedCohortId:typeof s.cachedCohortId==="string"?s.cachedCohortId:void 0,lastObservedModel:typeof s.lastObservedModel==="string"?s.lastObservedModel:void 0,lastObservedProviderID:typeof s.lastObservedProviderID==="string"?s.lastObservedProviderID:void 0}}async function readSnapshot(directory){for(let relativePath2 of[SNAPSHOT_PROJECTION_FILE,"session/state.json"])try{let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())continue;let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3){try{let quarantinePath=validateSwarmPath(directory,`${relativePath2}.quarantine`);renameSync29(resolvedPath,quarantinePath)}catch{}continue}return parsed}catch{}return null}async function readSnapshotFileStrict(directory,relativePath2){let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())throw Error(`snapshot ${relativePath2} is empty`);let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3)throw Error(`snapshot ${relativePath2} has an unsupported version`);if(!parsed.toolAggregates||!parsed.activeAgent||!parsed.delegationChains||!parsed.agentSessions)throw Error(`snapshot ${relativePath2} has an invalid shape`);return parsed}async function rehydrateState(snapshot,directory){if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);if(swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.agentSessions.clear(),snapshot.toolAggregates)for(let[key2,value]of Object.entries(snapshot.toolAggregates))swarmState.toolAggregates.set(key2,value);let now2=Date.now();if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS)session[field.name]=field.resetValue;if(session.fullAutoMode){let runStillActive=!1;if(directory)try{runStillActive=loadFullAutoRunState(directory,sessionId)?.status==="running"}catch{runStillActive=!1}if(!runStillActive)session.fullAutoMode=!1}swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key2,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key2))swarmState.activeAgent.set(key2,value)}if(snapshot.delegationChains){for(let[key2,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key2))swarmState.delegationChains.set(key2,value)}}async function loadSnapshot(directory){try{await buildRehydrationCache(directory);let snapshot=await readSnapshot(directory);if(snapshot!==null){await rehydrateState(snapshot,directory);for(let session of swarmState.agentSessions.values())applyRehydrationCache(session)}}catch{}}var TRANSIENT_SESSION_FIELDS,VALID_TASK_WORKFLOW_STATES;var init_snapshot_reader=__esm(()=>{init_state3();init_utils2();init_state2();init_bun_compat();init_logger();init_snapshot_writer();TRANSIENT_SESSION_FIELDS=[{name:"revisionLimitHit",resetValue:!1},{name:"coderRevisions",resetValue:0},{name:"selfFixAttempted",resetValue:!1},{name:"lastGateFailure",resetValue:null},{name:"architectWriteCount",resetValue:0},{name:"selfCodingWarnedAtCount",resetValue:0},{name:"pendingAdvisoryMessages",resetValue:[]},{name:"model_fallback_index",resetValue:0},{name:"modelFallbackExhausted",resetValue:!1},{name:"scopeViolationDetected",resetValue:!1},{name:"delegationActive",resetValue:!1},{name:"autoProceedOverride",resetValue:void 0},{name:"autoProceedNudgeDone",resetValue:void 0}],VALID_TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"]});var exports_snapshot_coordination_init={};__export(exports_snapshot_coordination_init,{startSnapshotCoordinationInitialization:()=>startSnapshotCoordinationInitialization,retrySnapshotCoordinationInitialization:()=>retrySnapshotCoordinationInitialization,markSnapshotCoordinationClosing:()=>markSnapshotCoordinationClosing,getSnapshotCoordinationStatus:()=>getSnapshotCoordinationStatus,ensureSnapshotCoordinationReady:()=>ensureSnapshotCoordinationReady,closeSnapshotCoordinationInitialization:()=>closeSnapshotCoordinationInitialization,beginSnapshotCoordinationReset:()=>beginSnapshotCoordinationReset,_snapshotCoordinationInternals:()=>_snapshotCoordinationInternals});import{createHash as createHash59,randomUUID as randomUUID21}from"node:crypto";import{existsSync as existsSync67,readFileSync as readFileSync45,renameSync as renameSync30}from"node:fs";function isRetryableArchiveError(error93){let code=error93?.code;return code==="EBUSY"||code==="EPERM"||code==="EACCES"}async function archiveLegacySnapshotIfPresent(legacyPath,expectedSnapshot){if(!existsSync67(legacyPath))return;if(expectedSnapshot)try{if(JSON.stringify(JSON.parse(readFileSync45(legacyPath,"utf8")))!==JSON.stringify(expectedSnapshot)){advisoryWarn("[opencode-swarm] Legacy snapshot changed after SQLite coordination; preserving it for explicit recovery.");return}}catch{return}let canonicalArchive=`${legacyPath}.imported`,archivePath=existsSync67(canonicalArchive)?`${canonicalArchive}.${randomUUID21()}`:canonicalArchive,lastError;for(let attempt=1;attempt<=ARCHIVE_RETRY_ATTEMPTS;attempt+=1)try{_snapshotCoordinationInternals.renameLegacySnapshot(legacyPath,archivePath);return}catch(error93){if(lastError=error93,!isRetryableArchiveError(error93)||attempt===ARCHIVE_RETRY_ATTEMPTS)break;await new Promise((resolve59)=>setTimeout(resolve59,ARCHIVE_RETRY_DELAY_MS))}advisoryWarn(`[opencode-swarm] SQLite snapshot is authoritative, but the legacy shadow could not be archived: ${lastError instanceof Error?lastError.message:String(lastError)}`)}function evictSettledEntries(){while(entries.size>=MAX_READY_ROOTS){let victim=[...entries].find(([,entry])=>entry.settled);if(!victim)return!1;entries.delete(victim[0])}return!0}async function initializeSnapshotCoordination(directory){let legacyArchiveAttempted=!1,snapshot=readSnapshotRows(directory);if(!snapshot){let legacyPath=validateSwarmPath(directory,"session/state.json"),projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),source=existsSync67(projectionPath)?SNAPSHOT_PROJECTION_FILE:existsSync67(legacyPath)?"session/state.json":null;if(source){let candidate=await readSnapshotFileStrict(directory,source),serialized2=JSON.stringify(candidate),outcome=importSnapshotRowsOnce(directory,candidate,createHash59("sha256").update(serialized2).digest("hex"),source);if(snapshot=readSnapshotRows(directory),outcome==="imported"&&source==="session/state.json")legacyArchiveAttempted=!0,await archiveLegacySnapshotIfPresent(legacyPath,candidate)}}if(!snapshot)return;if(!legacyArchiveAttempted)await archiveLegacySnapshotIfPresent(validateSwarmPath(directory,"session/state.json"),snapshot);await rehydrateState(snapshot,directory);for(let session of swarmState.agentSessions.values())applyRehydrationCache(session);try{await _snapshotCoordinationInternals.writeProjection(directory,snapshot)}catch(error93){advisoryWarn(`[opencode-swarm] SQLite snapshot is ready, but its compatibility projection could not be written: ${error93 instanceof Error?error93.message:String(error93)}`)}}function startSnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),existing=entries.get(root);if(existing?.state==="closing")return Promise.reject(Error("coordination initialization is closing for reset-session"));if(existing&&!existing.settled)return existing.underlying;if(existing?.state==="succeeded")return existing.underlying;if(!evictSettledEntries()){let error93=Error(`SQLite snapshot coordination capacity exhausted (${MAX_READY_ROOTS} unsettled roots)`);return advisoryWarn(`[opencode-swarm] ${error93.message}; initialization refused.`),Promise.reject(error93)}let attemptId=nextAttemptId++,generation=(existing?.generation??0)+1,entry={attemptId,generation,state:"running",settled:!1,underlying:Promise.resolve()},underlying=_snapshotCoordinationInternals.initialize(root).then(()=>{if(entries.get(root)===entry&&entry.state!=="closing")entry.state="succeeded"}).catch((error93)=>{throw entry.state="failed",entry.error=error93 instanceof Error?error93.message:String(error93),error93}).finally(()=>{entry.settled=!0});return entry.underlying=underlying,entries.set(root,entry),withTimeout(underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization timed out")).catch((error93)=>{if(!entry.settled&&entries.get(root)===entry)entry.state="timed_out",entry.error=error93 instanceof Error?error93.message:String(error93),advisoryWarn("[opencode-swarm] SQLite coordination initialization is still running; authority operations remain fail-closed.")}),underlying}async function ensureSnapshotCoordinationReady(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(!entry)return startSnapshotCoordinationInitialization(root);if(entry.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry.state==="timed_out"&&!entry.settled)throw Error("coordination initialization remains unsettled after timeout");if(await entry.underlying,entry.state!=="succeeded")throw Error(entry.error??"coordination initialization failed")}function retrySnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(entry?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry&&!entry.settled)throw Error("coordination initialization is still unsettled; recovery refused");return entries.delete(root),startSnapshotCoordinationInitialization(root)}function getSnapshotCoordinationStatus(directory){let entry=entries.get(canonicalProjectKey(directory));if(!entry)return{state:"idle",settled:!0};return{state:entry.state,attemptId:entry.attemptId,generation:entry.generation,settled:entry.settled,...entry.error?{error:entry.error.slice(0,512)}:{}}}async function beginSnapshotCoordinationReset(directory){let root=canonicalProjectKey(directory),prior=entries.get(root),closeError,priorUnsettled=!1;if(prior){prior.state="closing";try{await withTimeout(prior.underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization close timed out"))}catch(error93){if(closeError=error93 instanceof Error?error93:Error(String(error93)),priorUnsettled=!prior.settled,priorUnsettled)prior.underlying.catch(()=>{return})}}let guard={attemptId:nextAttemptId++,generation:(prior?.generation??0)+1,state:"closing",settled:!0,underlying:Promise.resolve(),...closeError?{error:closeError.message}:{}};entries.set(root,guard);let released=!1;return{release:()=>{if(released)return;released=!0;let removeGuard=()=>{if(entries.get(root)===guard)entries.delete(root)};if(!prior||prior.settled){removeGuard();return}prior.underlying.then(removeGuard,removeGuard)},...closeError?{closeError}:{},...priorUnsettled?{priorUnsettled:!0}:{}}}async function closeSnapshotCoordinationInitialization(directory){let guard=await beginSnapshotCoordinationReset(directory);try{if(guard.closeError)throw guard.closeError}finally{guard.release()}}function markSnapshotCoordinationClosing(directory){let entry=entries.get(canonicalProjectKey(directory));if(entry)entry.state="closing"}var READY_TIMEOUT_MS=1e4,MAX_READY_ROOTS=32,ARCHIVE_RETRY_ATTEMPTS=3,ARCHIVE_RETRY_DELAY_MS=25,entries,nextAttemptId=1,_snapshotCoordinationInternals;var init_snapshot_coordination_init=__esm(()=>{init_canonical_project();init_utils2();init_warning_buffer();init_state2();init_timeout();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();entries=new Map;_snapshotCoordinationInternals={entries,initialize:initializeSnapshotCoordination,renameLegacySnapshot:renameSync30,writeProjection:writeSnapshotProjection,timeoutMs:READY_TIMEOUT_MS}});import*as fsSync15 from"node:fs";import{promises as fs78}from"node:fs";import path135 from"node:path";async function archiveCloseSummary(ctx,closeSummaryPath,summaryWritten){if(!summaryWritten||ctx.archiveStageFailed||!ctx.archiveDir)return;try{await fs78.copyFile(closeSummaryPath,path135.join(ctx.archiveDir,"close-summary.md"))}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to archive close-summary.md: ${msg}`),log("[close-command] Failed to archive close-summary.md:",error93)}}async function handleCloseCommand(directory,args2,options={}){let swarmDir=path135.join(directory,".swarm");try{if(fsSync15.lstatSync(swarmDir).isSymbolicLink())return"❌ Refused: .swarm/ is a symlink or junction. Refusing to operate on a redirected directory for safety."}catch(err){if(err?.code!=="ENOENT")throw err}let planPath=validateSwarmPath(directory,"plan.json"),planExists=!1,planData={title:path135.basename(directory)||"Ad-hoc session",phases:[]};try{let content=await fs78.readFile(planPath,"utf-8");planData=JSON.parse(content),planExists=!0}catch(error93){if(error93?.code!=="ENOENT")return`❌ Failed to read plan.json: ${error93 instanceof Error?error93.message:String(error93)}`;try{let recovered=(await peekPlanFromLedger(directory)).plan;if(recovered)planData=recovered,planExists=!0}catch(recoveryError){return`❌ Failed to recover plan from the authoritative ledger: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`}if(!planExists){if(!await fs78.access(swarmDir).then(()=>!0).catch(()=>!1))return`❌ No .swarm/ directory found in ${directory}. Run /swarm close from the project root, or run /swarm plan first.`}}if(args2.includes("--dry-run"))return _internals97.runFinalizeDryRun(directory,swarmDir,planData,planExists);let finalizeLock={acquired:!1};if(finalizeLock=await _internals97.acquireFinalizeLock(directory),!finalizeLock.acquired)return"❌ Another /swarm finalize is already running for this project. If you are certain no other run is active, wait for the lock to expire or remove the stale lock and retry.";try{if(await closeSnapshotCoordinationInitialization(directory),!planExists){let archiveDir=path135.join(swarmDir,"archive");try{if((await fs78.readdir(archiveDir)).some((entry)=>entry.startsWith("swarm-"))){if(![...ACTIVE_STATE_TO_CLEAN,...ACTIVE_STATE_DIRS_TO_CLEAN].some((entry)=>fsSync15.existsSync(path135.join(swarmDir,entry))))return`✅ Already finalized — nothing to do.
|
|
1481
1481
|
|
|
1482
1482
|
This project was already finalized in a previous /swarm close run. The plan has been archived and cleaned up. No further action is needed.`}}catch{}}let phases=planData.phases??[],inProgressPhases=phases.filter((p)=>p.status==="in_progress"),isForced=args2.includes("--force"),runSkillReview=args2.includes("--skill-review"),planAlreadyDone=!1;if(planExists)planAlreadyDone=phases.length>0&&phases.every((p)=>p.status==="complete"||p.status==="completed"||p.status==="blocked"||p.status==="closed");let{config:loadedConfig}=_internals97.loadPluginConfigWithMeta(directory),config3=KnowledgeConfigSchema.parse(loadedConfig.knowledge??{}),ctx={directory,swarmDir,planData,planExists,planAlreadyDone,config:config3,projectName:planData.title??"Unknown Project",warnings:[],closedPhases:[],closedTasks:[],sessionStart:void 0,isForced,runSkillReview,options,phases,inProgressPhases,curationSucceeded:!1,curationResult:void 0,allLessons:[],explicitLessons:[],retroLessons:[],knowledgeSkillHint:"",skillReviewSummary:"",postMortemSummary:"",sessionReflection:void 0,hivePromoted:0,sessionKnowledgeCreated:0,fallbackKnowledgeCreated:0,dedupDropped:0,dedupAvailable:!0,retroLessonTotal:0,fullAuto:!1,originalStatuses:new Map,guaranteeResult:{closedPhaseIds:[],closedTaskIds:[]},archiveResult:"",archivedFileCount:0,archivedActiveStateFiles:new Set,archivedActiveStateDirs:new Set,archiveFailureReasons:new Map,archiveResults:[],archiveStageFailed:!1,timestamp:"",archiveDir:"",archiveSuffix:"",args:args2};if(ctx.fullAuto=options.sessionID?_internals97.detectFullAuto(directory,options.sessionID):!1,await runFinalizeStage(ctx),ctx.terminalizationError)return`❌ Close paused before reward, archive, cleanup, teardown, and Git alignment because terminal plan/evidence reconciliation failed: ${ctx.terminalizationError}
|
|
1483
1483
|
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* - per-entry failures are swallowed (fail-open): one unreadable entry
|
|
24
24
|
* never aborts the family.
|
|
25
25
|
*/
|
|
26
|
+
import * as fs from 'node:fs';
|
|
26
27
|
export interface PruneDirectoryOptions {
|
|
27
28
|
/** Keep at most this many entries (newest by mtime). */
|
|
28
29
|
maxEntries?: number;
|
|
@@ -39,7 +40,10 @@ export interface PruneDirectoryOptions {
|
|
|
39
40
|
maxScan?: number;
|
|
40
41
|
/** Count victims without deleting (blast-radius rehearsal / dry_run). */
|
|
41
42
|
dryRun?: boolean;
|
|
43
|
+
/** Optional allow-list for entries eligible for age/count pruning. */
|
|
44
|
+
includeEntry?: PruneEntryFilter;
|
|
42
45
|
}
|
|
46
|
+
export type PruneEntryFilter = (name: string, stat: fs.Stats) => boolean;
|
|
43
47
|
export interface PruneCandidate {
|
|
44
48
|
name: string;
|
|
45
49
|
mtimeMs: number;
|
|
@@ -61,7 +65,7 @@ export declare function subtreeNewestFileMtime(root: string, maxScan: number): n
|
|
|
61
65
|
*/
|
|
62
66
|
export declare const SUBTREE_SCAN_CAP = 2000;
|
|
63
67
|
/** List bounded entries with effective mtimes; symlinked entries are collected separately and refused. */
|
|
64
|
-
export declare function listPruneCandidates(dir: string, maxScan: number): {
|
|
68
|
+
export declare function listPruneCandidates(dir: string, maxScan: number, includeEntry?: PruneEntryFilter): {
|
|
65
69
|
candidates: PruneCandidate[];
|
|
66
70
|
refusedSymlinks: string[];
|
|
67
71
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-swarm",
|
|
3
|
-
"version": "7.171.
|
|
3
|
+
"version": "7.171.2",
|
|
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",
|