opencode-swarm 7.152.0 → 7.152.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/.opencode/skills/{resume → swarm-resume}/SKILL.md +1 -1
  2. package/dist/cli/{config-doctor-4hctd61b.js → config-doctor-bbqmye7a.js} +2 -2
  3. package/dist/cli/{core-ea8xgnwy.js → core-fh4e6ex0.js} +1 -1
  4. package/dist/cli/{curation-policy-vb2f0vm7.js → curation-policy-nem98yc9.js} +4 -4
  5. package/dist/cli/{curator-krg3abzq.js → curator-909s9dvs.js} +23 -23
  6. package/dist/cli/{curator-llm-factory-6xnnfpt4.js → curator-llm-factory-462rysph.js} +23 -23
  7. package/dist/cli/{evidence-summary-service-dtjr30pg.js → evidence-summary-service-kqw4y0yr.js} +9 -9
  8. package/dist/cli/{gate-evidence-msnd1tda.js → gate-evidence-ycts62pj.js} +4 -4
  9. package/dist/cli/{guardrail-explain-nbgds0g0.js → guardrail-explain-7620hasq.js} +24 -24
  10. package/dist/cli/{guardrail-log-emgfqa5s.js → guardrail-log-e1tmdxxa.js} +3 -3
  11. package/dist/cli/{guardrail-reset-95jhw7rg.js → guardrail-reset-gdnaxxvb.js} +23 -23
  12. package/dist/cli/{hive-promoter-ch6h94j3.js → hive-promoter-d0xydg6r.js} +23 -23
  13. package/dist/cli/{index-h6tvj6nr.js → index-02ajc6d1.js} +2 -2
  14. package/dist/cli/{index-qdnj3nwt.js → index-0tfgn5x0.js} +6 -6
  15. package/dist/cli/{index-19tznm6x.js → index-26vyr198.js} +4 -4
  16. package/dist/cli/{index-cxt62pxj.js → index-29vd7v3e.js} +1 -1
  17. package/dist/cli/{index-h9tcawtm.js → index-2e1294d1.js} +42 -5
  18. package/dist/cli/{index-7afvf50d.js → index-3djxegsc.js} +1 -1
  19. package/dist/cli/{index-s85abenr.js → index-44xdtqz8.js} +1 -1
  20. package/dist/cli/{index-ngzc8db3.js → index-4tvvh7pn.js} +25 -25
  21. package/dist/cli/{index-ek6t1e9h.js → index-73pmnsjg.js} +1 -1
  22. package/dist/cli/{index-5th6khpe.js → index-79g6edht.js} +1 -1
  23. package/dist/cli/{index-30gf3exm.js → index-7fh82sm1.js} +1 -1
  24. package/dist/cli/{index-n8yastrw.js → index-96m8ckpq.js} +3 -3
  25. package/dist/cli/{index-sgdqbhkv.js → index-dn6yt0xg.js} +5 -5
  26. package/dist/cli/{index-nwpbfh8x.js → index-k3d919yf.js} +1 -1
  27. package/dist/cli/{index-kca6ng28.js → index-mken64yj.js} +1 -1
  28. package/dist/cli/{index-cgfjvkps.js → index-n0vc5b5t.js} +2 -2
  29. package/dist/cli/{index-rqc83msp.js → index-nd8tkb3g.js} +5 -5
  30. package/dist/cli/{index-r0bwks42.js → index-pvrap7xg.js} +1 -1
  31. package/dist/cli/{index-dsg5aqtj.js → index-q77e475x.js} +3 -3
  32. package/dist/cli/{index-n1j0cmj3.js → index-qqrdmaxq.js} +1 -1
  33. package/dist/cli/{index-trj11few.js → index-rq6aetkv.js} +4 -4
  34. package/dist/cli/{index-93rgk3ax.js → index-ryecg2st.js} +2 -2
  35. package/dist/cli/{index-9hc6ytb1.js → index-sg2sx2q7.js} +57 -57
  36. package/dist/cli/{index-dc7hh4d9.js → index-x6803sxh.js} +1 -1
  37. package/dist/cli/{index-fk3msss3.js → index-xyfdmrv7.js} +1 -1
  38. package/dist/cli/{index-1hbmy0ny.js → index-z8s2asdk.js} +2 -2
  39. package/dist/cli/{index-8nzqtv6b.js → index-z9fyd0d6.js} +2 -2
  40. package/dist/cli/index.js +23 -23
  41. package/dist/cli/{knowledge-escalator-n4nx4veq.js → knowledge-escalator-4egcr928.js} +9 -9
  42. package/dist/cli/{knowledge-events-t77r3zhe.js → knowledge-events-kdyv4jzn.js} +7 -7
  43. package/dist/cli/{knowledge-link-r6hfj2ep.js → knowledge-link-h8cwj7af.js} +3 -3
  44. package/dist/cli/{knowledge-store-w1v0041d.js → knowledge-store-dq3cvg53.js} +4 -4
  45. package/dist/cli/{knowledge-validator-6fcx0xdb.js → knowledge-validator-4bhtden9.js} +6 -6
  46. package/dist/cli/{runner-cmvgkbtp.js → runner-w81n9js3.js} +4 -4
  47. package/dist/cli/{scan-cursor-936pmv37.js → scan-cursor-2eezv81a.js} +5 -5
  48. package/dist/cli/{schema-exk5afyz.js → schema-v4qcqhek.js} +1 -1
  49. package/dist/cli/{scope-persistence-0ddz95ke.js → scope-persistence-y2r227r0.js} +5 -5
  50. package/dist/cli/{skill-generator-qk0mf7da.js → skill-generator-hhzxvb3h.js} +11 -11
  51. package/dist/cli/{worktree-isolation-2jvaebns.js → worktree-isolation-ve338ez6.js} +23 -23
  52. package/dist/config/bundled-skills.d.ts +10 -1
  53. package/dist/index.js +4 -4
  54. package/package.json +2 -2
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.152.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check: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:test-file-cap":"bun run scripts/check-test-file-cap.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:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.152.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"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check: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:test-file-cap":"bun run scripts/check-test-file-cap.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:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -160,7 +160,7 @@ This runtime resolution supersedes any planning-profile default in the base prom
160
160
  BALANCED ceremony: use durable QA and execution defaults without pausing for the full questionnaire. Do not require a spec solely as ceremony. Ask the user only about unresolved material ambiguity, destructive or high-risk authorization, or another decision only they can make. save_plan exact-binds the default QA profile; persist planning_profile: "balanced" in the execution profile. Follow persisted QA gates after save.`;return`${header}${precedence}
161
161
  STRICT ceremony: require an effective spec, run the complete clarification funnel, present the unified QA/execution questionnaire, wait for the user's answers, exact-bind those choices, and persist planning_profile: "strict". A locked legacy profile with no field uses this ceremony without materializing a new hash field.`}function resolveRepositoryDefaultPlanningProfile(config2){return config2.execution_mode==="strict"?"strict":"balanced"}function resolvePlanningProfile({directory,incomingExecutionProfile,existingExecutionProfile,resetStatuses,config:config2}){if(incomingExecutionProfile?.planning_profile)return{effective:incomingExecutionProfile.planning_profile,persisted:incomingExecutionProfile.planning_profile,source:"incoming"};let existingProfile=resetStatuses?void 0:existingExecutionProfile;if(existingProfile?.planning_profile)return{effective:existingProfile.planning_profile,persisted:existingProfile.planning_profile,source:"persisted"};if(existingProfile?.locked===!0)return{effective:"strict",persisted:void 0,source:"legacy_locked_default"};let loadedConfig=config2??loadPluginConfig(directory),repositoryDefault=resolveRepositoryDefaultPlanningProfile(loadedConfig);return{effective:repositoryDefault,persisted:repositoryDefault,source:"repository_default"}}function normalizeExecutionProfileForHash(profile){if(!profile)return;return{...profile,commit_after_each_completed_task:profile.commit_after_each_completed_task===!0?!0:void 0}}var init_planning_profile=__esm(()=>{init_loader()});import*as fsSync from"node:fs";import*as fs3 from"node:fs/promises";import*as path3 from"node:path";function sameStamp(a,b){return a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs&&a.size===b.size}async function getStamp(filePath){try{let stat3=await _internals4.stat(filePath);if(!stat3.isFile())return null;return{mtimeMs:stat3.mtimeMs,ctimeMs:stat3.ctimeMs,size:stat3.size}}catch{return stats.statFailureCount++,null}}function getStampSync(filePath){try{let stat3=_internals4.statSync(filePath);if(!stat3.isFile())return null;return{mtimeMs:stat3.mtimeMs,ctimeMs:stat3.ctimeMs,size:stat3.size}}catch{return stats.statFailureCount++,null}}function canStoreRead(before,after){return after!==null&&sameStamp(before,after)}function setBounded(cache2,key,value,cacheKind){cache2.set(key,value);while(cache2.size>MAX_CACHE_ENTRIES){let oldest=cache2.keys().next().value;if(oldest===void 0)break;if(cache2.delete(oldest),stats.evictionCount++,cacheKind==="text")stats.textEvictionCount++;else stats.parsedEvictionCount++}stats.textEntryCount=textCache.size,stats.parsedEntryCount=parsedCache.size}function cloneCachedValue(value){if(value===null||typeof value!=="object")return value;if(typeof structuredClone==="function")return structuredClone(value);return stats.cloneFallbackCount++,JSON.parse(JSON.stringify(value))}function readCachedTextFileSync(filePath,directRead){let cacheKey=path3.resolve(filePath),stamp=getStampSync(cacheKey);if(!stamp)return stats.textReadCount++,directRead();let cached2=textCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.textCacheHitCount++,cached2.value;stats.textCacheMissCount++,stats.textReadCount++;let value=directRead(),afterReadStamp=getStampSync(cacheKey);if(value!==null&&canStoreRead(stamp,afterReadStamp))setBounded(textCache,cacheKey,{...afterReadStamp,value},"text");return value}async function readCachedTextFile(filePath,directRead){let cacheKey=path3.resolve(filePath),stamp=await getStamp(cacheKey);if(!stamp)return stats.textReadCount++,directRead();let cached2=textCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.textCacheHitCount++,cached2.value;stats.textCacheMissCount++,stats.textReadCount++;let value=await directRead(),afterReadStamp=await getStamp(cacheKey);if(value!==null&&canStoreRead(stamp,afterReadStamp))setBounded(textCache,cacheKey,{...afterReadStamp,value},"text");return value}function readCachedParsedFileSync(filePath,namespace,readText,parse5){let resolvedPath=path3.resolve(filePath),cacheKey=`${resolvedPath}\x00${namespace}`,stamp=getStampSync(resolvedPath);if(!stamp){stats.parsedReadCount++;let content2=readText();if(content2===null)return null;return stats.parseCount++,parse5(content2)}let cached2=parsedCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.parsedCacheHitCount++,cloneCachedValue(cached2.value);stats.parsedCacheMissCount++,stats.parsedReadCount++;let content=readText();if(content===null)return null;stats.parseCount++;let value=parse5(content),afterReadStamp=getStampSync(resolvedPath);if(canStoreRead(stamp,afterReadStamp))setBounded(parsedCache,cacheKey,{...afterReadStamp,value},"parsed");return cloneCachedValue(value)}async function readCachedParsedFile(filePath,namespace,readText,parse5){let resolvedPath=path3.resolve(filePath),cacheKey=`${resolvedPath}\x00${namespace}`,stamp=await getStamp(resolvedPath);if(!stamp){stats.parsedReadCount++;let content2=await readText();if(content2===null)return null;return stats.parseCount++,parse5(content2)}let cached2=parsedCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.parsedCacheHitCount++,cloneCachedValue(cached2.value);stats.parsedCacheMissCount++,stats.parsedReadCount++;let content=await readText();if(content===null)return null;stats.parseCount++;let value=parse5(content),afterReadStamp=await getStamp(resolvedPath);if(canStoreRead(stamp,afterReadStamp))setBounded(parsedCache,cacheKey,{...afterReadStamp,value},"parsed");return cloneCachedValue(value)}function invalidateCachedArtifact(filePath){let resolvedPath=path3.resolve(filePath);textCache.delete(resolvedPath);let prefix=`${resolvedPath}\x00`;for(let key of parsedCache.keys())if(key.startsWith(prefix))parsedCache.delete(key)}function resetSwarmArtifactCache(){textCache.clear(),parsedCache.clear(),stats.textReadCount=0,stats.textCacheHitCount=0,stats.textCacheMissCount=0,stats.parsedReadCount=0,stats.parseCount=0,stats.parsedCacheHitCount=0,stats.parsedCacheMissCount=0,stats.statFailureCount=0,stats.evictionCount=0,stats.textEvictionCount=0,stats.parsedEvictionCount=0,stats.cloneFallbackCount=0,stats.textEntryCount=0,stats.parsedEntryCount=0}var MAX_CACHE_ENTRIES=128,textCache,parsedCache,stats,_internals4;var init_swarm_artifact_cache=__esm(()=>{textCache=new Map,parsedCache=new Map,stats={textReadCount:0,textCacheHitCount:0,textCacheMissCount:0,parsedReadCount:0,parseCount:0,parsedCacheHitCount:0,parsedCacheMissCount:0,statFailureCount:0,evictionCount:0,textEvictionCount:0,parsedEvictionCount:0,cloneFallbackCount:0,textEntryCount:0,parsedEntryCount:0};_internals4={stat:fs3.stat,statSync:fsSync.statSync}});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
162
162
 
163
- ${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path4 from"node:path";function bundledProjectSkillFileReference(slug){return`file:${BUNDLED_PROJECT_SKILL_ROOT}/${slug}/SKILL.md`}function describeBundledSkillSyncFailure(err){return`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${err instanceof Error?err.message:String(err)}`}async function isSymbolicLinkAsync(p){try{return(await fsp.lstat(p)).isSymbolicLink()}catch{return!1}}async function ensureNotSymlinkedDirectoryAsync(p){try{let stat4=await fsp.lstat(p);return stat4.isDirectory()&&!stat4.isSymbolicLink()}catch(err){return err.code==="ENOENT"}}async function pathExistsAsync(p){try{return await fsp.access(p),!0}catch{return!1}}async function collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeDir=""){let currentSource=path4.join(sourceDir,relativeDir),entries=await fsp.readdir(currentSource,{withFileTypes:!0});entries.sort((a,b)=>a.name.localeCompare(b.name));let files=[];for(let entry of entries){let relativeEntry=path4.join(relativeDir,entry.name),sourcePath=path4.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))throw Error("refusing to copy symlinked bundled skill entry");if(entry.isDirectory()){files.push(...await collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeEntry));continue}if(!entry.isFile())continue;let stat4=await fsp.stat(sourcePath),nextFiles=state.files+1,nextBytes=state.bytes+stat4.size;if(nextFiles>MAX_SKILL_FILES||nextBytes>MAX_SKILL_BYTES)throw Error("bundled skill package exceeds copy bounds");state.files=nextFiles,state.bytes=nextBytes,files.push({relativePath:relativeEntry})}return files}async function ensureContainedDirectoryAsync(rootDir,directory){let safeRoot=path4.resolve(rootDir),safeDirectory=path4.resolve(directory),relative2=path4.relative(safeRoot,safeDirectory);if(relative2.startsWith("..")||path4.isAbsolute(relative2))throw Error("bundled skill destination escaped its private root");try{let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;await fsp.mkdir(safeRoot,{recursive:!0});let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}let current=safeRoot;for(let segment of relative2.split(path4.sep).filter(Boolean)){current=path4.join(current,segment);try{let stat4=await fsp.lstat(current);if(stat4.isSymbolicLink()||!stat4.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;try{await fsp.mkdir(current)}catch(mkdirErr){if(mkdirErr.code!=="EEXIST")throw mkdirErr}let stat4=await fsp.lstat(current);if(stat4.isSymbolicLink()||!stat4.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}}}async function rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles=[]){let safeDestDir=path4.resolve(destDir),dirs=new Set;for(let copiedFile of copiedFiles){let resolvedFile=path4.resolve(copiedFile),relative2=path4.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path4.isAbsolute(relative2))continue;try{await fsp.rm(resolvedFile,{force:!0})}catch{}dirs.add(path4.dirname(resolvedFile))}for(let overwritten of overwrittenFiles.reverse()){let resolvedFile=path4.resolve(overwritten.path),relative2=path4.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path4.isAbsolute(relative2))continue;try{await fsp.writeFile(resolvedFile,overwritten.contents)}catch{}}for(let dir of[...dirs].sort((a,b)=>b.length-a.length)){let relative2=path4.relative(safeDestDir,path4.resolve(dir));if(relative2.startsWith("..")||path4.isAbsolute(relative2))continue;try{await fsp.rmdir(dir)}catch{}}}async function copyFileAtomicAsync(sourcePath,destPath){let tempPath=path4.join(path4.dirname(destPath),`.${path4.basename(destPath)}.tmp.${randomUUID()}`);try{await fsp.copyFile(sourcePath,tempPath),await fsp.rename(tempPath,destPath)}catch(err){try{await fsp.rm(tempPath,{force:!0})}catch{}throw err}}async function copyBundledDirectoryBoundedAsync(sourceDir,destDir){let files=await collectBundledSkillFilesBoundedAsync(sourceDir,{files:0,bytes:0}),copiedFiles=[],overwrittenFiles=[];try{for(let file2 of files){let sourcePath=path4.join(sourceDir,file2.relativePath),destPath=path4.join(destDir,file2.relativePath);if(await ensureContainedDirectoryAsync(destDir,path4.dirname(destPath)),await pathExistsAsync(destPath)){if(await isSymbolicLinkAsync(destPath))throw Error("refusing to overwrite symlinked bundled skill file");let[sourceContents,destContents]=await Promise.all([fsp.readFile(sourcePath),fsp.readFile(destPath)]);if(sourceContents.equals(destContents))continue;overwrittenFiles.push({path:destPath,contents:destContents}),await copyFileAtomicAsync(sourcePath,destPath)}else await copyFileAtomicAsync(sourcePath,destPath),copiedFiles.push(destPath)}}catch(err){throw await rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles),err}}async function performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet){try{let sourceRoot=path4.join(packageRoot,".opencode","skills"),swarmDir=path4.join(projectDirectory,".swarm"),skillsDir=path4.join(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT);if(!await ensureNotSymlinkedDirectoryAsync(sourceRoot))throw Error("refusing to copy symlinked bundled skill source root");if(!await ensureNotSymlinkedDirectoryAsync(swarmDir))return;if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;for(let slug of BUNDLED_PROJECT_SKILLS){let sourceDir=path4.join(sourceRoot,slug),sourceSkill=path4.join(sourceDir,"SKILL.md"),destDir=path4.join(skillsDir,slug);if(!await pathExistsAsync(sourceSkill))continue;if(!await ensureNotSymlinkedDirectoryAsync(sourceDir))throw Error("refusing to copy symlinked bundled skill directory");if(!await ensureNotSymlinkedDirectoryAsync(destDir))continue;await copyBundledDirectoryBoundedAsync(sourceDir,destDir),log("synchronized bundled skill",{slug:bundledProjectSkillFileReference(slug)})}}catch(err){let failureMsg=describeBundledSkillSyncFailure(err);if(quiet)advisoryWarn(failureMsg);else console.warn(failureMsg)}}async function syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){let syncKey=path4.resolve(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT),existing=inFlightSyncs.get(syncKey);if(existing)return existing;if(inFlightSyncs.size>=MAX_IN_FLIGHT_SYNCS){log("skipping bundled skill sync because the in-flight limit was reached",{limit:MAX_IN_FLIGHT_SYNCS});return}let syncPromise=performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet).finally(()=>{if(inFlightSyncs.get(syncKey)===syncPromise)inFlightSyncs.delete(syncKey)});return inFlightSyncs.set(syncKey,syncPromise),syncPromise}var BUNDLED_PROJECT_SKILLS,BUNDLED_PROJECT_SKILL_ROOT=".swarm/bundled-skills",MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000,MAX_IN_FLIGHT_SYNCS=64,inFlightSyncs;var init_bundled_skills=__esm(()=>{init_warning_buffer();init_logger();BUNDLED_PROJECT_SKILLS=["brainstorm","specify","clarify-spec","resume","clarify","discover","consult","pre-phase-briefing","council","deep-dive","deep-research","codebase-review-swarm","swarm-implement","design-docs","swarm-pr-review","swarm","swarm-pr-feedback","swarm-pr-subscribe","swarm-ci-monitor","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr","ci-failure-batching","gate-attribution","merge-queue-readiness","skill-edit-validation","worktree-retry-cleanup","test-file-split","fork-pr-operations","parallel-work-check","ci-fix-monitor","issue-tracer","orchestrating-subagents","durable-session-state"];inFlightSyncs=new Map});function formatCandidateHeader(family){return["[CANDIDATE]",...CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name)].join(" | ")}function formatCleanTemplate(family){return["[CLEAN]",family==="base_explorer"?"lane":"micro_lane","coverage_scope","evidence"].join(" | ")}function candidateHeaderFamily(fields){if(fields[0]?.trim()!=="[CANDIDATE]")return null;let normalized=fields.slice(1).map((field)=>field.trim());for(let family of["base_explorer","micro_lane"]){let canonicalHeaderFields=CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name);if(normalized.length===canonicalHeaderFields.length&&canonicalHeaderFields.every((name,index)=>normalized[index]===name))return family}return null}function selectCandidateHeader(lines){let markerlessFallback=null;for(let[lineIndex,line]of lines.entries()){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());if(fields.length<2||!fields.some(Boolean))continue;let markerBearing=fields[0]==="[CANDIDATE]",selection={lineIndex,fields,family:candidateHeaderFamily(fields),markerBearing};if(markerBearing)return selection;markerlessFallback??=selection}return markerlessFallback}function removeCandidateCodeFences(text){let lines=[],inFence=!1;for(let rawLine of text.split(`
163
+ ${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path4 from"node:path";function bundledProjectSkillFileReference(slug){return`file:${BUNDLED_PROJECT_SKILL_ROOT}/${slug}/SKILL.md`}function describeBundledSkillSyncFailure(err){return`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${err instanceof Error?err.message:String(err)}`}async function isSymbolicLinkAsync(p){try{return(await fsp.lstat(p)).isSymbolicLink()}catch{return!1}}async function ensureNotSymlinkedDirectoryAsync(p){try{let stat4=await fsp.lstat(p);return stat4.isDirectory()&&!stat4.isSymbolicLink()}catch(err){return err.code==="ENOENT"}}async function pathExistsAsync(p){try{return await fsp.access(p),!0}catch{return!1}}async function collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeDir=""){let currentSource=path4.join(sourceDir,relativeDir),entries=await fsp.readdir(currentSource,{withFileTypes:!0});entries.sort((a,b)=>a.name.localeCompare(b.name));let files=[];for(let entry of entries){let relativeEntry=path4.join(relativeDir,entry.name),sourcePath=path4.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))throw Error("refusing to copy symlinked bundled skill entry");if(entry.isDirectory()){files.push(...await collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeEntry));continue}if(!entry.isFile())continue;let stat4=await fsp.stat(sourcePath),nextFiles=state.files+1,nextBytes=state.bytes+stat4.size;if(nextFiles>MAX_SKILL_FILES||nextBytes>MAX_SKILL_BYTES)throw Error("bundled skill package exceeds copy bounds");state.files=nextFiles,state.bytes=nextBytes,files.push({relativePath:relativeEntry})}return files}async function ensureContainedDirectoryAsync(rootDir,directory){let safeRoot=path4.resolve(rootDir),safeDirectory=path4.resolve(directory),relative2=path4.relative(safeRoot,safeDirectory);if(relative2.startsWith("..")||path4.isAbsolute(relative2))throw Error("bundled skill destination escaped its private root");try{let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;await fsp.mkdir(safeRoot,{recursive:!0});let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}let current=safeRoot;for(let segment of relative2.split(path4.sep).filter(Boolean)){current=path4.join(current,segment);try{let stat4=await fsp.lstat(current);if(stat4.isSymbolicLink()||!stat4.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;try{await fsp.mkdir(current)}catch(mkdirErr){if(mkdirErr.code!=="EEXIST")throw mkdirErr}let stat4=await fsp.lstat(current);if(stat4.isSymbolicLink()||!stat4.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}}}async function rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles=[]){let safeDestDir=path4.resolve(destDir),dirs=new Set;for(let copiedFile of copiedFiles){let resolvedFile=path4.resolve(copiedFile),relative2=path4.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path4.isAbsolute(relative2))continue;try{await fsp.rm(resolvedFile,{force:!0})}catch{}dirs.add(path4.dirname(resolvedFile))}for(let overwritten of overwrittenFiles.reverse()){let resolvedFile=path4.resolve(overwritten.path),relative2=path4.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path4.isAbsolute(relative2))continue;try{await fsp.writeFile(resolvedFile,overwritten.contents)}catch{}}for(let dir of[...dirs].sort((a,b)=>b.length-a.length)){let relative2=path4.relative(safeDestDir,path4.resolve(dir));if(relative2.startsWith("..")||path4.isAbsolute(relative2))continue;try{await fsp.rmdir(dir)}catch{}}}async function copyFileAtomicAsync(sourcePath,destPath){let tempPath=path4.join(path4.dirname(destPath),`.${path4.basename(destPath)}.tmp.${randomUUID()}`);try{await fsp.copyFile(sourcePath,tempPath),await fsp.rename(tempPath,destPath)}catch(err){try{await fsp.rm(tempPath,{force:!0})}catch{}throw err}}async function copyBundledDirectoryBoundedAsync(sourceDir,destDir){let files=await collectBundledSkillFilesBoundedAsync(sourceDir,{files:0,bytes:0}),copiedFiles=[],overwrittenFiles=[];try{for(let file2 of files){let sourcePath=path4.join(sourceDir,file2.relativePath),destPath=path4.join(destDir,file2.relativePath);if(await ensureContainedDirectoryAsync(destDir,path4.dirname(destPath)),await pathExistsAsync(destPath)){if(await isSymbolicLinkAsync(destPath))throw Error("refusing to overwrite symlinked bundled skill file");let[sourceContents,destContents]=await Promise.all([fsp.readFile(sourcePath),fsp.readFile(destPath)]);if(sourceContents.equals(destContents))continue;overwrittenFiles.push({path:destPath,contents:destContents}),await copyFileAtomicAsync(sourcePath,destPath)}else await copyFileAtomicAsync(sourcePath,destPath),copiedFiles.push(destPath)}}catch(err){throw await rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles),err}}async function removeRetiredBundledSkillDirsAsync(skillsDir){if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;let safeRoot=path4.resolve(skillsDir);for(let slug of RETIRED_BUNDLED_PROJECT_SKILLS)try{let target=path4.resolve(safeRoot,slug),relative2=path4.relative(safeRoot,target);if(relative2.startsWith("..")||path4.isAbsolute(relative2))throw Error("retired bundled skill path escaped its private root");try{let stat4=await fsp.lstat(target);if(stat4.isSymbolicLink()||!stat4.isDirectory())continue}catch(err){if(err.code==="ENOENT")continue;throw err}await fsp.rm(target,{recursive:!0,force:!0}),log("removed retired bundled skill",{slug})}catch(err){log("could not remove retired bundled skill (continuing)",{slug,message:err instanceof Error?err.message:String(err)})}}async function performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet){let skillsDirValidated=!1;try{let sourceRoot=path4.join(packageRoot,".opencode","skills"),swarmDir=path4.join(projectDirectory,".swarm"),skillsDir=path4.join(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT);if(!await ensureNotSymlinkedDirectoryAsync(sourceRoot))throw Error("refusing to copy symlinked bundled skill source root");if(!await ensureNotSymlinkedDirectoryAsync(swarmDir))return;if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;skillsDirValidated=!0;for(let slug of BUNDLED_PROJECT_SKILLS){let sourceDir=path4.join(sourceRoot,slug),sourceSkill=path4.join(sourceDir,"SKILL.md"),destDir=path4.join(skillsDir,slug);if(!await pathExistsAsync(sourceSkill))continue;if(!await ensureNotSymlinkedDirectoryAsync(sourceDir))throw Error("refusing to copy symlinked bundled skill directory");if(!await ensureNotSymlinkedDirectoryAsync(destDir))continue;await copyBundledDirectoryBoundedAsync(sourceDir,destDir),log("synchronized bundled skill",{slug:bundledProjectSkillFileReference(slug)})}}catch(err){let failureMsg=describeBundledSkillSyncFailure(err);if(quiet)advisoryWarn(failureMsg);else console.warn(failureMsg)}finally{if(skillsDirValidated)await removeRetiredBundledSkillDirsAsync(path4.join(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT))}}async function syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){let syncKey=path4.resolve(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT),existing=inFlightSyncs.get(syncKey);if(existing)return existing;if(inFlightSyncs.size>=MAX_IN_FLIGHT_SYNCS){log("skipping bundled skill sync because the in-flight limit was reached",{limit:MAX_IN_FLIGHT_SYNCS});return}let syncPromise=performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet).finally(()=>{if(inFlightSyncs.get(syncKey)===syncPromise)inFlightSyncs.delete(syncKey)});return inFlightSyncs.set(syncKey,syncPromise),syncPromise}var BUNDLED_PROJECT_SKILLS,RETIRED_BUNDLED_PROJECT_SKILLS,BUNDLED_PROJECT_SKILL_ROOT=".swarm/bundled-skills",MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000,MAX_IN_FLIGHT_SYNCS=64,inFlightSyncs;var init_bundled_skills=__esm(()=>{init_warning_buffer();init_logger();BUNDLED_PROJECT_SKILLS=["brainstorm","specify","clarify-spec","swarm-resume","clarify","discover","consult","pre-phase-briefing","council","deep-dive","deep-research","codebase-review-swarm","swarm-implement","design-docs","swarm-pr-review","swarm","swarm-pr-feedback","swarm-pr-subscribe","swarm-ci-monitor","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr","ci-failure-batching","gate-attribution","merge-queue-readiness","skill-edit-validation","worktree-retry-cleanup","test-file-split","fork-pr-operations","parallel-work-check","ci-fix-monitor","issue-tracer","orchestrating-subagents","durable-session-state"],RETIRED_BUNDLED_PROJECT_SKILLS=["resume"];inFlightSyncs=new Map});function formatCandidateHeader(family){return["[CANDIDATE]",...CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name)].join(" | ")}function formatCleanTemplate(family){return["[CLEAN]",family==="base_explorer"?"lane":"micro_lane","coverage_scope","evidence"].join(" | ")}function candidateHeaderFamily(fields){if(fields[0]?.trim()!=="[CANDIDATE]")return null;let normalized=fields.slice(1).map((field)=>field.trim());for(let family of["base_explorer","micro_lane"]){let canonicalHeaderFields=CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name);if(normalized.length===canonicalHeaderFields.length&&canonicalHeaderFields.every((name,index)=>normalized[index]===name))return family}return null}function selectCandidateHeader(lines){let markerlessFallback=null;for(let[lineIndex,line]of lines.entries()){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());if(fields.length<2||!fields.some(Boolean))continue;let markerBearing=fields[0]==="[CANDIDATE]",selection={lineIndex,fields,family:candidateHeaderFamily(fields),markerBearing};if(markerBearing)return selection;markerlessFallback??=selection}return markerlessFallback}function removeCandidateCodeFences(text){let lines=[],inFence=!1;for(let rawLine of text.split(`
164
164
  `)){if(rawLine.trimStart().startsWith("```")){inFence=!inFence;continue}if(!inFence)lines.push(rawLine)}return lines.join(`
165
165
  `)}function parseClosedMarkdownFences(text){let lines=text.split(/\r?\n/),blocks=[],fencedLineIndexes=new Set,openingLine=-1,openingWidth=0;for(let index=0;index<lines.length;index+=1){let line=lines[index];if(openingLine<0){let opening=line.match(/^\s{0,3}(`{3,})([^`]*)$/);if(!opening)continue;openingLine=index,openingWidth=opening[1].length;continue}let closing=line.match(/^\s{0,3}(`{3,})\s*$/);if(!closing||closing[1].length<openingWidth)continue;let content=lines.slice(openingLine+1,index);blocks.push({openingLine,closingLine:index,content});for(let fenced=openingLine;fenced<=index;fenced+=1)fencedLineIndexes.add(fenced);openingLine=-1,openingWidth=0}if(openingLine>=0)return null;return{lines,blocks,unfencedLines:lines.filter((_,index)=>!fencedLineIndexes.has(index))}}function lineCarriesCandidateProtocol(line){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());return fields[0]==="[CANDIDATE]"||fields[0]==="[CLEAN]"||candidateHeaderFamily(fields)!==null}function lastUnescapedPipeIndex(line){let last=-1;for(let index=0;index<line.length;index+=1){if(line[index]==="\\"&&line[index+1]==="|"){index+=1;continue}if(line[index]==="|")last=index}return last}function repairRedundantCleanConfidenceLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields.length!==5||fields[0]!=="[CLEAN]"||!isCandidateConfidence(fields[4])||!analyzeCleanFields(fields.slice(0,4),family).valid)return{line,repaired:!1};let delimiter=lastUnescapedPipeIndex(line);if(delimiter<0)return{line,repaired:!1};return{line:line.slice(0,delimiter).trimEnd(),repaired:!0}}function repairRedundantCleanConfidence(text,family){let repaired=!1;return{text:text.split(/\r?\n/).map((line)=>{let result=repairRedundantCleanConfidenceLine(line,family);return repaired||=result.repaired,result.line}).join(`
166
166
  `),repaired}}function canonicalHeaderShape(line){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());if(fields.length===0)return null;if(candidateHeaderFamily(fields))return{markerBearing:!0};for(let family of["base_explorer","micro_lane"]){let canonical=CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name);if(fields.length===canonical.length&&canonical.every((name,index)=>fields[index]===name))return{markerBearing:!1}}return null}function dropDuplicateHeaderRows(text){let lines=text.split(/\r?\n/),shapes=lines.map((line)=>line.includes("|")?canonicalHeaderShape(line):null),keepIndex=(()=>{let markerBearing=shapes.findIndex((shape)=>shape?.markerBearing);if(markerBearing!==-1)return markerBearing;return shapes.findIndex((shape)=>shape!==null)})();if(keepIndex===-1)return{text,dropped:!1};let kept=lines.filter((_line,index)=>shapes[index]===null||index===keepIndex);return{text:kept.join(`
@@ -292,7 +292,7 @@ ${lines[i]}`),framingChecked=!0}else{let prefix=!framingChecked&&!fileEndsWithNe
292
292
  ON qi.profile_id = p.id
293
293
  WHERE p.plan_id = ?
294
294
  AND qi.profile_id IS NULL
295
- LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch(err){warn(`[qa-gate-profile] skipping unparseable qa_gate_profile row while checking gate "${gate}": ${err instanceof Error?err.message:String(err)}`)}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals15.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates),insert=db.transaction(()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])});try{insert()}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals15.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")return createExactProfileTx(db,exact,projectType,initialGates);return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory),savepointName=`qa_gate_profile_set_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction;db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals15.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`),rowToProfile(updatedRow)}catch(err){try{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)}catch{}throw err}}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity),savepointName=`qa_gate_profile_set_identity_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction,finishTransaction=()=>{db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`)},rollbackTransaction=()=>{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)};db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing"){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals15.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return finishTransaction(),current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return finishTransaction(),rowToProfileWithBinding(updatedRow,binding)}catch(err){try{rollbackTransaction()}catch{}throw err}}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash11("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals15,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError,qaGateProfileSavepointCounter=0;var init_qa_gate_profile=__esm(()=>{init_utils3();init_logger();init_project_db();_internals15={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{}},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash12}from"node:crypto";function hashString(value){return createHash12("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import{randomBytes as randomBytes2}from"node:crypto";import*as fs13 from"node:fs";import*as path18 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path18.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs13.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path18.normalize(path18.resolve(targetPath)),segments=resolved.split(path18.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path18.sep);try{let st=fs13.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path18.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path18.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path18.sep)){if(probe=path18.join(probe,seg),!fs13.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path18.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep2(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS2.length;attempt++)try{_internals16.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES2.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS2.length)syncSleep2(RENAME_RETRY_DELAYS_MS2[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path18.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals16.randomSuffix()}.tmp`;fs13.mkdirSync(path18.dirname(tempPath),{recursive:!0});try{let fd=fs13.openSync(tempPath,"wx");try{let written=0;while(written<buffer.byteLength)written+=_internals16.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals16.fsyncSync(fd)}catch{}}finally{fs13.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals16.unlinkSync(tempPath)}catch{}}try{let dirFd=fs13.openSync(path18.dirname(resolvedTarget),"r");try{fs13.fsyncSync(dirFd)}finally{fs13.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_internals16;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:241"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:14566"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:14531-14579) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:629","src/plan/manager.ts:1785","src/plan/manager.ts:1831","src/review/evidence.ts:160","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:106","src/tools/repo-graph/storage.ts:426","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:995","src/background/delegation-health.ts:390","src/hooks/delegation-gate/worktree-provisioning-owner.ts:100","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:124","src/tools/write-pr-review-artifact.ts:144","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1971","src/plan/manager.ts:2160"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:107","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:1145","src/hooks/skill-usage-log.ts:1650","src/hooks/skill-usage-pending.ts:816","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"registered-bespoke","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals16={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs13.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs13.renameSync(from,to),unlinkSync:(p)=>fs13.unlinkSync(p),fsyncSync:(fd)=>fs13.fsyncSync(fd)}});import*as path19 from"node:path";function taskEvidenceRelPath(taskId){return path19.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path19.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash13}from"node:crypto";import*as fs14 from"node:fs";import*as path20 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path20.resolve(value).toLowerCase():path20.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs14.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs14.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path20.join(current,segment);let info;try{info=fs14.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs14.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs14.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs14.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path20.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash13("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs14.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs14.openSync(filePath,fs14.constants.O_RDONLY|(fs14.constants.O_NOFOLLOW??0));try{let openedStat=fs14.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs14.readFileSync(descriptor,"utf-8")}finally{fs14.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
295
+ LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch(err){warn(`[qa-gate-profile] skipping unparseable qa_gate_profile row while checking gate "${gate}": ${err instanceof Error?err.message:String(err)}`)}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals15.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates),insert=db.transaction(()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])});try{insert()}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals15.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")return createExactProfileTx(db,exact,projectType,initialGates);return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory),savepointName=`qa_gate_profile_set_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction;db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals15.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`),rowToProfile(updatedRow)}catch(err){try{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)}catch{}throw err}}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity),savepointName=`qa_gate_profile_set_identity_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction,finishTransaction=()=>{db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`)},rollbackTransaction=()=>{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)};db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing"){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals15.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return finishTransaction(),current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return finishTransaction(),rowToProfileWithBinding(updatedRow,binding)}catch(err){try{rollbackTransaction()}catch{}throw err}}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash11("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals15,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError,qaGateProfileSavepointCounter=0;var init_qa_gate_profile=__esm(()=>{init_utils3();init_logger();init_project_db();_internals15={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{}},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash12}from"node:crypto";function hashString(value){return createHash12("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import{randomBytes as randomBytes2}from"node:crypto";import*as fs13 from"node:fs";import*as path18 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path18.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs13.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path18.normalize(path18.resolve(targetPath)),segments=resolved.split(path18.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path18.sep);try{let st=fs13.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path18.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path18.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path18.sep)){if(probe=path18.join(probe,seg),!fs13.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path18.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep2(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS2.length;attempt++)try{_internals16.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES2.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS2.length)syncSleep2(RENAME_RETRY_DELAYS_MS2[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path18.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals16.randomSuffix()}.tmp`;fs13.mkdirSync(path18.dirname(tempPath),{recursive:!0});try{let fd=fs13.openSync(tempPath,"wx");try{let written=0;while(written<buffer.byteLength)written+=_internals16.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals16.fsyncSync(fd)}catch{}}finally{fs13.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals16.unlinkSync(tempPath)}catch{}}try{let dirFd=fs13.openSync(path18.dirname(resolvedTarget),"r");try{fs13.fsyncSync(dirFd)}finally{fs13.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_internals16;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:250"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:14566"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:14531-14579) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:629","src/plan/manager.ts:1785","src/plan/manager.ts:1831","src/review/evidence.ts:160","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:106","src/tools/repo-graph/storage.ts:426","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:995","src/background/delegation-health.ts:390","src/hooks/delegation-gate/worktree-provisioning-owner.ts:100","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:124","src/tools/write-pr-review-artifact.ts:144","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1971","src/plan/manager.ts:2160"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:107","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:1145","src/hooks/skill-usage-log.ts:1650","src/hooks/skill-usage-pending.ts:816","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"registered-bespoke","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals16={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs13.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs13.renameSync(from,to),unlinkSync:(p)=>fs13.unlinkSync(p),fsyncSync:(fd)=>fs13.fsyncSync(fd)}});import*as path19 from"node:path";function taskEvidenceRelPath(taskId){return path19.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path19.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash13}from"node:crypto";import*as fs14 from"node:fs";import*as path20 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path20.resolve(value).toLowerCase():path20.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs14.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs14.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path20.join(current,segment);let info;try{info=fs14.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs14.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs14.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs14.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path20.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash13("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs14.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs14.openSync(filePath,fs14.constants.O_RDONLY|(fs14.constants.O_NOFOLLOW??0));try{let openedStat=fs14.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs14.readFileSync(descriptor,"utf-8")}finally{fs14.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
296
296
  `)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function deriveReceiptRole(event){switch(event.type){case"accepted_mutation":case"dispatch_attempted":case"dispatch_no_mutation":if(typeof event.agentType==="string"&&event.agentType.trim().length>0)return{normalizedRole:event.agentType.trim(),testEngineerExempt:event.agentType==="coder"?event.context?.testEngineerExempt===!0:null};return null;case"stage_b_completed":case"gate_recorded":return{normalizedRole:event.gate,testEngineerExempt:null};default:return null}}function shouldAppendReceipt(current,next,role){if(next.required_gates.length===0)return!1;let currentGeneration=current?.workflow?.generation??-1,nextGeneration=next.workflow?.generation??-1;if(current===null)return!0;if(JSON.stringify(current.required_gates)!==JSON.stringify(next.required_gates))return!0;if((current.test_engineer_exempt??null)!==role.testEngineerExempt)return!0;return currentGeneration!==nextGeneration}async function appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,next,event){let role=deriveReceiptRole(event);if(!role||!shouldAppendReceipt(current,next,role))return;let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!0),receipts=await readTaskGateRequirementsReceipts(directory,taskId),latest=receipts.at(-1),baseReceipt={schemaVersion:1,taskId,generation:next.workflow?.generation??0,normalizedRole:role.normalizedRole,testEngineerExempt:role.testEngineerExempt,requiredGates:[...next.required_gates],sourceEvent:event.type,sourceTransitionId:event.transitionId??null,recordedAt:new Date().toISOString(),previousChainHash:latest?.chainHash??null},receipt={...baseReceipt,chainHash:computeChainHash(baseReceipt)};if(latest&&latest.generation===receipt.generation&&latest.normalizedRole===receipt.normalizedRole&&latest.testEngineerExempt===receipt.testEngineerExempt&&JSON.stringify(latest.requiredGates)===JSON.stringify(receipt.requiredGates)&&latest.sourceTransitionId===receipt.sourceTransitionId)return;let lines=[...receipts,receipt].map((entry)=>JSON.stringify(entry));assertSafeRequirementsParent(directory,!1),await atomicWriteFile(filePath,`${lines.join(`
297
297
  `)}
298
298
  `),assertSafeRequirementsParent(directory,!1)}var MAX_TASK_GATE_REQUIREMENTS_BYTES=262144,TaskGateRequirementsReceiptSchema;var init_task_gate_requirements=__esm(()=>{init_zod();init_utils2();init_project_boundary();init_task_file();TaskGateRequirementsReceiptSchema=exports_external.object({schemaVersion:exports_external.literal(1),taskId:exports_external.string().min(1).max(120),generation:exports_external.number().int().min(0),normalizedRole:exports_external.string().min(1).max(120),testEngineerExempt:exports_external.boolean().nullable(),requiredGates:exports_external.array(exports_external.string()).min(1).max(16),sourceEvent:exports_external.string().min(1).max(120),sourceTransitionId:exports_external.string().min(1).max(200).nullable(),recordedAt:exports_external.string().min(1).max(128),previousChainHash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),chainHash:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});function checkUnsafeChars(taskId){if(!taskId||taskId.length===0)return"Invalid task ID: empty string";if(/\0/.test(taskId))return"Invalid task ID: contains null bytes";for(let i=0;i<taskId.length;i++)if(taskId.charCodeAt(i)<32)return"Invalid task ID: contains control characters";if(taskId.includes("..")||taskId.includes("/")||taskId.includes("\\"))return"Invalid task ID: path traversal detected";return}function isStrictTaskId(taskId){if(!taskId)return!1;if(checkUnsafeChars(taskId))return!1;return STRICT_TASK_ID_PATTERN.test(taskId)}function assertStrictTaskId(taskId){if(!isStrictTaskId(taskId))throw Error(`Invalid taskId: "${taskId}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3").`)}function sanitizeTaskId(taskId){let unsafeMsg=checkUnsafeChars(taskId);if(unsafeMsg)throw Error(unsafeMsg);if(STRICT_TASK_ID_PATTERN.test(taskId)||RETRO_TASK_ID_REGEX.test(taskId)||INTERNAL_TOOL_ID_REGEX.test(taskId)||GENERAL_TASK_ID_REGEX.test(taskId))return taskId;throw Error(`Invalid task ID: must be alphanumeric (ASCII) with optional hyphens, underscores, or dots, got "${taskId}"`)}function validateTaskIdFormat(taskId){if(!STRICT_TASK_ID_PATTERN.test(taskId))return`Invalid taskId "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}var STRICT_TASK_ID_PATTERN,RETRO_TASK_ID_REGEX,INTERNAL_TOOL_ID_REGEX,GENERAL_TASK_ID_REGEX;var init_task_id=__esm(()=>{STRICT_TASK_ID_PATTERN=/^\d+\.\d+(\.\d+)*$/,RETRO_TASK_ID_REGEX=/^retro-\d+$/,INTERNAL_TOOL_ID_REGEX=/^(?:sast_scan|quality_budget|syntax_check|placeholder_scan|sbom_generate|build|secretscan)$/,GENERAL_TASK_ID_REGEX=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/});import*as path21 from"node:path";function isControlCharacter(character){let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159}function isBidiControlCharacter(character){return BIDI_CONTROL_CHARACTERS.test(character)}function getPathFlavor(pathLib=path21){return pathLib.sep==="\\"?"win32":"posix"}function pathImplementation(flavor){return flavor==="win32"?path21.win32:path21.posix}function normalizePathIdentity(value,flavor=getPathFlavor()){let normalized=pathImplementation(flavor).normalize(flavor==="win32"?value.replace(/\//g,"\\"):value);return flavor==="win32"?normalized.toLowerCase():normalized}function pathIdentitiesEqual(a,b,flavor=getPathFlavor()){return normalizePathIdentity(a,flavor)===normalizePathIdentity(b,flavor)}function isPathIdentityWithin(target,container,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetIdentity=normalizePathIdentity(target,flavor),containerIdentity=normalizePathIdentity(container,flavor);if(targetIdentity===containerIdentity)return!0;let relative5=pathImpl.relative(containerIdentity,targetIdentity);return relative5.length>0&&relative5!==".."&&!relative5.startsWith(`..${pathImpl.sep}`)&&!pathImpl.isAbsolute(relative5)}function isPathWithinDeclaredScope(filePath,scopeEntries,cwd=process.cwd(),flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),resolvedFile=pathImpl.resolve(cwd,filePath);return scopeEntries.some((scope)=>isPathIdentityWithin(resolvedFile,pathImpl.resolve(cwd,scope),flavor))}function isOnDifferentPathRoot(target,cwd,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetRoot=pathImpl.parse(pathImpl.normalize(target)).root,cwdRoot=pathImpl.parse(pathImpl.normalize(cwd)).root;return!pathIdentitiesEqual(targetRoot,cwdRoot,flavor)}function unsafePathTextReason(value){if([...value].some(isControlCharacter))return"control characters are not allowed in paths";if([...value].some(isBidiControlCharacter))return"bidirectional control characters are not allowed in paths";return null}function sanitizeDiagnosticText(value,maxLength=256){let rendered=String(value).split("").map((character)=>isControlCharacter(character)||isBidiControlCharacter(character)?"?":character).join("").replace(/\s+/gu," ").trim();if(rendered.length<=maxLength)return rendered;return`${rendered.slice(0,Math.max(0,maxLength-1))}…`}var BIDI_CONTROL_CHARACTERS;var init_path_identity=__esm(()=>{BIDI_CONTROL_CHARACTERS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u});import*as fs15 from"node:fs";import*as path22 from"node:path";function recoveryDir(directory){return path22.join(directory,".swarm",RECOVERY_DIR_NAME)}function recordPath(directory,sessionId,laneId){let safeSession=sessionId.replace(/[^a-zA-Z0-9._-]/g,"_"),safeLane=laneId.replace(/[^a-zA-Z0-9._-]/g,"_");return path22.join(recoveryDir(directory),`${safeSession}-${safeLane}.json`)}function isRecoveryRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return!1;let record2=value,validStatus=record2.status==="failed"||record2.status==="partial"||record2.status==="conflict";return typeof record2.laneId==="string"&&typeof record2.sessionId==="string"&&typeof record2.worktreePath==="string"&&validStatus&&typeof record2.reason==="string"&&typeof record2.recordedAt==="number"&&Number.isFinite(record2.recordedAt)&&typeof record2.replayHint==="string"&&(record2.branchName===void 0||typeof record2.branchName==="string")&&(record2.conflictFiles===void 0||Array.isArray(record2.conflictFiles)&&record2.conflictFiles.every((file2)=>typeof file2==="string"))}function readRecoveryRecords(directory){let dir=recoveryDir(directory),entries;try{entries=fs15.readdirSync(dir,{withFileTypes:!0})}catch{return{records:[],errored:fs15.existsSync(dir)}}let records=[],errored=!1;for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let full=path22.join(dir,entry.name);try{let parsed=JSON.parse(fs15.readFileSync(full,"utf-8"));if(isRecoveryRecord(parsed))records.push(parsed);else errored=!0}catch{errored=!0}}return{records,errored}}function writeRecoveryRecord(directory,record2){try{let dir=recoveryDir(directory);fs15.mkdirSync(dir,{recursive:!0});let filePath=recordPath(directory,record2.sessionId,record2.laneId),payload={...record2,recordedAt:record2.recordedAt??Date.now()},tmpPath=`${filePath}.tmp.${Date.now()}`;fs15.writeFileSync(tmpPath,JSON.stringify(payload,null,2),"utf-8"),fs15.renameSync(tmpPath,filePath)}catch{}}function listRecoveryRecords(directory){return readRecoveryRecords(directory).records}function hasRecoveryRecordForBranch(directory,branchName){return listRecoveryRecords(directory).some((r)=>r.branchName===branchName)}function clearRecoveryRecord(directory,laneId,sessionId){try{let filePath=recordPath(directory,sessionId,laneId);if(fs15.existsSync(filePath))fs15.unlinkSync(filePath)}catch{}}function recoveryReadErrored(directory){return readRecoveryRecords(directory).errored}var RECOVERY_DIR_NAME="recovery";var init_recovery=()=>{};function isGitBinaryMissing(err,cwd){return classifySpawnFailure(err,cwd)==="binary-missing"}function isSpawnCwdMissing(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-missing"}function isSpawnCwdUnreadable(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-unreadable"}var GitUnavailableError,GitBinaryMissingError,GitSpawnCwdError;var init_git_binary_missing_error=__esm(()=>{init_bun_compat();init_bun_compat();GitUnavailableError=class GitUnavailableError extends Error{};GitBinaryMissingError=class GitBinaryMissingError extends GitUnavailableError{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}};GitSpawnCwdError=class GitSpawnCwdError extends GitUnavailableError{name="GitSpawnCwdError";cwd;fault;constructor(cwd,fault,options){super(fault==="missing"?`git could not start: working directory no longer exists: ${cwd}`:`git could not start: working directory could not be inspected (permission denied): ${cwd}`,options);this.cwd=cwd,this.fault=fault}}});function isSwarmSessionId(sessionId){return typeof sessionId==="string"&&SESSION_ID_PATTERN.test(sessionId)}function isPlainSegment(segment){return typeof segment==="string"&&segment.length>0&&segment!=="."&&segment!==".."}function buildSwarmBranchName(sessionId,id,purpose,legacyLane){let[standardPrefix,legacyLanePrefix]=SWARM_WORKTREE_BRANCH_PREFIXES;return legacyLane?`${legacyLanePrefix}${sessionId}/${id}`:`${standardPrefix}${purpose}/${sessionId}/${id}`}function matchSwarmLanePath(lanePath){if(typeof lanePath!=="string"||lanePath==="")return;let segments=lanePath.split(/[\\/]+/).filter((s)=>s.length>0);if(segments.length<3)return;let[base,sessionId,id]=segments.slice(-3);if(!(process.platform==="win32"?base.toLowerCase()===SWARM_WORKTREE_DIR_NAME.toLowerCase():base===SWARM_WORKTREE_DIR_NAME))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{sessionId,id}}function matchSwarmLaneBranch(branch){if(typeof branch!=="string"||branch==="")return;let segments=branch.split("/");if(segments[0]==="swarm-lane"){if(segments.length!==3)return;let[,sessionId,id]=segments;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose:"lane",sessionId,id,style:"legacy-lane"}}if(segments[0]==="swarm"){if(segments.length!==4)return;let[,purpose,sessionId,id]=segments;if(!isPlainSegment(purpose))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose,sessionId,id,style:"purpose"}}return}var SWARM_WORKTREE_BRANCH_PREFIXES,SESSION_ID_PATTERN;var init_swarm_branch=__esm(()=>{init_constants();SWARM_WORKTREE_BRANCH_PREFIXES=["swarm/","swarm-lane/"],SESSION_ID_PATTERN=/^ses_[A-Za-z0-9]+$/});import*as crypto3 from"node:crypto";import*as fs16 from"node:fs";import*as path23 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path23.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path23.join(directory,".swarm",PLAN_JSON_FILENAME)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs16.openSync(tempPath,"w");try{fs16.writeFileSync(fd,data,"utf8"),fs16.fsyncSync(fd)}finally{fs16.closeSync(fd)}fs16.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs16.openSync(directory,"r"),fs16.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs16.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function computePlanHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs16.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs16.existsSync(ledgerPath)}async function getLatestLedgerSeq(directory){let ledgerPath=getLedgerPath(directory);if(!fs16.existsSync(ledgerPath))return 0;try{let lines=fs16.readFileSync(ledgerPath,"utf8").trim().split(`
@@ -4339,7 +4339,7 @@ Activates when an existing .swarm/plan.md or .swarm/spec.md must be resumed.
4339
4339
 
4340
4340
  Purpose: Reconcile saved workflow state with the current swarm and continue without corrupting ownership.
4341
4341
 
4342
- ACTION: Load skill ${bundledProjectSkillFileReference("resume")} immediately. Follow the protocol defined there.
4342
+ ACTION: Load skill ${bundledProjectSkillFileReference("swarm-resume")} immediately. Follow the protocol defined there.
4343
4343
 
4344
4344
  HARD CONSTRAINTS:
4345
4345
  - Preserve existing plan/spec state and reconcile swarm ownership before continuing work.