opencode-swarm 7.176.0 → 7.176.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 (80) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{coder-settlement-y3ftsdje.js → coder-settlement-cctwqn8q.js} +10 -10
  4. package/dist/cli/{config-doctor-3x9d5y3w.js → config-doctor-f2j4t2qg.js} +2 -2
  5. package/dist/cli/{core-hf9pjm7y.js → core-j1wef1b1.js} +3 -3
  6. package/dist/cli/{curation-policy-8h25hyf8.js → curation-policy-62k3tfy2.js} +4 -4
  7. package/dist/cli/{curator-pf4n52b1.js → curator-9bkavyx7.js} +35 -35
  8. package/dist/cli/{curator-drift-qxgs5ee4.js → curator-drift-j1ggdamr.js} +4 -4
  9. package/dist/cli/curator-llm-factory-rdmbyw36.js +72 -0
  10. package/dist/cli/{evidence-summary-service-t4nnvgyz.js → evidence-summary-service-vp1gnmw8.js} +14 -14
  11. package/dist/cli/{gate-evidence-d6wmarwz.js → gate-evidence-wfc2ypwe.js} +5 -5
  12. package/dist/cli/guardrail-explain-271bxeve.js +73 -0
  13. package/dist/cli/{guardrail-log-ehwt0w51.js → guardrail-log-cw6kst05.js} +6 -6
  14. package/dist/cli/{guardrail-reset-ceqcapzm.js → guardrail-reset-vs77rj7q.js} +35 -35
  15. package/dist/cli/{hive-promoter-9dgmk5nq.js → hive-promoter-f9zx73na.js} +35 -35
  16. package/dist/cli/{index-2xm1xtqy.js → index-02sbqp2j.js} +1 -1
  17. package/dist/cli/{index-bym86sb4.js → index-25aq56s9.js} +1 -1
  18. package/dist/cli/{index-z9nzrjf7.js → index-36gm5wzh.js} +1 -1
  19. package/dist/cli/{index-wpae4r9j.js → index-39g9ktkw.js} +5 -5
  20. package/dist/cli/{index-509g4m8s.js → index-3ac47c51.js} +96 -76
  21. package/dist/cli/{index-g9pqwf7v.js → index-3mrdcdsw.js} +2 -2
  22. package/dist/cli/{index-crx99j5b.js → index-85qk65a0.js} +3 -3
  23. package/dist/cli/{index-r3ftkdvn.js → index-8q6ax18j.js} +1 -1
  24. package/dist/cli/{index-cfjbrcv7.js → index-9kqtzj67.js} +1 -1
  25. package/dist/cli/{index-t5t6cqfb.js → index-9rpw0edg.js} +5 -5
  26. package/dist/cli/{index-n1wean2y.js → index-9xp8cgh3.js} +8 -8
  27. package/dist/cli/{index-wer28675.js → index-af37hks1.js} +7 -7
  28. package/dist/cli/{index-twymcfj9.js → index-agwajtws.js} +1 -1
  29. package/dist/cli/{index-hvt8902r.js → index-axzmpwsp.js} +3 -3
  30. package/dist/cli/{index-jj09bfnn.js → index-b6xgqf81.js} +2 -2
  31. package/dist/cli/{index-gtjx3q5h.js → index-bh07vpsw.js} +1 -1
  32. package/dist/cli/{index-rm1k8ekt.js → index-bmzmxewc.js} +35 -35
  33. package/dist/cli/{index-wdcsy80q.js → index-cj66fbmz.js} +7 -7
  34. package/dist/cli/{index-dq0fbb2g.js → index-drdcsxdc.js} +7 -7
  35. package/dist/cli/{index-s0w34gp3.js → index-dzqarb47.js} +4 -4
  36. package/dist/cli/{index-zpa6ywts.js → index-ekw3p6a9.js} +10 -10
  37. package/dist/cli/{index-n5aa7f72.js → index-faqr1jkr.js} +2 -2
  38. package/dist/cli/{index-kj7h2yfv.js → index-fsrfamds.js} +1 -1
  39. package/dist/cli/{index-wn00ra10.js → index-fwjenx4w.js} +1 -1
  40. package/dist/cli/{index-8tn4yx8b.js → index-g4m0t1y4.js} +1 -1
  41. package/dist/cli/{index-czhbsgdh.js → index-gaa1h7rv.js} +1 -1
  42. package/dist/cli/{index-dn5kkjfv.js → index-k4r7m6vz.js} +37 -37
  43. package/dist/cli/{index-5t71wd7j.js → index-mw5k6s43.js} +2 -2
  44. package/dist/cli/{index-6tbnev6y.js → index-nxgbfgmc.js} +1 -1
  45. package/dist/cli/{index-2xwavnbg.js → index-p2r8cejw.js} +1 -1
  46. package/dist/cli/{index-c45zvjeg.js → index-qr5ryazn.js} +2 -2
  47. package/dist/cli/{index-fh8jh5n1.js → index-r7fz80tj.js} +3 -3
  48. package/dist/cli/{index-569pn3vz.js → index-sdcybkes.js} +6 -6
  49. package/dist/cli/{index-pd3yg1mh.js → index-stz507bw.js} +4 -4
  50. package/dist/cli/{index-t4kwsbhj.js → index-swhxs3n7.js} +1 -1
  51. package/dist/cli/{index-eawhasqk.js → index-wa6ryk62.js} +1 -1
  52. package/dist/cli/{index-580v9v50.js → index-xj3j4v3r.js} +2 -2
  53. package/dist/cli/{index-rekx0gq7.js → index-yj8hn89a.js} +6 -6
  54. package/dist/cli/{index-9fnjkqsr.js → index-yss54mb9.js} +2 -2
  55. package/dist/cli/{index-s1cm0jre.js → index-zwvrrwwb.js} +1 -1
  56. package/dist/cli/index.js +36 -36
  57. package/dist/cli/{knowledge-escalator-0eyjbhap.js → knowledge-escalator-znzksqjb.js} +11 -11
  58. package/dist/cli/{knowledge-events-64k22qmf.js → knowledge-events-n77sysfe.js} +9 -9
  59. package/dist/cli/{knowledge-link-yx57s7zb.js → knowledge-link-1n4kjc0c.js} +3 -3
  60. package/dist/cli/{knowledge-store-q3k2zf8a.js → knowledge-store-qv2n3q7j.js} +4 -4
  61. package/dist/cli/{knowledge-validator-ywbk1gpw.js → knowledge-validator-ed7y0c3r.js} +6 -6
  62. package/dist/cli/{mcp-yas626k0.js → mcp-xpxfwpjq.js} +1 -1
  63. package/dist/cli/{pending-delegations-91a6nb8z.js → pending-delegations-d1m7ebsd.js} +10 -10
  64. package/dist/cli/{pr-subscriptions-dyn9hn9g.js → pr-subscriptions-8v66558d.js} +10 -10
  65. package/dist/cli/{pr-workflow-gate-xwz3f6zm.js → pr-workflow-gate-bx7x5cyh.js} +35 -35
  66. package/dist/cli/{runner-j4hrfyve.js → runner-91q995mh.js} +4 -4
  67. package/dist/cli/{scan-cursor-etrpan51.js → scan-cursor-9vp5c7dk.js} +5 -5
  68. package/dist/cli/{schema-aarfgdn3.js → schema-e0b6nwh6.js} +1 -1
  69. package/dist/cli/{scope-persistence-j0vzwybd.js → scope-persistence-dd6cwhhc.js} +13 -13
  70. package/dist/cli/{server-rhpwneb6.js → server-6xqhb2xr.js} +35 -35
  71. package/dist/cli/{skill-generator-m6yrxy2s.js → skill-generator-k9gvpdq5.js} +13 -13
  72. package/dist/cli/{snapshot-coordination-init-1yn3fyt4.js → snapshot-coordination-init-8a0cqgzy.js} +35 -35
  73. package/dist/cli/{workspace-snapshot-07rzjg7s.js → workspace-snapshot-f81xc1vd.js} +3 -3
  74. package/dist/cli/{worktree-collision-ownership-g6bjm090.js → worktree-collision-ownership-msxze6pq.js} +11 -11
  75. package/dist/cli/{worktree-isolation-6kebmn1t.js → worktree-isolation-1fxsq65k.js} +35 -35
  76. package/dist/index.js +5 -5
  77. package/dist/services/diagnose-service.d.ts +10 -0
  78. package/package.json +1 -1
  79. package/dist/cli/curator-llm-factory-rs8zyytn.js +0 -72
  80. package/dist/cli/guardrail-explain-x8n8dtq6.js +0 -73
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.176.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",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.176.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -176,7 +176,7 @@ line break`,"required change with\rcarriage return"]),discardedReviewer=encodePr
176
176
  `);return outside?`${outside}
177
177
  ${protocol}`:protocol}function declaredCanonicalFamilies(source){let families=[];for(let line of source.split(/\r?\n/)){let family=candidateHeaderFamily(splitPipeFields(line).map((field)=>field.trim()));if(family&&!families.includes(family))families.push(family)}return families}function normalizeCandidateArtifact(rawText,fallbackFamily){let repairKinds=[],summaryDrop=dropNonContractMarkerRows(rawText);if(summaryDrop.dropped)repairKinds.push("summary-row-dropped");let recoveredFence=recoverTerminalProtocolFence(summaryDrop.text,fallbackFamily);if(recoveredFence!==null)repairKinds.push("terminal-protocol-fence");let cleanRepair=repairRedundantCleanConfidence(recoveredFence??removeCandidateCodeFences(summaryDrop.text),fallbackFamily);if(cleanRepair.repaired)repairKinds.push("redundant-clean-confidence");let pipeRepair=repairCleanEvidencePipes(cleanRepair.text);if(pipeRepair.repaired)repairKinds.push("clean-evidence-pipe-tail-merge");let candidatePipeRepair=repairCandidateEvidencePipes(pipeRepair.text,fallbackFamily);if(candidatePipeRepair.repaired)repairKinds.push("candidate-evidence-pipe-recovery-lossy");let lateHeaderRepair=resynchronizeLateCanonicalHeader(candidatePipeRepair.text,fallbackFamily);if(lateHeaderRepair.repaired)repairKinds.push("late-canonical-header-resynchronized");let duplicateHeaderDrop=dropDuplicateHeaderRows(lateHeaderRepair.text);if(duplicateHeaderDrop.dropped)repairKinds.push("duplicate-header-row-dropped");let text=duplicateHeaderDrop.text,header=selectCandidateHeader(text.split(/\r?\n/));if(header?.markerBearing&&header.family!==null)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(text).length>0)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(summaryDrop.text).some((family)=>family!==fallbackFamily))return{text,synthesizedHeader:!1,repairKinds};let lines=text.split(/\r?\n/);if(!lines.some((line)=>{if(analyzeCandidateLine(line,fallbackFamily)?.valid===!0)return!0;let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!==CLEAN_MARKER)return!1;return analyzeCleanFields(fields,fallbackFamily).valid}))return{text,synthesizedHeader:!1,repairKinds};let firstSalvageableIndex=lines.findIndex((line)=>{let marker=splitPipeFields(line)[0]?.trim();return marker===CANDIDATE_MARKER||marker===CLEAN_MARKER});return repairKinds.push("synthesized-header"),{text:[...lines.slice(0,firstSalvageableIndex),CANDIDATE_HEADERS[fallbackFamily],...lines.slice(firstSalvageableIndex)].join(`
178
178
  `),synthesizedHeader:!0,repairKinds}}function candidateArtifactCacheKey(rawText,fallbackFamily){return createHash2("sha256").update(`${rawText}\x00${fallbackFamily}`).digest("hex")}function normalizeCandidateArtifactCached(rawText,fallbackFamily){let key=candidateArtifactCacheKey(rawText,fallbackFamily),hit=candidateArtifactCache.get(key);if(hit!==void 0)return candidateArtifactCacheHits++,hit;candidateArtifactCacheMisses++;let result=normalizeCandidateArtifact(rawText,fallbackFamily);if(candidateArtifactCache.size>=CANDIDATE_ARTIFACT_CACHE_CAPACITY){let oldest=candidateArtifactCache.keys().next().value;if(oldest!==void 0)candidateArtifactCache.delete(oldest)}return candidateArtifactCache.set(key,result),result}function analyzeCandidateLaneContext(context){let issues=[],baseBound=Boolean(context.expected_lane||context.expected_lanes),microBound=Boolean(context.expected_micro_lane||context.expected_micro_lanes);if(context.expected_lanes){if(!context.expected_lane)issues.push({field:"expected_lane",message:"expected_lane is required when expected_lanes is supplied"});if(new Set(context.expected_lanes).size!==context.expected_lanes.length)issues.push({field:"expected_lanes",message:"expected_lanes must contain unique lane identities"});if(context.expected_lane&&!context.expected_lanes.includes(context.expected_lane))issues.push({field:"expected_lanes",message:"expected_lanes must contain expected_lane"})}if(context.expected_micro_lanes){if(!context.expected_micro_lane)issues.push({field:"expected_micro_lane",message:"expected_micro_lane is required when expected_micro_lanes is supplied"});if(new Set(context.expected_micro_lanes).size!==context.expected_micro_lanes.length)issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain unique lane identities"});if(context.expected_micro_lane&&!context.expected_micro_lanes.includes(context.expected_micro_lane))issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain expected_micro_lane"})}if(!context.expected_family&&baseBound&&microBound)issues.push({field:"expected_family",message:"base and micro ownership fields cannot be combined without one expected_family"});else if(context.expected_family==="base_explorer"&&microBound)issues.push({field:"expected_family",message:"base_explorer ownership cannot include expected_micro_lane fields"});else if(context.expected_family==="micro_lane"&&baseBound)issues.push({field:"expected_family",message:"micro_lane ownership cannot include expected_lane fields"});else if(!context.expected_family&&baseBound)issues.push({field:"expected_family",message:"base ownership fields require expected_family base_explorer"});else if(!context.expected_family&&microBound)issues.push({field:"expected_family",message:"micro ownership fields require expected_family micro_lane"});return issues}function splitPipeFields(line){let fields=[],current="";for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"&&index+1<line.length&&line[index+1]==="|"){current+="|",index++;continue}if(char==="|"){fields.push(current),current="";continue}current+=char}return fields.push(current),fields}function candidateDiagnosticPreview(value){let normalized=value.replace(/[\r\n\t]+/g," ").trim();if(normalized.length<=CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)return normalized;return`${normalized.slice(0,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)}...`}function isCandidateSeverity(value){return value!==null&&value!==void 0&&CANDIDATE_SEVERITIES.includes(value)}function isCandidateConfidence(value){return value!==null&&value!==void 0&&CANDIDATE_CONFIDENCES.includes(value)}function isCandidateLookingShortRow(fields,_context,explicitCandidateMarker=!1){if(explicitCandidateMarker||fields[0]?.trim()==="[CANDIDATE]")return!0;return fields.length>=2}function analyzeCandidateFields(fields,family){let names=CANDIDATE_FIELDS[family],trimmed=fields.map((field)=>field.trim()),values={},issues=[];if(trimmed.length!==CANDIDATE_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CANDIDATE_FIELD_COUNT} candidate fields, received ${trimmed.length}`});for(let index=0;index<names.length;index++){let name=names[index],value=trimmed[index]?.trim()||null;if(values[name]=value,value===null&&name!=="risk_impact"&&name!=="risk_tags")issues.push({field:name,message:`Missing required field: ${name}`})}let severity=values.severity;if(severity!==null&&!isCandidateSeverity(severity))issues.push({field:"severity",message:`Invalid severity: ${candidateDiagnosticPreview(severity)}; expected ${CANDIDATE_SEVERITIES.join("|")}`});let confidence=values.confidence;if(confidence!==null&&!isCandidateConfidence(confidence))issues.push({field:"confidence",message:`Invalid confidence: ${candidateDiagnosticPreview(confidence)}; expected ${CANDIDATE_CONFIDENCES.join("|")}`});let riskImpact=values.risk_impact;if(riskImpact!==null&&!PR_REVIEW_RISK_IMPACTS.includes(riskImpact))issues.push({field:"risk_impact",message:`Invalid risk_impact: ${candidateDiagnosticPreview(riskImpact)}; expected ${PR_REVIEW_RISK_IMPACTS.join("|")}`});let riskTags=values.risk_tags;if(riskTags!==null){let parsedTags=parsePrReviewRiskTagsField(riskTags),known=new Set(PR_REVIEW_RISK_TAGS);if(riskTags!==""&&(parsedTags.length===0||parsedTags.some((tag)=>!known.has(tag))))issues.push({field:"risk_tags",message:`Invalid risk_tags: ${candidateDiagnosticPreview(riskTags)}; expected a comma-separated subset of ${PR_REVIEW_RISK_TAGS.join("|")}, or empty`})}return{valid:issues.length===0,issues,values,candidateId:values.candidate_id,workflowLane:family==="base_explorer"?values.lane:values.micro_lane}}function analyzeCleanFields(fields,family,expectedLane){let trimmed=fields.map((field)=>field.trim()),issues=[],laneField=family==="base_explorer"?"lane":"micro_lane";if(trimmed.length!==CLEAN_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CLEAN_FIELD_COUNT-1} CLEAN fields after [CLEAN], received ${Math.max(0,trimmed.length-1)}`});if(trimmed[0]!=="[CLEAN]")issues.push({field:"row",message:"CLEAN row must begin with [CLEAN]"});let lane=trimmed[1]||null,coverageScope=trimmed[2]||null,evidence=trimmed[3]||null;if(lane===null)issues.push({field:laneField,message:`Missing required field: ${laneField}`});else if(expectedLane!==void 0&&lane!==expectedLane)issues.push({field:laneField,message:`Expected ${laneField} ${candidateDiagnosticPreview(expectedLane)}, received ${candidateDiagnosticPreview(lane)}`});if(coverageScope===null)issues.push({field:"coverage_scope",message:"Missing required field: coverage_scope"});else if(coverageScope.length<CLEAN_COVERAGE_SCOPE_MIN_CHARS)issues.push({field:"coverage_scope",message:`coverage_scope must contain at least ${CLEAN_COVERAGE_SCOPE_MIN_CHARS} characters`});if(evidence===null)issues.push({field:"evidence",message:"Missing required field: evidence"});else if(evidence.length<CLEAN_EVIDENCE_MIN_CHARS)issues.push({field:"evidence",message:`evidence must contain at least ${CLEAN_EVIDENCE_MIN_CHARS} characters`});return{valid:issues.length===0,issues,lane,coverageScope,evidence}}function analyzeCandidateLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CANDIDATE]")return null;return analyzeCandidateFields(fields.slice(1),family)}var CANDIDATE_SEVERITIES,FINDINGS_SEVERITIES,CANDIDATE_CONFIDENCES,CANDIDATE_FIELD_COUNT=11,CANDIDATE_LEGACY_FIELD_COUNT=9,CLEAN_FIELD_COUNT=4,CLEAN_COVERAGE_SCOPE_MIN_CHARS=12,CLEAN_EVIDENCE_MIN_CHARS=20,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS=160,CANDIDATE_FIELDS,CANDIDATE_REQUIRED_FIELDS,CANDIDATE_MARKER="[CANDIDATE]",CLEAN_MARKER="[CLEAN]",CANDIDATE_HEADERS,CLEAN_TEMPLATES,NON_CONTRACT_MARKER_LINE,CANDIDATE_ARTIFACT_CACHE_CAPACITY=512,candidateArtifactCache,candidateArtifactCacheHits=0,candidateArtifactCacheMisses=0;var init_candidate_contract=__esm(()=>{init_pr_review_contract();init_pr_review_contract();CANDIDATE_SEVERITIES=["INFO","LOW","MEDIUM","HIGH","CRITICAL"],FINDINGS_SEVERITIES=[...CANDIDATE_SEVERITIES,"NONE"],CANDIDATE_CONFIDENCES=["HIGH","MEDIUM","LOW"],CANDIDATE_FIELDS={base_explorer:["candidate_id","lane","severity","category","file_line","claim","evidence_summary","impact_context","confidence","risk_impact","risk_tags"],micro_lane:["candidate_id","micro_lane","severity","category","file_line","claim","invariant_violated","evidence_summary","confidence","risk_impact","risk_tags"]},CANDIDATE_REQUIRED_FIELDS={base_explorer:CANDIDATE_FIELDS.base_explorer.filter((field)=>field!=="risk_impact"&&field!=="risk_tags"),micro_lane:CANDIDATE_FIELDS.micro_lane.filter((field)=>field!=="risk_impact"&&field!=="risk_tags")};CANDIDATE_HEADERS={base_explorer:formatCandidateHeader("base_explorer"),micro_lane:formatCandidateHeader("micro_lane")},CLEAN_TEMPLATES={base_explorer:formatCleanTemplate("base_explorer"),micro_lane:formatCleanTemplate("micro_lane")};NON_CONTRACT_MARKER_LINE=/^\[(?!(?:CANDIDATE|CLEAN)\])[A-Z][A-Z0-9_-]*\]/;candidateArtifactCache=new Map});var require_polyfills=__commonJS((exports,module)=>{var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs4){if(constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs4);if(!fs4.lutimes)patchLutimes(fs4);if(fs4.chown=chownFix(fs4.chown),fs4.fchown=chownFix(fs4.fchown),fs4.lchown=chownFix(fs4.lchown),fs4.chmod=chmodFix(fs4.chmod),fs4.fchmod=chmodFix(fs4.fchmod),fs4.lchmod=chmodFix(fs4.lchmod),fs4.chownSync=chownFixSync(fs4.chownSync),fs4.fchownSync=chownFixSync(fs4.fchownSync),fs4.lchownSync=chownFixSync(fs4.lchownSync),fs4.chmodSync=chmodFixSync(fs4.chmodSync),fs4.fchmodSync=chmodFixSync(fs4.fchmodSync),fs4.lchmodSync=chmodFixSync(fs4.lchmodSync),fs4.stat=statFix(fs4.stat),fs4.fstat=statFix(fs4.fstat),fs4.lstat=statFix(fs4.lstat),fs4.statSync=statFixSync(fs4.statSync),fs4.fstatSync=statFixSync(fs4.fstatSync),fs4.lstatSync=statFixSync(fs4.lstatSync),fs4.chmod&&!fs4.lchmod)fs4.lchmod=function(path6,mode,cb){if(cb)process.nextTick(cb)},fs4.lchmodSync=function(){};if(fs4.chown&&!fs4.lchown)fs4.lchown=function(path6,uid,gid,cb){if(cb)process.nextTick(cb)},fs4.lchownSync=function(){};if(platform==="win32")fs4.rename=typeof fs4.rename!=="function"?fs4.rename:function(fs$rename){function rename2(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs4.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename2,fs$rename);return rename2}(fs4.rename);fs4.read=typeof fs4.read!=="function"?fs4.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs4,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs4,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs4.read),fs4.readSync=typeof fs4.readSync!=="function"?fs4.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs4,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs4.readSync);function patchLchmod(fs5){fs5.lchmod=function(path6,mode,callback){fs5.open(path6,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs5.fchmod(fd,mode,function(err2){fs5.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs5.lchmodSync=function(path6,mode){var fd=fs5.openSync(path6,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs5.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret}}function patchLutimes(fs5){if(constants.hasOwnProperty("O_SYMLINK")&&fs5.futimes)fs5.lutimes=function(path6,at,mt,cb){fs5.open(path6,constants.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs5.futimes(fd,at,mt,function(er2){fs5.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs5.lutimesSync=function(path6,at,mt){var fd=fs5.openSync(path6,constants.O_SYMLINK),ret,threw=!0;try{ret=fs5.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret};else if(fs5.futimes)fs5.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs5.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs4,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs4,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs4,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs4,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs4,target,options,callback):orig.call(fs4,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs4,target,options):orig.call(fs4,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs4){return{ReadStream,WriteStream};function ReadStream(path6,options){if(!(this instanceof ReadStream))return new ReadStream(path6,options);Stream.call(this);var self=this;this.path=path6,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs4.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path6,options){if(!(this instanceof WriteStream))return new WriteStream(path6,options);Stream.call(this),this.path=path6,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs4.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs4=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
179
- GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.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(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.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(path6.sep);try{let st=fs4.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=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(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_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let 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}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),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_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;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 (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{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 (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:661","src/plan/manager.ts:1979","src/plan/manager.ts:2033","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:123","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1448","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],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:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{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 (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1458","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],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:154","src/tools/write-pr-review-artifact.ts:174","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 (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],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:2226","src/plan/manager.ts:2374"],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 (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],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:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:578","src/plan/ledger.ts:1763"],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/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.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_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
179
+ GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.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(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.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(path6.sep);try{let st=fs4.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=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(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_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let 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}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),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_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;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 (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{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 (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:661","src/plan/manager.ts:1979","src/plan/manager.ts:2033","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:123","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:230","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1448","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],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:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{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 (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1458","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],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:154","src/tools/write-pr-review-artifact.ts:174","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 (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],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:2226","src/plan/manager.ts:2374"],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 (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],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:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:578","src/plan/ledger.ts:1763"],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/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.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_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
180
180
  → ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};for(let fn2 of fns)if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");return async(input,output)=>{for(let fn2 of fns)await _internals10.safeHook(fn2)(input,output)}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path8.normalize(path8.resolve(directory,".swarm")),resolved=path8.normalize(path8.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path8.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path8.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs5.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs5.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs5.existsSync(existingPath)){let parent=path8.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs5.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path8.normalize(candidate),normalizedBase=path8.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path8.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path8.sep}`)}async function readSwarmFileAsync(directory,filename,cache2,reader,useArtifactCache=!0){if(cache2!==void 0&&useArtifactCache){let key=`${directory}::${filename}`,cached2=cache2.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename,void 0,reader,useArtifactCache);return cache2.set(key,promise2),promise2}let ENOENT_MAX_ATTEMPTS=5,ENOENT_RETRY_DELAY_MS=10,maxAttempts=6;for(let attempt=0;attempt<maxAttempts;attempt++){let resolvedPath="";try{resolvedPath=_internals10.validateSwarmPath(directory,filename);let read=async()=>{if(reader!==void 0)return reader(resolvedPath);return await bunFile(resolvedPath).text()};return useArtifactCache?await _internals10.readCachedTextFile(resolvedPath,read):await read()}catch(err){let code=err?.code;if(reader!==void 0&&(code===void 0||code==="ERR_ENCODING_INVALID_ENCODED_DATA"))throw err;if(code==="ENOENT"){if(!(resolvedPath!==""&&(wasRecentlyWrittenByThisProcess(resolvedPath,RECENT_WRITE_WINDOW_MS)||wasObservedToExist(resolvedPath))))return null;if(attempt>=ENOENT_MAX_ATTEMPTS-1)return null;await new Promise((resolve6)=>setTimeout(resolve6,ENOENT_RETRY_DELAY_MS));continue}if(!(code==="EBUSY"||code==="EPERM"||code==="EACCES")||attempt===maxAttempts-1)return null;let retryDelayMs=10*2**attempt;await new Promise((resolve6)=>setTimeout(resolve6,retryDelayMs))}}return null}function estimateTokensFromCharCount(chars){if(chars<=0)return 0;return Math.ceil(chars*TOKENS_PER_CHAR)}function estimateCharsForTokens(tokens){if(tokens<=0)return 0;return Math.floor(tokens/TOKENS_PER_CHAR)}function estimateTokens(text){if(!text)return 0;return estimateTokensFromCharCount(text.length)}var _internals10,TOKENS_PER_CHAR=0.33;var init_utils2=__esm(()=>{init_utils();init_atomic_write();init_bun_compat();init_swarm_artifact_cache();_internals10={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});import{createHash as createHash3}from"node:crypto";import{appendFileSync,mkdirSync as mkdirSync2}from"node:fs";import*as path9 from"node:path";function isBidiCodePoint(code){for(let i=0;i<BIDI_RANGES.length;i++){let[lo,hi]=BIDI_RANGES[i];if(code>=lo&&code<=hi)return!0}return!1}function sanitizeString(value){let result="";for(let i=0;i<value.length;i++){let code=value.codePointAt(i)??0;if(code>65535)result+=value[i],i++,result+=value[i];else if(code===0)result+="\\u0000";else if(code===27){if(i+1<value.length&&value[i+1]==="["){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=48&&next<=63)i++;else if(next>=32&&next<=47)i++;else if(next>=64&&next<=126){i++;break}else break}}else if(i+1<value.length&&value[i+1]==="]"){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next===7){i++;break}else if(next===27&&i+2<value.length&&value[i+2]==="\\"){i+=2;break}else i++}}else if(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=32&&next<=47){i++;while(i+1<value.length){let b=value.charCodeAt(i+1);if(b>=48&&b<=126){i++;break}else if(b>=32&&b<=47)i++;else break}}else if(next>=48&&next<=126)i++}}else if(isBidiCodePoint(code));else result+=value[i]}return result}function sanitizeRecord(record2){for(let key of Object.keys(record2)){let value=record2[key];if(typeof value==="string")record2[key]=sanitizeString(value);else if(value!==null&&typeof value==="object")if(Array.isArray(value))for(let i=0;i<value.length;i++){let element=value[i];if(typeof element==="string")value[i]=sanitizeString(element);else if(element!==null&&typeof element==="object")sanitizeRecord(element)}else sanitizeRecord(value)}return record2}function computeBatchDigest(batchId){return createHash3(BATCH_DIGEST_ALGORITHM).update(batchId).digest("hex")}function sidecarRelativePath(batchDigest){return path9.join("lane-results",batchDigest,"candidates.jsonl")}function validateRecord(record2,schema,label){let result=schema.safeParse(record2);if(!result.success)throw Error(`Sidecar ${label} schema validation failed: ${result.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")}`)}function withLockfile(lockDir,write){let lockPath=path9.join(lockDir,".lock"),release=import_proper_lockfile.default.lockSync(lockPath,{realpath:!1});try{return write()}finally{release()}}function appendToSidecar(options,batchId,envelope,candidates,cleanAttestation){let batchDigest=options.batchDigest??computeBatchDigest(batchId),relPath=sidecarRelativePath(batchDigest),absPath=validateSwarmPath(options.projectRoot,relPath);validateRecord(envelope,SidecarEnvelopeSchema,"envelope");for(let i=0;i<candidates.length;i++)validateRecord(candidates[i],SidecarCandidateSchema,`candidate[${i}]`);if(cleanAttestation!==void 0)validateRecord(cleanAttestation,SidecarCleanAttestationSchema,"clean_attestation");mkdirSync2(path9.dirname(absPath),{recursive:!0});let sanitizedEnvelope=sanitizeRecord(structuredClone(envelope)),sanitizedCandidates=candidates.map((c)=>sanitizeRecord(structuredClone(c))),sanitizedCleanAttestation=cleanAttestation===void 0?void 0:sanitizeRecord(structuredClone(cleanAttestation)),lines=[JSON.stringify(sanitizedEnvelope)];if(sanitizedCleanAttestation)lines.push(JSON.stringify(sanitizedCleanAttestation));for(let candidate of sanitizedCandidates)lines.push(JSON.stringify(candidate));let payload=`${lines.join(`
181
181
  `)}
182
182
  `,doWrite=()=>{appendFileSync(absPath,payload,"utf-8")};if(options.useLockfile)withLockfile(path9.dirname(absPath),doWrite);else doWrite()}var import_proper_lockfile,BATCH_DIGEST_ALGORITHM="sha256",SidecarEnvelopeSchema,SidecarCleanAttestationSchema,SidecarCandidateCommon,SidecarCandidateSchema,BIDI_RANGES;var init_candidate_sidecar_store=__esm(()=>{init_zod();init_utils2();init_candidate_contract();import_proper_lockfile=__toESM(require_proper_lockfile(),1),SidecarEnvelopeSchema=exports_external.object({record_type:exports_external.literal("invocation"),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),produced_at:exports_external.string().min(1),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),format_families_detected:exports_external.array(exports_external.string()),candidate_count:exports_external.number().int().nonnegative(),parse_errors:exports_external.number().int().nonnegative(),malformed_rows:exports_external.number().int().nonnegative(),clean_attestation_count:exports_external.number().int().nonnegative().optional()}).strict(),SidecarCleanAttestationSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("base_explorer"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict(),exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("micro_lane"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),micro_lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict()]),SidecarCandidateCommon={record_type:exports_external.literal("candidate"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),extracted_from_partial_source:exports_external.boolean(),candidate_id:exports_external.string().min(1),severity:exports_external.enum(CANDIDATE_SEVERITIES),category:exports_external.string().min(1),file_line:exports_external.string().min(1),claim:exports_external.string().min(1),evidence_summary:exports_external.string().min(1),confidence:exports_external.enum(CANDIDATE_CONFIDENCES),risk_impact:exports_external.enum(PR_REVIEW_RISK_IMPACTS).optional(),risk_tags:exports_external.array(exports_external.enum(PR_REVIEW_RISK_TAGS)).optional()},SidecarCandidateSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("base_explorer"),lane:exports_external.string().min(1),micro_lane:exports_external.null(),impact_context:exports_external.string().min(1),invariant_violated:exports_external.null()}).strict(),exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("micro_lane"),lane:exports_external.null(),micro_lane:exports_external.string().min(1),impact_context:exports_external.null(),invariant_violated:exports_external.string().min(1)}).strict()]),BIDI_RANGES=[[8234,8238],[8294,8297]]});function detectRowFormatFamily(rowFields){let trimmed=rowFields.map((f)=>f.trim()),hasImpactContext=trimmed.length>7&&trimmed[7]!=="",hasInvariantViolated=trimmed.length>6&&trimmed[6]!=="";if(hasImpactContext&&!hasInvariantViolated)return"base_explorer";if(hasInvariantViolated&&!hasImpactContext)return"micro_lane";if(hasImpactContext&&hasInvariantViolated)return"base_explorer";throw new UnknownFormatFamilyError}function mapFields(fields,family){let trimmed=fields.map((f)=>f.trim()),names=CANDIDATE_FIELDS[family],result={};for(let i=0;i<names.length;i++)result[names[i]]=i<trimmed.length&&trimmed[i]!==""?trimmed[i]:null;if(family==="base_explorer")result.micro_lane=null,result.invariant_violated=null;else result.lane=null,result.impact_context=null;return result}function getRequiredFields(family){return CANDIDATE_REQUIRED_FIELDS[family]}function assertNonNullCandidateId(value){if(value===null||value==="")throw Error("Invariant violation: null/empty candidate_id reached candidate builder")}function buildInvocationEnvelope(input,flags,formatFamiliesDetected,candidateCount,parseErrors,malformedRows,cleanAttestationCount=0){return{record_type:"invocation",source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,row_format_version:flags.row_format_version,sessionId:input.sessionId,parentSessionId:input.parentSessionId,...flags.producer?{producer:flags.producer}:{},produced_at:input.produced_at,record_version:RECORD_VERSION,format_families_detected:formatFamiliesDetected,candidate_count:candidateCount,parse_errors:parseErrors,malformed_rows:malformedRows,clean_attestation_count:cleanAttestationCount}}function buildEmptyDiagnostics(input,flags){return{candidate_count:0,parse_errors:0,parse_error_details:[],malformed_rows:0,duplicate_id_count:0,duplicate_id_warnings:[],degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:[],clean_attestation_count:0}}function refusalResult(errorCode,errorMessage,input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0);return{error:errorMessage,error_code:errorCode,candidates:[],invocation_envelope:envelope,diagnostics:buildEmptyDiagnostics(input,flags)}}function detectFormatMismatchHint(text){if(text.trim()==="")return;let severityPattern=/\b(CRITICAL|HIGH|MEDIUM|LOW|INFO)\b/,fileLinePattern=/\b\S+\.[a-z]{1,4}:\d+\b/,hasSeverity=severityPattern.test(text),textForFileLine=text.replace(/\b\w+:\/\/\S*/g,""),hasFileLine=fileLinePattern.test(textForFileLine);if(hasSeverity&&hasFileLine)return"Lane output contains severity keywords and file:line references but no parseable [CANDIDATE] rows. The explorer may have emitted findings in prose format instead of pipe-delimited candidate rows.";if(hasSeverity)return"Lane output contains severity keywords but no parseable [CANDIDATE] rows. The explorer may have emitted findings in an unstructured format.";return}function emptyTextResult(input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0),diagnostics=buildEmptyDiagnostics(input,flags),hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint;return{candidates:[],invocation_envelope:envelope,diagnostics}}function parseCandidates(input,flags){let inputParse=ArtifactInputSchema.safeParse(input);if(!inputParse.success)throw Error(`Invalid ArtifactInput: ${inputParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let flagsParse=ParseFlagsSchema.safeParse(flags);if(!flagsParse.success)throw Error(`Invalid ParseFlags: ${flagsParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let validatedInput=inputParse.data,validatedFlags=flagsParse.data;if(validatedInput.artifact_status==="ref-not-found")return refusalResult("ref-not-found","Artifact reference not found in store",validatedInput,validatedFlags);if(validatedInput.artifact_status==="artifact-corrupted")return refusalResult("artifact-corrupted","Artifact data is corrupted",validatedInput,validatedFlags);if(validatedFlags.degraded&&!validatedFlags.accept_degraded)return refusalResult("degraded-source-refused","Degraded source refused by caller",validatedInput,validatedFlags);if(validatedInput.transcriptIncomplete===!0&&!validatedFlags.accept_partial)return refusalResult("partial-source-refused","Partial transcript refused by caller",validatedInput,validatedFlags);if(validatedInput.text.trim()==="")return emptyTextResult(validatedInput,validatedFlags);return parseText(validatedInput,validatedFlags)}function parseText(input,flags){let lines=removeCandidateCodeFences(input.text).split(`
@@ -2458,10 +2458,10 @@ Flags:
2458
2458
  --update sync existing docs to current code/spec instead of generating fresh`;var init_design_docs=__esm(()=>{init_config();init_warning_buffer();_internals135={loadPluginConfigWithMeta}});import*as fs90 from"node:fs";import*as os22 from"node:os";import*as path167 from"node:path";function getPluginConfigDir(){return path167.join(process.env.XDG_CONFIG_HOME||path167.join(os22.homedir(),".config"),"opencode")}function getHostConfigDir(){let override=process.env.OPENCODE_CONFIG_DIR;if(override&&override.trim()!=="")return override;return getPluginConfigDir()}function getHostDataDir(){let base=process.env.XDG_DATA_HOME||path167.join(os22.homedir(),".local","share");return path167.join(base,"opencode")}function getHostCacheDir(){let base=process.env.XDG_CACHE_HOME||path167.join(os22.homedir(),".cache");return path167.join(base,"opencode")}function getHostSkillCacheDir(){return path167.join(getHostCacheDir(),"skills")}function getPluginCachePaths(){let cacheBase=process.env.XDG_CACHE_HOME||path167.join(os22.homedir(),".cache"),configDir=getPluginConfigDir(),paths=[path167.join(cacheBase,"opencode","node_modules","opencode-swarm"),path167.join(cacheBase,"opencode","packages","opencode-swarm@latest"),path167.join(cacheBase,"opencode","packages","opencode-swarm"),path167.join(configDir,"node_modules","opencode-swarm")];if(process.platform==="darwin"){let libCaches=path167.join(os22.homedir(),"Library","Caches");paths.push(path167.join(libCaches,"opencode","node_modules","opencode-swarm"),path167.join(libCaches,"opencode","packages","opencode-swarm@latest"),path167.join(libCaches,"opencode","packages","opencode-swarm"))}if(process.platform==="win32"){let localAppData=process.env.LOCALAPPDATA||path167.join(os22.homedir(),"AppData","Local"),appData=process.env.APPDATA||path167.join(os22.homedir(),"AppData","Roaming");paths.push(path167.join(localAppData,"opencode","node_modules","opencode-swarm"),path167.join(localAppData,"opencode","packages","opencode-swarm@latest"),path167.join(localAppData,"opencode","packages","opencode-swarm"),path167.join(appData,"opencode","node_modules","opencode-swarm"))}return paths}function discoverVersionPinnedCachePaths(){let cacheBase=process.env.XDG_CACHE_HOME||path167.join(os22.homedir(),".cache"),packagesParents=[path167.join(cacheBase,"opencode","packages")];if(process.platform==="darwin"){let libCaches=path167.join(os22.homedir(),"Library","Caches");packagesParents.push(path167.join(libCaches,"opencode","packages"))}if(process.platform==="win32"){let localAppData=process.env.LOCALAPPDATA||path167.join(os22.homedir(),"AppData","Local");packagesParents.push(path167.join(localAppData,"opencode","packages"))}let found=[];for(let parent of packagesParents){let entries2;try{entries2=fs90.readdirSync(parent,{withFileTypes:!0})}catch{continue}for(let entry of entries2){if(!VERSION_PINNED_LEAF.test(entry.name))continue;if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;found.push(path167.join(parent,entry.name))}}return found}function resolveCachePackageRoot(cachePath){let nestedPackageRoot=path167.join(cachePath,"node_modules","opencode-swarm");return fs90.existsSync(nestedPackageRoot)?nestedPackageRoot:cachePath}var VERSION_PINNED_LEAF;var init_cache_paths=__esm(()=>{VERSION_PINNED_LEAF=/^opencode-swarm@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/});import{existsSync as existsSync84,statSync as statSync52}from"node:fs";import{join as join122}from"node:path";function getSwarmDbHealthSnapshot(directory){try{let size=statSync52(projectDbPath(directory)).size;if(size>SWARM_DB_QUICK_CHECK_MAX_BYTES)return{kind:"too_large",sizeBytes:size}}catch{return{kind:"absent"}}let staleMarker=existsSync84(join122(canonicalProjectKey(directory),".swarm","db-migration-failure.json"));try{let db=getProjectDb(directory);return{kind:"open",quickCheck:db.query("PRAGMA quick_check").get()?.quick_check??"unknown",journalMode:db.query("PRAGMA journal_mode").get()?.journal_mode??"unknown",pageCount:db.query("PRAGMA page_count").get()?.page_count??-1,migrationFailures:db.query("SELECT COUNT(*) as n FROM migration_failures").get()?.n??0,staleMarker}}catch(err){return{kind:"error",category:err&&typeof err==="object"&&"category"in err?String(err.category):"unknown",message:err instanceof Error?err.message:String(err)}}}var SWARM_DB_QUICK_CHECK_MAX_BYTES=67108864;var init_health=__esm(()=>{init_canonical_project();init_project_db()});async function readDurableGateEvidence(directory,taskId){try{return await readTaskEvidence(directory,taskId)}catch{return null}}function getDurableGateEvidenceStatus(evidence2){if(!evidence2?.gates||typeof evidence2.gates!=="object")return{isComplete:!1,missingGates:[],evidenceExists:evidence2!=null,invalid:!1};if(!Array.isArray(evidence2.required_gates)||evidence2.required_gates.length===0)return{isComplete:!1,missingGates:["required_gates"],evidenceExists:!0,invalid:!1};let missingGates=evidence2.required_gates.filter((gate)=>evidence2.gates[gate]==null);return{isComplete:missingGates.length===0,missingGates,evidenceExists:!0,invalid:!1}}async function getDurableGateEvidenceStatusForTask(directory,taskId){if(!isValidTaskId(taskId))return{isComplete:!1,missingGates:[],evidenceExists:!1,invalid:!1};try{return getDurableGateEvidenceStatus(readTaskEvidenceRaw(directory,taskId))}catch{return{isComplete:!1,missingGates:["invalid_gate_evidence"],evidenceExists:!0,invalid:!0}}}function gateEvidenceToEntry(taskId,gate,type,evidence2){let gateRecord=evidence2.gates[gate];if(!gateRecord)return null;let base={task_id:taskId,timestamp:gateRecord.timestamp,agent:gateRecord.agent||gate,verdict:"pass",summary:`Gate evidence recorded by ${gate}`,metadata:{source:"durable_gate_evidence",gate}};if(type==="review")return{...base,type,risk:"low",issues:[]};if(type==="approval")return{...base,type};return{...base,type,tests_passed:0,tests_failed:0,failures:[]}}function mergeDurableGateEntriesFromEvidence(taskId,entries2,evidence2){if(!evidence2?.gates)return entries2;let merged=[...entries2];for(let gate of Object.keys(evidence2.gates).sort()){let type=GATE_EVIDENCE_TYPE_BY_GATE[gate]??"approval";if((type==="review"||type==="test")&&merged.some((entry2)=>entry2.type===type))continue;let entry=gateEvidenceToEntry(taskId,gate,type,evidence2);if(entry)merged.push(entry)}return merged}var GATE_EVIDENCE_TYPE_BY_GATE;var init_gate_bridge=__esm(()=>{init_gate_evidence();GATE_EVIDENCE_TYPE_BY_GATE={reviewer:"review",test_engineer:"test"}});function renderRecoveryInvocationQuickForms(docPath="docs/troubleshooting/recovery-runbook.md"){let labels={host:"host command path",powershell:"PowerShell headless","git-bash":"Git Bash (MSYS) headless",cli:"shell-neutral CLI"},notes={host:"",powershell:"","git-bash":" (leading slash doubled — MSYS rewrites a single leading slash; never set MSYS_NO_PATHCONV=1 for the whole invocation)",cli:""};return[`Shell-correct invocations (see ${docPath}):`,...RECOVERY_INVOCATIONS.map((form)=>`- ${labels[form.surface]}: ${form.invocation}${notes[form.surface]}`)].join(`
2459
2459
  `)}var RECOVERY_INVOCATIONS;var init_recovery_invocation=__esm(()=>{RECOVERY_INVOCATIONS=[{surface:"host",invocation:"/swarm recover <task_id>",note:"Host command path — type it verbatim in the OpenCode TUI/GUI command line."},{surface:"powershell",invocation:"opencode run --dir <project-dir> '/swarm recover <task_id>'",note:"PowerShell headless — single quotes keep the /swarm message argument literal."},{surface:"git-bash",invocation:'opencode run --dir <project-dir> "//swarm recover <task_id>"',note:"Git Bash (MSYS) headless — the leading slash is doubled because MSYS rewrites a single leading-slash argument to C:/Program Files/Git/swarm …; do NOT set MSYS_NO_PATHCONV=1 globally (it breaks --dir /c/... conversion)."},{surface:"cli",invocation:"bunx opencode-swarm run recover <task_id> [--force]",note:"Shell-neutral CLI — same command in every shell; --force is an operator assertion that no dispatch is genuinely in flight."}]});function identitySuffix(status2){let parts=[];if(status2.transitionId)parts.push(`transition ${sanitizeDiagnosticText(status2.transitionId)}`);if(typeof status2.generation==="number")parts.push(`generation ${status2.generation}`);return parts.length>0?` (${parts.join(", ")})`:""}function classifySettlementWalState(entry,workflow){let base={taskId:entry.taskId,transitionId:entry.transitionId,generation:entry.expectedGeneration??(workflow&&workflow.authoritative?workflow.generation:void 0)};if(entry.state==="unreadable")return{...base,category:"corrupt",repairAllowed:!1,uncertainExternalEffect:!0,explanation:"settlement WAL is corrupt (unreadable bytes) — recovery refuses corrupt facts instead of rewriting them; the task stays blocked until a human reconciles the file",suggestedNextCommand:"inspect .swarm/coder-settlements/"+entry.taskId+".json and consult docs/troubleshooting/recovery-runbook.md — do not delete or hand-edit the file"};if(entry.ownedByLiveForeignPid)return{...base,category:"ambiguous",repairAllowed:!1,uncertainExternalEffect:!0,explanation:`owned by live foreign process pid ${entry.processId??"?"} (another OpenCode instance) — the dispatch may genuinely be in flight, so this host never interrupts it and the external effect stays uncertain`,suggestedNextCommand:`close that instance (or run /swarm recover ${entry.taskId} there), then re-run diagnose here`};if(entry.ownedInProcess)return{...base,category:"ambiguous",repairAllowed:!1,uncertainExternalEffect:!0,explanation:"in flight, in this process — the dispatch may still complete on its own; releasing it is an operator assertion, not a status claim",suggestedNextCommand:`wait for the dispatch to settle, or re-run /swarm recover ${entry.taskId} --force only if no coder is genuinely running`};if(entry.state==="DISPATCHED"||entry.state==="PREPARED"){let generationConflict=typeof entry.expectedGeneration==="number"&&workflow!==null&&workflow.authoritative&&workflow.generation!==entry.expectedGeneration;return{...base,category:"stale",repairAllowed:!0,uncertainExternalEffect:!1,explanation:`${entry.state.toLowerCase()} settlement whose owning process is gone${generationConflict?` — the WAL's generation fence (${entry.expectedGeneration}) no longer matches the workflow generation (${workflow?.generation}), so the stale receipt cannot be consumed by a normal settle and recovery is the only deterministic path`:""} — blocks dispatches with CODER_DISPATCH_IN_PROGRESS`,suggestedNextCommand:`/swarm recover ${entry.taskId}`}}return{...base,category:"healthy",repairAllowed:!1,uncertainExternalEffect:!1,explanation:`settlement ${entry.state.toLowerCase()}`,suggestedNextCommand:""}}function classifyEvidenceRecoveryTask(taskId,evidence2,greenPreCheck){let snapshot=evidence2?.workflow!==void 0&&evidence2.workflow!==null?{...evidence2.workflow,authoritative:!0}:null;if(snapshot===null)return{taskId,category:"missing",repairAllowed:!1,uncertainExternalEffect:!1,explanation:"no durable receipt exists for this task (no settlement WAL, no evidence workflow) — nothing to repair",suggestedNextCommand:"dispatch the task normally, then re-run diagnose; if it was dispatched, see docs/troubleshooting/recovery-runbook.md"};let base={taskId,transitionId:snapshot.lastTransitionId??void 0,generation:snapshot.generation};if(snapshot.state==="coder_delegated"){if(evidence2?.gates?.pre_check===void 0)return{...base,category:"live_wedge",repairAllowed:greenPreCheck===!0,uncertainExternalEffect:!1,explanation:`live-shaped task wedge — workflow at coder_delegated with no pre_check gate proof${greenPreCheck===!0?" and green post-settlement pre-check bundles: the missing Stage A receipt is deterministically repairable without re-running the coder or editing evidence":greenPreCheck===!1?" but pre-check proof is missing or not green: run pre_check_batch first — the repair refuses to mark Stage A passed without proof":""}`,suggestedNextCommand:`/swarm recover ${taskId}`}}return{...base,category:"healthy",repairAllowed:!1,uncertainExternalEffect:!1,explanation:`workflow ${snapshot.state}`,suggestedNextCommand:""}}function renderTaskRecoveryLine(status2){if(status2.category==="healthy")return"";let suffix=identitySuffix(status2),command=status2.suggestedNextCommand?` — ${status2.suggestedNextCommand}`:"";return`task ${status2.taskId} [${status2.category}] ${status2.explanation}${suffix}${command}`}var init_task_recovery_status=__esm(()=>{init_path_identity()});import{readdir as readdir11}from"node:fs/promises";async function appendStageARepairEvent(directory,payload){try{appendCoreEventSync(directory,{type:"stage_a_repair",timestamp:new Date().toISOString(),...payload})}catch(error93){criticalWarn(`[stage-a-repair] audit event write failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}async function hasGreenPostSettlementPreCheck(directory,settledAfterMs){let sawSecretscanGreen=!1,sawSastGreen=!1;for(let evidenceType of["secretscan","sast_scan"]){let result;try{result=await loadEvidence(directory,evidenceType,{migrate:!1})}catch{continue}if(result.status!=="found")continue;let entryTypeTag=evidenceType==="sast_scan"?"sast":evidenceType,typed=result.bundle.entries.filter((entry)=>entry.type===entryTypeTag);if(typed.length===0)continue;let last=typed[typed.length-1],ts=Date.parse(String(last.timestamp??""));if(settledAfterMs!==null&&Number.isFinite(ts)&&ts<settledAfterMs)return{green:!1,reason:"pre_check_failed_or_stale"};if(evidenceType==="secretscan"){if((last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info")&&isSecretscanEvidence(last)&&(last.incomplete_files??0)===0&&(last.files_scanned??0)>0&&(last.findings_count??0)===0){sawSecretscanGreen=!0;continue}}else if(last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info"){sawSastGreen=!0;continue}if(last.verdict==="fail"||last.verdict==="rejected")return{green:!1,reason:"pre_check_failed_or_stale"}}if(!sawSecretscanGreen||!sawSastGreen)return{green:!1,reason:"no_pre_check_bundles"};return{green:!0}}async function enumerateStageACandidates(directory,requested){let entries2;try{let evidenceDir=validateSwarmPath(directory,"evidence");entries2=await readdir11(evidenceDir)}catch{return{selected:[],truncated:!1}}let candidates=entries2.filter((entry)=>entry.endsWith(".json")&&isStrictTaskId(entry.slice(0,-5))),selected=requested?.length?candidates.filter((entry)=>requested.includes(entry.slice(0,-5))):candidates,truncated=!requested?.length&&candidates.length>MAX_STAGE_A_REPAIR_SCAN;return{selected:selected.sort().slice(0,MAX_STAGE_A_REPAIR_SCAN).map((entry)=>entry.slice(0,-5)),truncated}}async function scanStageATask(directory,taskId,walStates){let evidence2=await readTaskEvidence(directory,taskId),workflow=getTaskWorkflowSnapshot(evidence2);if(workflow.state!=="coder_delegated")return{kind:"not_wedged",state:workflow.state,evidence:evidence2};if(evidence2?.gates?.pre_check)return{kind:"not_wedged",state:workflow.state,evidence:evidence2};let settledAfterMs=null;for(let state2 of walStates){if(state2.taskId!==taskId)continue;if(state2.state!=="COMMITTED")continue;if(state2.recordedAt===void 0)continue;let parsed=Date.parse(state2.recordedAt);if(!Number.isFinite(parsed))continue;settledAfterMs=settledAfterMs===null?parsed:Math.max(settledAfterMs,parsed)}if(settledAfterMs===null){let fallbackTs=Date.parse(workflow.updatedAt);if(Number.isFinite(fallbackTs))settledAfterMs=fallbackTs}let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green)return{kind:"not_green",reason:greenness.reason,evidence:evidence2};return{kind:"repairable",generation:workflow.generation,green:!0,predecessorTransitionId:workflow.lastTransitionId??null,evidence:evidence2}}async function scanWedgedStageA(directory,options){let{selected,truncated}=await enumerateStageACandidates(directory,options?.taskIds),{states:walStates}=await listCoderSettlementWalStates(directory),results=[];for(let taskId of selected)try{let verdict=await scanStageATask(directory,taskId,walStates);if(verdict.kind==="repairable")results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,verdict.green));else if(verdict.kind==="not_green")results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,!1));else results.push(classifyEvidenceRecoveryTask(taskId,verdict.evidence,null))}catch{}return{results,truncated}}async function repairWedgedStageA(directory,options){let requested=options?.taskIds,{selected,truncated}=await enumerateStageACandidates(directory,requested),{states:walStates}=await listCoderSettlementWalStates(directory),results=[];for(let taskId of selected)try{let scan=await scanStageATask(directory,taskId,walStates);if(scan.kind==="not_wedged"){results.push({taskId,outcome:"skipped_not_wedged",state:scan.state});continue}if(scan.kind==="not_green"){results.push({taskId,outcome:"skipped_not_green",reason:scan.reason});continue}let transitionId=`stage-a-repair:${taskId}:${scan.generation}`;await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",expectedGeneration:scan.generation,transitionId}),await appendStageARepairEvent(directory,{action:"repaired",taskId,transitionId,generation:scan.generation,predecessorTransitionId:scan.predecessorTransitionId}),results.push({taskId,outcome:"repaired",generation:scan.generation,transitionId})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendStageARepairEvent(directory,{action:"repair-failed",taskId,message:sanitizeDiagnosticText(message,512)}),results.push({taskId,outcome:"error",message})}return{results,truncated}}var MAX_STAGE_A_REPAIR_SCAN=200;var init_stage_a_repair=__esm(()=>{init_core_events();init_manager2();init_gate_evidence();init_utils2();init_path_identity();init_logger();init_task_id();init_coder_settlement();init_task_recovery_status()});import{existsSync as existsSync85,mkdirSync as mkdirSync54,readFileSync as readFileSync60,writeFileSync as writeFileSync29}from"node:fs";import{homedir as homedir13}from"node:os";import{join as join123}from"node:path";function isStrictSemver(value){return typeof value==="string"&&STRICT_SEMVER.test(value)}function cacheDir(){let xdg=process.env.XDG_CACHE_HOME,base=xdg&&xdg.length>0?xdg:join123(homedir13(),".cache");return join123(base,"opencode-swarm")}function cacheFile(){return join123(cacheDir(),"version-check.json")}function readVersionCache(){try{let path168=cacheFile();if(!existsSync85(path168))return null;let raw=readFileSync60(path168,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed?.checkedAt!=="number")return null;let npmLatest=typeof parsed.npmLatest==="string"?parsed.npmLatest:null;return{checkedAt:parsed.checkedAt,npmLatest}}catch{return null}}function writeVersionCache(entry){try{let dir=cacheDir();mkdirSync54(dir,{recursive:!0}),writeFileSync29(cacheFile(),JSON.stringify(entry,null,2),"utf-8")}catch{}}function parseVersion(version3){let trimmed=version3.trim(),match=SEMVER_REGEX.exec(trimmed);if(!match)return null;return{major:Number.parseInt(match[1],10),minor:Number.parseInt(match[2],10),patch:Number.parseInt(match[3],10),prerelease:match[4]??null}}function normalizeVersionCandidate(version3){if(typeof version3!=="string")return null;let trimmed=version3.trim();return SEMVER_REGEX.test(trimmed)?trimmed:null}function compareVersions(a,b){let aParsed=parseVersion(a),bParsed=parseVersion(b);if(!aParsed||!bParsed)return 0;if(aParsed.major!==bParsed.major)return aParsed.major>bParsed.major?1:-1;if(aParsed.minor!==bParsed.minor)return aParsed.minor>bParsed.minor?1:-1;if(aParsed.patch!==bParsed.patch)return aParsed.patch>bParsed.patch?1:-1;if(aParsed.prerelease&&!bParsed.prerelease)return-1;if(!aParsed.prerelease&&bParsed.prerelease)return 1;if(aParsed.prerelease&&bParsed.prerelease)return aParsed.prerelease<bParsed.prerelease?-1:aParsed.prerelease>bParsed.prerelease?1:0;return 0}async function fetchLatestVersion(signal){try{let res=await _internals136.fetch(NPM_REGISTRY_URL,{signal,headers:{Accept:"application/json"}});if(!res.ok)return null;if(!(res.headers.get("content-type")??"").toLowerCase().includes("json"))return null;let lengthHeader=res.headers.get("content-length");if(lengthHeader){let advertised=Number.parseInt(lengthHeader,10);if(Number.isFinite(advertised)&&advertised>MAX_RESPONSE_BYTES)return null}let text=await res.text();if(text.length>MAX_RESPONSE_BYTES)return null;let body;try{body=JSON.parse(text)}catch{return null}return isStrictSemver(body.version)?body.version:null}catch{return null}}function scheduleVersionCheck(runningVersion,emitWarning,options){if(_checkLatched)return;_checkLatched=!0;let now2=options?.now??(()=>Date.now()),fetchImpl=options?.fetchImpl??fetchLatestVersion;queueMicrotask(()=>{runVersionCheck(runningVersion,emitWarning,now2,fetchImpl).catch(()=>{})})}async function runVersionCheck(runningVersion,emitWarning,now2,fetchImpl){let cached3=readVersionCache(),t=now2();if(cached3&&t-cached3.checkedAt<CHECK_INTERVAL_MS){if(cached3.npmLatest)maybeWarn(runningVersion,cached3.npmLatest,emitWarning);return}let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),FETCH_TIMEOUT_MS),npmLatest=null;try{let fetchedVersion=await fetchImpl(controller.signal);npmLatest=normalizeVersionCandidate(fetchedVersion)}finally{clearTimeout(timeout)}if(writeVersionCache({checkedAt:t,npmLatest}),npmLatest)maybeWarn(runningVersion,npmLatest,emitWarning)}function maybeWarn(runningVersion,npmLatest,emitWarning){if(compareVersions(npmLatest,runningVersion)>0)emitWarning(`[opencode-swarm] Update available: ${runningVersion} → ${npmLatest}. OpenCode caches plugins indefinitely. Run \`bunx opencode-swarm update\` to refresh. Also run \`/swarm config doctor\` to check for available config migrations.`)}var NPM_REGISTRY_URL="https://registry.npmjs.org/opencode-swarm/latest",CHECK_INTERVAL_MS=86400000,FETCH_TIMEOUT_MS=5000,SEMVER_REGEX,MAX_RESPONSE_BYTES=262144,STRICT_SEMVER,_checkLatched=!1,_internals136;var init_version_check=__esm(()=>{SEMVER_REGEX=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,STRICT_SEMVER=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;_internals136={fetch:(input,init)=>fetch(input,init)}});import{existsSync as existsSync86,readFileSync as readFileSync61}from"node:fs";import{readFile as readFile40}from"node:fs/promises";import{join as join124}from"node:path";async function readRawLines(filePath){if(!existsSync86(filePath))return{entries:[],corrupt:0};let content=await readFile40(filePath,"utf-8"),entries2=[],corrupt=0;for(let line of content.split(`
2460
2460
  `)){let trimmed=line.trim();if(!trimmed)continue;try{entries2.push(JSON.parse(trimmed))}catch{corrupt++}}return{entries:entries2,corrupt}}function hasV2Counters(entry){let ro=entry.retrieval_outcomes;if(!ro||typeof ro!=="object")return!1;return typeof ro.shown_count==="number"&&typeof ro.applied_explicit_count==="number"&&typeof ro.ignored_count==="number"}function cacheStatus(){let cache3=readVersionCache();if(!cache3?.npmLatest)return"unknown";return compareVersions(cache3.npmLatest,version3)>0?"stale":"fresh"}async function computeKnowledgeDebug(directory){let swarmPath2=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath2(),eventsPath=resolveKnowledgeEventsPath(directory),[swarmRaw,hiveRaw]=await Promise.all([readRawLines(swarmPath2),readRawLines(hivePath)]),rawEntries=[...swarmRaw.entries,...hiveRaw.entries],corrupt=swarmRaw.corrupt+hiveRaw.corrupt,schemaVersions={},missingV2=0;for(let e of rawEntries){let sv=String(typeof e.schema_version==="number"?e.schema_version:"unknown");if(schemaVersions[sv]=(schemaVersions[sv]??0)+1,!hasV2Counters(e))missingV2++}let normalizedCount=0,active=0,archived=0,quarantined=0,enforcedDirectives=0,escalatedDirectives=0;try{let swarm=await readKnowledge(swarmPath2),hive=await readKnowledge(hivePath);for(let e of[...swarm,...hive]){if(normalizedCount++,e.status==="archived")archived++;else if(e.status==="quarantined")quarantined++;else active++;if(e.status!=="archived"&&e.status!=="quarantined"){if(e.enforcement_mode==="enforce")enforcedDirectives++;if(Array.isArray(e.escalation_history)&&e.escalation_history.length>0)escalatedDirectives++}}}catch{}let rejected2=0;try{rejected2=(await readRejectedLessons(directory)).length}catch{}let eventCount=0,retrieval7d=0,eventsByType={};try{let events=await readKnowledgeEvents(directory);eventCount=events.length;let cutoff=Date.now()-SEVEN_DAYS_MS2;for(let ev of events){if(eventsByType[ev.type]=(eventsByType[ev.type]??0)+1,ev.type!=="retrieved")continue;let t=Date.parse(ev.timestamp);if(!Number.isNaN(t)&&t>=cutoff)retrieval7d++}}catch{}let unactionableQueueDepth=await safeJsonlCount(resolveUnactionablePathSafe(directory)),insightCandidatesPending=await countInsightCandidatesPendingDiagnostic(directory),synonymPairs=0;try{synonymPairs=Object.keys((await readSynonymMap(directory)).pairs).length}catch{}let cohortLinked=!1,cohortPointerVersion=null,cohortLinkId=null,cohortId=null,cohortIdentitySource=null,cohortDegraded=!1,cohortSharedRoot=null,cohortGeneration=null,cohortLocalOrphaned=!1;try{let pointer=readLinkPointer(directory);if(pointer)cohortLinked=!0,cohortPointerVersion=pointer.version,cohortLinkId=pointer.linkId,cohortId=pointer.cohortId??null,cohortIdentitySource=pointer.identitySource??null,cohortDegraded=pointer.degraded??!1,cohortSharedRoot=resolveLinkDir(pointer.linkId),cohortGeneration=pointer.generation??null,cohortLocalOrphaned=getLinkedLocalKnowledgeStatus(directory).orphaned}catch{}let hiveEntriesWithLineage=0,hiveOverridePromotions=0,hiveOverrideEntries=[];try{let hive=await readKnowledge(hivePath);for(let e of hive)if(e.lineage){if(hiveEntriesWithLineage++,e.lineage.actor==="manual-override"){if(hiveOverridePromotions++,hiveOverrideEntries.length<20)hiveOverrideEntries.push({id:e.id,lesson_excerpt:e.lesson.slice(0,80),override_failed_gates:e.lineage.override_failed_gates,reason:e.lineage.reason,promotion_event_id:e.lineage.promotion_event_id})}}}catch{}return{plugin_version:version3,directory,swarm_path:swarmPath2,hive_path:hivePath,events_path:eventsPath,raw_entry_count:rawEntries.length,normalized_entry_count:normalizedCount,corrupt_line_count:corrupt,schema_versions:schemaVersions,entries_missing_v2_counters:missingV2,status_breakdown:{active,archived,quarantined,rejected:rejected2},event_count:eventCount,retrieval_events_7d:retrieval7d,cache_status:cacheStatus(),learning:{unactionable_queue_depth:unactionableQueueDepth,insight_candidates_pending:insightCandidatesPending,synonym_pairs:synonymPairs,enforced_directives:enforcedDirectives,escalated_directives:escalatedDirectives,events_by_type:eventsByType,shown_vs_applied:{shown:eventsByType.retrieved??0,applied_explicit:eventsByType.applied??0,ignored:eventsByType.ignored??0,contradicted:eventsByType.contradicted??0,violated:eventsByType.violated??0,no_relevant:eventsByType.no_relevant??0,unacknowledged:eventsByType.unacknowledged??0}},cohort:{linked:cohortLinked,pointer_version:cohortPointerVersion,link_id:cohortLinkId,cohort_id:cohortId,identity_source:cohortIdentitySource,degraded:cohortDegraded,shared_root:cohortSharedRoot,generation:cohortGeneration,local_orphaned:cohortLocalOrphaned},hive:{entries_with_lineage:hiveEntriesWithLineage,override_promotions:hiveOverridePromotions,override_entries:hiveOverrideEntries},curation:await computeCurationDiagnostics(directory,swarmRaw.entries),memory:computeMemoryCohortDiagnostics(directory)}}function computeMemoryCohortDiagnostics(directory){try{let pointer=readMemoryLinkPointer(directory),provider=null,configFingerprintMatch=null;try{let{loadPluginConfig:loadPluginConfig2}=(init_loader(),__toCommonJS(exports_loader)),cfg=loadPluginConfig2(directory);if(provider=cfg.memory?.provider??null,pointer&&cfg.memory){let cohortConfigPath=join124(resolveLinkDir(pointer.linkId),"memory","memory-cohort-config.json");if(existsSync86(cohortConfigPath)){let stored=JSON.parse(readFileSync61(cohortConfigPath,"utf-8"));if(classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version).status==="comparable"&&typeof stored.fingerprint==="string"){let expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput({provider:cfg.memory.provider??"sqlite",redaction:{rejectDurableSecrets:cfg.memory.redaction?.rejectDurableSecrets??!0},embeddings:{model:cfg.memory.embeddings?.model??"Xenova/all-MiniLM-L6-v2",dimension:cfg.memory.embeddings?.dimension??384,version:cfg.memory.embeddings?.version}}));configFingerprintMatch=stored.fingerprint===expected}}}}catch{}if(pointer)return{linked:!0,pointer_version:pointer.version,link_id:pointer.linkId,cohort_id:pointer.cohortId??null,identity_source:pointer.identitySource??null,degraded:pointer.degraded??!1,shared_root:pointer.linkId?resolveLinkDir(pointer.linkId):null,generation:pointer.generation??null,provider,config_fingerprint_match:configFingerprintMatch};return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider,config_fingerprint_match:null}}catch{return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider:null,config_fingerprint_match:null}}}async function computeCurationDiagnostics(directory,entries2){let scanGeneration=0,scanCompleted=!1,scanRemaining=0;try{let{getScanStatus:getScanStatus2}=await Promise.resolve().then(() => (init_scan_cursor(),exports_scan_cursor)),status2=await getScanStatus2(directory);scanGeneration=status2.generation,scanCompleted=status2.completed,scanRemaining=status2.remaining_estimate}catch{}let configMatch=null;try{let{isLinked:isLinked2}=await Promise.resolve().then(() => (init_knowledge_link(),exports_knowledge_link));if(isLinked2(directory)){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),config3;try{let{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config(),exports_config)),loaded=loadPluginConfigWithMeta2(directory);config3=KnowledgeConfigSchema2.parse(loaded.config.knowledge??{})}catch{config3=KnowledgeConfigSchema2.parse({})}let{cohortConfigFingerprint:cohortConfigFingerprint2}=await Promise.resolve().then(() => (init_config_fingerprint(),exports_config_fingerprint)),{buildConfigFingerprintInput:buildConfigFingerprintInput2,readCohortConfigFingerprint:readCohortConfigFingerprint2}=await Promise.resolve().then(() => (init_curation_policy(),exports_curation_policy)),currentFp=cohortConfigFingerprint2(buildConfigFingerprintInput2(config3)),cohortFp=await readCohortConfigFingerprint2(directory);configMatch=cohortFp===null?null:currentFp===cohortFp}}catch{}let withProvenance=0,unknownOwner=0;for(let e of entries2)if(e.producer!=null)withProvenance++;else unknownOwner++;let pendingProposals=await countPendingProposals(directory);return{scan_generation:scanGeneration,scan_completed:scanCompleted,scan_remaining_estimate:scanRemaining,config_fingerprint_match:configMatch,entries_with_provenance:withProvenance,entries_unknown_owner:unknownOwner,pending_proposals:pendingProposals}}async function countPendingProposals(directory){let proposalsPath;try{proposalsPath=join124(resolveKnowledgeStoreDir(directory),"curation-proposals.jsonl")}catch{return 0}if(!existsSync86(proposalsPath))return 0;try{let records=await readTailJsonl(proposalsPath,{maxEntries:resolveRetentionCap("MAX_CURATION_PROPOSALS",MAX_CURATION_PROPOSALS)}),n=0;for(let parsed of records)if(parsed.status==="pending")n++;return n}catch{return 0}}async function safeJsonlCount(filePath){if(!filePath||!existsSync86(filePath))return 0;try{let content=await readFile40(filePath,"utf-8"),n=0;for(let line of content.split(`
2461
- `))if(line.trim())n++;return n}catch{return 0}}function resolveUnactionablePathSafe(directory){try{return resolveUnactionablePath(directory)}catch{return null}}function resolveInsightCandidatesPathSafe(directory){try{return resolveInsightCandidatesPath(directory)}catch{return null}}async function countInsightCandidatesPendingDiagnostic(directory){try{if(projectDbExists(directory))return countPendingInsightCandidatesDb(directory);return await safeJsonlCount(resolveInsightCandidatesPathSafe(directory))}catch{return 0}}async function checkKnowledgeHealth(directory){let debug;try{debug=await computeKnowledgeDebug(directory)}catch{return{name:"Knowledge health",status:"⚠️",detail:"Could not compute knowledge diagnostics"}}let{status_breakdown:sb,learning:lr,cohort:co,hive:hv,curation:cu}=debug,cohortTag=co.linked?` | cohort[linked id=${co.link_id}${co.cohort_id?` cohort=${co.cohort_id}`:""}${co.identity_source?` via=${co.identity_source}`:""}${co.degraded?" DEGRADED":""}${co.local_orphaned?" local-orphan":""}${co.generation!==null?` gen=${co.generation}`:""}]`:" | cohort[local]",hiveTag=hv.entries_with_lineage>0||hv.override_promotions>0?` | hive[lineage=${hv.entries_with_lineage} overrides=${hv.override_promotions}]`:" | hive[local]",scanPart=cu.scan_completed?`scan[gen=${cu.scan_generation} complete]`:`scan[gen=${cu.scan_generation} remaining=${cu.scan_remaining_estimate}]`,fpPart=cu.config_fingerprint_match===null?"fp=n/a":cu.config_fingerprint_match?"fp=match":"fp=MISMATCH",provenanceTotal=cu.entries_with_provenance+cu.entries_unknown_owner,curationTag=` | curation[${scanPart} ${fpPart} provenance=${cu.entries_with_provenance}/${provenanceTotal} proposals=${cu.pending_proposals}]`,summary=`active=${sb.active} archived=${sb.archived} quarantined=${sb.quarantined} rejected=${sb.rejected} | events=${debug.event_count} (retrieved/7d=${debug.retrieval_events_7d}) | learning[enforce=${lr.enforced_directives} escalated=${lr.escalated_directives} synonyms=${lr.synonym_pairs} unactionable=${lr.unactionable_queue_depth} insights_pending=${lr.insight_candidates_pending}] | schema=${JSON.stringify(debug.schema_versions)}`+cohortTag+hiveTag+curationTag,warnings=[];if(co.linked&&co.degraded)warnings.push(`cohort identity is degraded (via ${co.identity_source}): shared store is machine-local, not portable across machines`);if(co.linked&&co.local_orphaned)warnings.push("local .swarm/knowledge.jsonl is orphaned by the link store (benign; resolver ignores it)");if(lr.unactionable_queue_depth>UNACTIONABLE_BACKLOG_WARN)warnings.push(`${lr.unactionable_queue_depth} lessons stuck in the unactionable queue (curator may not be draining)`);if(lr.insight_candidates_pending>INSIGHT_BACKLOG_WARN)warnings.push(`${lr.insight_candidates_pending} micro-reflection insight candidates pending (curator may not be folding them in)`);if(debug.corrupt_line_count>0)warnings.push(`${debug.corrupt_line_count} corrupt JSONL line(s) (raw=${debug.raw_entry_count} vs normalized=${debug.normalized_entry_count})`);if(debug.entries_missing_v2_counters>0)warnings.push(`${debug.entries_missing_v2_counters} entr(y/ies) missing v2 counters (normalized on read)`);if(debug.cache_status==="stale")warnings.push("stale plugin cache — run `bunx opencode-swarm update` (knowledge tools may be running old code)");if(hv.override_promotions>0){let sample=hv.override_entries[0],gates=sample?.override_failed_gates?.join(",")??"?";warnings.push(`${hv.override_promotions} hive entr(y/ies) promoted via --force override (failed gates: ${gates}${sample?.reason?`; reason: "${sample.reason.slice(0,60)}"`:""})`)}if(cu.config_fingerprint_match===!1)warnings.push("cohort config fingerprint mismatch: this worktree curates with different knowledge semantics than the cohort — align knowledge config across linked worktrees");if(cu.pending_proposals>0)warnings.push(`${cu.pending_proposals} pending curation proposal(s) awaiting confirmation (blocked destructive actions recorded in curation-proposals.jsonl)`);if(warnings.length>0)return{name:"Knowledge health",status:"⚠️",detail:`${summary} — ${warnings.join("; ")}`};return{name:"Knowledge health",status:"✅",detail:summary}}var version3,SEVEN_DAYS_MS2=604800000,UNACTIONABLE_BACKLOG_WARN=100,INSIGHT_BACKLOG_WARN=50;var init_knowledge_diagnostics=__esm(()=>{init_package();init_insight_candidate_store();init_project_db();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_curation_policy();init_memory_link();init_redaction();init_caps();init_jsonl_cap();init_synonym_map();init_version_check();({version:version3}=package_default)});import*as child_process7 from"node:child_process";import{existsSync as existsSync87,readdirSync as readdirSync21,readFileSync as readFileSync62,statSync as statSync53}from"node:fs";import*as path168 from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function checkSwarmDb(directory){let runtime=process.versions.bun===void 0?"node":"bun",runtimeVersion=process.versions.bun??process.versions.node??"unknown",snapshot=getSwarmDbHealthSnapshot(directory);switch(snapshot.kind){case"absent":return{name:"swarm.db",status:"✅",detail:`not created yet (driver: ${runtime} ${runtimeVersion})`};case"too_large":return{name:"swarm.db",status:"⚠️",detail:`${Math.round(snapshot.sizeBytes/1048576)} MiB exceeds the ${Math.round(SWARM_DB_QUICK_CHECK_MAX_BYTES2/1048576)} MiB inline quick_check cap — run an external integrity check (driver: ${runtime} ${runtimeVersion})`};case"error":return{name:"swarm.db",status:"❌",detail:`unavailable (${snapshot.category}): ${snapshot.message}`};case"open":{let markerNote=snapshot.staleMarker?", stale db-migration-failure.json marker present":"",detail=`quick_check ${snapshot.quickCheck}; ${snapshot.journalMode} mode, ${snapshot.pageCount} pages, ${snapshot.migrationFailures} recorded migration failure(s)${markerNote}; driver: ${runtime} ${runtimeVersion}`;if(snapshot.quickCheck!=="ok")return{name:"swarm.db",status:"❌",detail};if(snapshot.migrationFailures>0||snapshot.staleMarker)return{name:"swarm.db",status:"⚠️",detail};return{name:"swarm.db",status:"✅",detail}}}}function validateTaskDag(plan){let allTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)allTaskIds.add(task.id);let missingDeps=[];for(let phase of plan.phases)for(let task of phase.tasks)for(let dep of task.depends)if(!allTaskIds.has(dep))missingDeps.push(`${task.id} depends on missing ${dep}`);return{valid:missingDeps.length===0,missingDeps}}async function checkEvidenceCompleteness(directory,plan){let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length>0){let evidenceTaskIds=new Set(await listEvidenceTaskIds(directory)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(directory,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}if(missingEvidence.length===0)return{name:"Evidence",status:"✅",detail:`All ${completedTaskIds.length} completed tasks have evidence`};else return{name:"Evidence",status:"❌",detail:`${missingEvidence.length} completed task(s) missing evidence: ${missingEvidence.join(", ")}`}}return{name:"Evidence",status:"✅",detail:"No completed tasks yet"}}async function checkSwarmIdentity(plan){let activeSwarmId=process.env.OPENCODE_SWARM_ID;if(plan&&!activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:"Plan exists but OPENCODE_SWARM_ID not set in environment"};if(!plan&&!activeSwarmId)return{name:"Swarm Identity",status:"✅",detail:"No conflict detected"};if(!plan)return{name:"Swarm Identity",status:"✅",detail:`No plan, but OPENCODE_SWARM_ID is '${activeSwarmId}'`};if(plan&&plan.swarm!==activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:`Swarm identity mismatch: plan says '${plan.swarm}', active is '${activeSwarmId}'`};return{name:"Swarm Identity",status:"✅",detail:`Swarm identity consistent: '${plan.swarm}'`}}async function checkPhaseBoundaries(plan){if(!plan)return{name:"Phase Boundaries",status:"✅",detail:"No plan to validate"};let mismatches=[];for(let phase of plan.phases)for(let task of phase.tasks){let taskPhaseNum=parseInt(task.id.split(".")[0],10);if(Number.isNaN(taskPhaseNum))mismatches.push(`Task ${task.id} has invalid phase number`);else if(taskPhaseNum!==phase.id)mismatches.push(`Task ${task.id} found under Phase ${phase.id}`)}if(mismatches.length===0)return{name:"Phase Boundaries",status:"✅",detail:"All tasks correctly aligned to phases"};return{name:"Phase Boundaries",status:"❌",detail:mismatches.join("; ")}}async function checkOrphanedEvidence(directory,plan){if(!plan)return{name:"Orphaned Evidence",status:"✅",detail:"No plan to cross-reference"};let planTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)planTaskIds.add(task.id);try{let orphaned=(await listEvidenceTaskIds(directory)).filter((id)=>!planTaskIds.has(id)&&!/^retro-/.test(id));if(orphaned.length===0)return{name:"Orphaned Evidence",status:"✅",detail:"All evidence entries reference valid plan tasks"};return{name:"Orphaned Evidence",status:"❌",detail:`Evidence for [${orphaned.join(", ")}] not in plan`}}catch{return{name:"Orphaned Evidence",status:"❌",detail:"Could not read evidence directory"}}}async function checkPlanSync(directory,plan){if(!plan)return{name:"Plan Sync",status:"✅",detail:"No plan.json present"};try{let jsonTaskCount=0;for(let phase of plan.phases)jsonTaskCount+=phase.tasks.length;let planMdContent=await readSwarmFileAsync(directory,"plan.md");if(!planMdContent)return{name:"Plan Sync",status:"✅",detail:"plan.md not present"};let mdTaskCount=(planMdContent.match(/^- \[[ xX~]/gm)||[]).length;if(jsonTaskCount===mdTaskCount)return{name:"Plan Sync",status:"✅",detail:`plan.json and plan.md both have ${jsonTaskCount} tasks`};return{name:"Plan Sync",status:"❌",detail:`plan.json: ${jsonTaskCount} tasks, plan.md: ${mdTaskCount} — run /swarm sync-plan`}}catch{return{name:"Plan Sync",status:"❌",detail:"Could not compare plan files"}}}async function checkConfigBackups(directory){try{let backupCount=readdirSync21(directory).filter((f)=>/\.opencode-swarm\.yaml\.bak/.test(f)).length;if(backupCount<=5)return{name:"Config Backups",status:"✅",detail:`${backupCount} backup file(s) — within acceptable range`};if(backupCount<=19)return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — consider cleanup`};return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — cleanup required`}}catch{return{name:"Config Backups",status:"✅",detail:"Could not check backup files"}}}async function checkGitRepository(directory){try{if(!existsSync87(directory)||!statSync53(directory).isDirectory())return{name:"Git Repository",status:"❌",detail:"Invalid directory — cannot check git status"};let gitExecutable=await resolveGitExecutableAsync();return child_process7.execFileSync(gitExecutable,["rev-parse","--git-dir"],{cwd:directory,stdio:"pipe"}),{name:"Git Repository",status:"✅",detail:"Git repository detected"}}catch{return{name:"Git Repository",status:"❌",detail:"Not a git repository — version control recommended"}}}async function checkSpecStaleness(directory,plan){let specContent=readEffectiveSpecSync(directory)?.content??null;if(!specContent)return{name:"Spec Staleness",status:"✅",detail:"No effective spec present"};if(!plan)return{name:"Spec Staleness",status:"✅",detail:"No plan to compare spec against"};let titleMatch=specContent.match(/^#\s+(.+)$/m);if(!titleMatch)return{name:"Spec Staleness",status:"✅",detail:"Spec title not detectable"};let specTitle=titleMatch[1].trim(),planTitle=plan.title.trim();if(specTitle.toLowerCase()===planTitle.toLowerCase())return{name:"Spec Staleness",status:"✅",detail:"Spec and plan titles are aligned"};return{name:"Spec Staleness",status:"❌",detail:`Spec/plan title mismatch: spec says '${specTitle}', plan says '${planTitle}'`}}async function checkConfigParseability(directory){let configPath=path168.join(directory,".opencode/opencode-swarm.json");if(!existsSync87(configPath))return{name:"Config Parseability",status:"✅",detail:"No project config file present (using defaults)"};try{let content=readFileSync62(configPath,"utf-8");return JSON.parse(content),{name:"Config Parseability",status:"✅",detail:"Project config is valid JSON"}}catch(err){return{name:"Config Parseability",status:"❌",detail:`Project config at .opencode/opencode-swarm.json is not valid JSON: ${err instanceof Error?err.message:"Unknown error"}`}}}function resolveGrammarDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/services"),isCliBundle=normalized.endsWith("/cli");return isSource||isCliBundle?path168.join(thisDir,"..","lang","grammars"):path168.join(thisDir,"lang","grammars")}async function checkGrammarWasmFiles(){let grammarFiles=["tree-sitter-javascript.wasm","tree-sitter-typescript.wasm","tree-sitter-tsx.wasm","tree-sitter-python.wasm","tree-sitter-go.wasm","tree-sitter-rust.wasm","tree-sitter-cpp.wasm","tree-sitter-c-sharp.wasm","tree-sitter-css.wasm","tree-sitter-bash.wasm","tree-sitter-ruby.wasm","tree-sitter-php.wasm","tree-sitter-java.wasm","tree-sitter-kotlin.wasm","tree-sitter-swift.wasm","tree-sitter-dart.wasm","tree-sitter-powershell.wasm","tree-sitter-ini.wasm","tree-sitter-regex.wasm"],thisDir=path168.dirname(fileURLToPath4(import.meta.url)),grammarDir=resolveGrammarDir(thisDir),missing=[];if(!existsSync87(path168.join(grammarDir,"tree-sitter.wasm")))missing.push("tree-sitter.wasm (core runtime)");for(let file3 of grammarFiles)if(!existsSync87(path168.join(grammarDir,file3)))missing.push(file3);if(missing.length===0)return{name:"Grammar WASM Files",status:"✅",detail:`Core runtime + all ${grammarFiles.length} grammar WASM files present`};return{name:"Grammar WASM Files",status:"❌",detail:`${missing.length} WASM file(s) missing: ${missing.join(", ")}`}}async function checkCheckpointManifest(directory){let manifestPath2=path168.join(directory,".swarm/checkpoints.json");if(!existsSync87(manifestPath2))return{name:"Checkpoint Manifest",status:"✅",detail:"No checkpoint manifest (no checkpoints saved)"};try{let content=readFileSync62(manifestPath2,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json missing 'checkpoints' array"};let invalidCount=0;for(let cp2 of parsed.checkpoints)if(typeof cp2.label!=="string"||typeof cp2.sha!=="string"||typeof cp2.timestamp!=="string")invalidCount++;if(invalidCount>0)return{name:"Checkpoint Manifest",status:"❌",detail:`${invalidCount} checkpoint(s) have invalid structure (missing label/sha/timestamp)`};return{name:"Checkpoint Manifest",status:"✅",detail:`Checkpoint manifest valid — ${parsed.checkpoints.length} checkpoint(s)`}}catch(err){if(err instanceof SyntaxError)return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json is not valid JSON"};return{name:"Checkpoint Manifest",status:"❌",detail:"Could not read checkpoint manifest"}}}async function checkEventStreamIntegrity(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Event Stream",status:"✅",detail:"No events.jsonl present"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
2461
+ `))if(line.trim())n++;return n}catch{return 0}}function resolveUnactionablePathSafe(directory){try{return resolveUnactionablePath(directory)}catch{return null}}function resolveInsightCandidatesPathSafe(directory){try{return resolveInsightCandidatesPath(directory)}catch{return null}}async function countInsightCandidatesPendingDiagnostic(directory){try{if(projectDbExists(directory))return countPendingInsightCandidatesDb(directory);return await safeJsonlCount(resolveInsightCandidatesPathSafe(directory))}catch{return 0}}async function checkKnowledgeHealth(directory){let debug;try{debug=await computeKnowledgeDebug(directory)}catch{return{name:"Knowledge health",status:"⚠️",detail:"Could not compute knowledge diagnostics"}}let{status_breakdown:sb,learning:lr,cohort:co,hive:hv,curation:cu}=debug,cohortTag=co.linked?` | cohort[linked id=${co.link_id}${co.cohort_id?` cohort=${co.cohort_id}`:""}${co.identity_source?` via=${co.identity_source}`:""}${co.degraded?" DEGRADED":""}${co.local_orphaned?" local-orphan":""}${co.generation!==null?` gen=${co.generation}`:""}]`:" | cohort[local]",hiveTag=hv.entries_with_lineage>0||hv.override_promotions>0?` | hive[lineage=${hv.entries_with_lineage} overrides=${hv.override_promotions}]`:" | hive[local]",scanPart=cu.scan_completed?`scan[gen=${cu.scan_generation} complete]`:`scan[gen=${cu.scan_generation} remaining=${cu.scan_remaining_estimate}]`,fpPart=cu.config_fingerprint_match===null?"fp=n/a":cu.config_fingerprint_match?"fp=match":"fp=MISMATCH",provenanceTotal=cu.entries_with_provenance+cu.entries_unknown_owner,curationTag=` | curation[${scanPart} ${fpPart} provenance=${cu.entries_with_provenance}/${provenanceTotal} proposals=${cu.pending_proposals}]`,summary=`active=${sb.active} archived=${sb.archived} quarantined=${sb.quarantined} rejected=${sb.rejected} | events=${debug.event_count} (retrieved/7d=${debug.retrieval_events_7d}) | learning[enforce=${lr.enforced_directives} escalated=${lr.escalated_directives} synonyms=${lr.synonym_pairs} unactionable=${lr.unactionable_queue_depth} insights_pending=${lr.insight_candidates_pending}] | schema=${JSON.stringify(debug.schema_versions)}`+cohortTag+hiveTag+curationTag,warnings=[];if(co.linked&&co.degraded)warnings.push(`cohort identity is degraded (via ${co.identity_source}): shared store is machine-local, not portable across machines`);if(co.linked&&co.local_orphaned)warnings.push("local .swarm/knowledge.jsonl is orphaned by the link store (benign; resolver ignores it)");if(lr.unactionable_queue_depth>UNACTIONABLE_BACKLOG_WARN)warnings.push(`${lr.unactionable_queue_depth} lessons stuck in the unactionable queue (curator may not be draining)`);if(lr.insight_candidates_pending>INSIGHT_BACKLOG_WARN)warnings.push(`${lr.insight_candidates_pending} micro-reflection insight candidates pending (curator may not be folding them in)`);if(debug.corrupt_line_count>0)warnings.push(`${debug.corrupt_line_count} corrupt JSONL line(s) (raw=${debug.raw_entry_count} vs normalized=${debug.normalized_entry_count})`);if(debug.entries_missing_v2_counters>0)warnings.push(`${debug.entries_missing_v2_counters} entr(y/ies) missing v2 counters (normalized on read)`);if(debug.cache_status==="stale")warnings.push("stale plugin cache — run `bunx opencode-swarm update` (knowledge tools may be running old code)");if(hv.override_promotions>0){let sample=hv.override_entries[0],gates=sample?.override_failed_gates?.join(",")??"?";warnings.push(`${hv.override_promotions} hive entr(y/ies) promoted via --force override (failed gates: ${gates}${sample?.reason?`; reason: "${sample.reason.slice(0,60)}"`:""})`)}if(cu.config_fingerprint_match===!1)warnings.push("cohort config fingerprint mismatch: this worktree curates with different knowledge semantics than the cohort — align knowledge config across linked worktrees");if(cu.pending_proposals>0)warnings.push(`${cu.pending_proposals} pending curation proposal(s) awaiting confirmation (blocked destructive actions recorded in curation-proposals.jsonl)`);if(warnings.length>0)return{name:"Knowledge health",status:"⚠️",detail:`${summary} — ${warnings.join("; ")}`};return{name:"Knowledge health",status:"✅",detail:summary}}var version3,SEVEN_DAYS_MS2=604800000,UNACTIONABLE_BACKLOG_WARN=100,INSIGHT_BACKLOG_WARN=50;var init_knowledge_diagnostics=__esm(()=>{init_package();init_insight_candidate_store();init_project_db();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_curation_policy();init_memory_link();init_redaction();init_caps();init_jsonl_cap();init_synonym_map();init_version_check();({version:version3}=package_default)});import*as child_process7 from"node:child_process";import{existsSync as existsSync87,readdirSync as readdirSync21,readFileSync as readFileSync62,statSync as statSync53}from"node:fs";import*as path168 from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function checkSwarmDb(directory){let runtime=process.versions.bun===void 0?"node":"bun",runtimeVersion=process.versions.bun??process.versions.node??"unknown",snapshot=getSwarmDbHealthSnapshot(directory);switch(snapshot.kind){case"absent":return{name:"swarm.db",status:"✅",detail:`not created yet (driver: ${runtime} ${runtimeVersion})`};case"too_large":return{name:"swarm.db",status:"⚠️",detail:`${Math.round(snapshot.sizeBytes/1048576)} MiB exceeds the ${Math.round(SWARM_DB_QUICK_CHECK_MAX_BYTES2/1048576)} MiB inline quick_check cap — run an external integrity check (driver: ${runtime} ${runtimeVersion})`};case"error":return{name:"swarm.db",status:"❌",detail:`unavailable (${snapshot.category}): ${snapshot.message}`};case"open":{let markerNote=snapshot.staleMarker?", stale db-migration-failure.json marker present":"",detail=`quick_check ${snapshot.quickCheck}; ${snapshot.journalMode} mode, ${snapshot.pageCount} pages, ${snapshot.migrationFailures} recorded migration failure(s)${markerNote}; driver: ${runtime} ${runtimeVersion}`;if(snapshot.quickCheck!=="ok")return{name:"swarm.db",status:"❌",detail};if(snapshot.migrationFailures>0||snapshot.staleMarker)return{name:"swarm.db",status:"⚠️",detail};return{name:"swarm.db",status:"✅",detail}}}}function validateTaskDag(plan){let allTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)allTaskIds.add(task.id);let missingDeps=[];for(let phase of plan.phases)for(let task of phase.tasks)for(let dep of task.depends)if(!allTaskIds.has(dep))missingDeps.push(`${task.id} depends on missing ${dep}`);return{valid:missingDeps.length===0,missingDeps}}async function checkEvidenceCompleteness(directory,plan){let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length>0){let evidenceTaskIds=new Set(await listEvidenceTaskIds(directory)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(directory,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}if(missingEvidence.length===0)return{name:"Evidence",status:"✅",detail:`All ${completedTaskIds.length} completed tasks have evidence`};else return{name:"Evidence",status:"❌",detail:`${missingEvidence.length} completed task(s) missing evidence: ${missingEvidence.join(", ")}`}}return{name:"Evidence",status:"✅",detail:"No completed tasks yet"}}async function checkSwarmIdentity(plan){let activeSwarmId=process.env.OPENCODE_SWARM_ID;if(plan&&!activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:"Plan exists but OPENCODE_SWARM_ID not set in environment"};if(!plan&&!activeSwarmId)return{name:"Swarm Identity",status:"✅",detail:"No conflict detected"};if(!plan)return{name:"Swarm Identity",status:"✅",detail:`No plan, but OPENCODE_SWARM_ID is '${activeSwarmId}'`};if(plan&&plan.swarm!==activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:`Swarm identity mismatch: plan says '${plan.swarm}', active is '${activeSwarmId}'`};return{name:"Swarm Identity",status:"✅",detail:`Swarm identity consistent: '${plan.swarm}'`}}async function checkPhaseBoundaries(plan){if(!plan)return{name:"Phase Boundaries",status:"✅",detail:"No plan to validate"};let mismatches=[];for(let phase of plan.phases)for(let task of phase.tasks){let taskPhaseNum=parseInt(task.id.split(".")[0],10);if(Number.isNaN(taskPhaseNum))mismatches.push(`Task ${task.id} has invalid phase number`);else if(taskPhaseNum!==phase.id)mismatches.push(`Task ${task.id} found under Phase ${phase.id}`)}if(mismatches.length===0)return{name:"Phase Boundaries",status:"✅",detail:"All tasks correctly aligned to phases"};return{name:"Phase Boundaries",status:"❌",detail:mismatches.join("; ")}}async function checkOrphanedEvidence(directory,plan){if(!plan)return{name:"Orphaned Evidence",status:"✅",detail:"No plan to cross-reference"};let planTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)planTaskIds.add(task.id);try{let orphaned=(await listEvidenceTaskIds(directory)).filter((id)=>!planTaskIds.has(id)&&!/^retro-/.test(id));if(orphaned.length===0)return{name:"Orphaned Evidence",status:"✅",detail:"All evidence entries reference valid plan tasks"};return{name:"Orphaned Evidence",status:"❌",detail:`Evidence for [${orphaned.join(", ")}] not in plan`}}catch{return{name:"Orphaned Evidence",status:"❌",detail:"Could not read evidence directory"}}}async function checkPlanSync(directory,plan){if(!plan)return{name:"Plan Sync",status:"✅",detail:"No plan.json present"};try{let jsonTaskCount=0;for(let phase of plan.phases)jsonTaskCount+=phase.tasks.length;let planMdContent=await readSwarmFileAsync(directory,"plan.md");if(!planMdContent)return{name:"Plan Sync",status:"✅",detail:"plan.md not present"};let mdTaskCount=(planMdContent.match(/^- \[[ xX~]/gm)||[]).length;if(jsonTaskCount===mdTaskCount)return{name:"Plan Sync",status:"✅",detail:`plan.json and plan.md both have ${jsonTaskCount} tasks`};return{name:"Plan Sync",status:"❌",detail:`plan.json: ${jsonTaskCount} tasks, plan.md: ${mdTaskCount} — run /swarm sync-plan`}}catch{return{name:"Plan Sync",status:"❌",detail:"Could not compare plan files"}}}async function checkConfigBackups(directory){try{let backupCount=readdirSync21(directory).filter((f)=>/\.opencode-swarm\.yaml\.bak/.test(f)).length;if(backupCount<=5)return{name:"Config Backups",status:"✅",detail:`${backupCount} backup file(s) — within acceptable range`};if(backupCount<=19)return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — consider cleanup`};return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — cleanup required`}}catch{return{name:"Config Backups",status:"✅",detail:"Could not check backup files"}}}function isSpawnTimeoutLike(err){if(typeof err!=="object"||err===null)return!1;let e=err;return e.killed===!0||e.signal==="SIGKILL"||e.signal==="SIGTERM"||e.code==="ETIMEDOUT"}async function checkGitRepository(directory){try{if(!existsSync87(directory)||!statSync53(directory).isDirectory())return{name:"Git Repository",status:"❌",detail:"Invalid directory — cannot check git status"};let gitExecutable=await resolveGitExecutableAsync();return _internals137.execFileSync(gitExecutable,["rev-parse","--git-dir"],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:GIT_REPOSITORY_CHECK_TIMEOUT_MS,killSignal:"SIGKILL",maxBuffer:GIT_REPOSITORY_CHECK_MAX_BUFFER_BYTES,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),{name:"Git Repository",status:"✅",detail:"Git repository detected"}}catch(err){if(isSpawnTimeoutLike(err))return{name:"Git Repository",status:"⬜",detail:`git rev-parse did not answer within ${GIT_REPOSITORY_CHECK_TIMEOUT_MS} ms — git state unknown`};return{name:"Git Repository",status:"❌",detail:"Not a git repository — version control recommended"}}}async function checkSpecStaleness(directory,plan){let specContent=readEffectiveSpecSync(directory)?.content??null;if(!specContent)return{name:"Spec Staleness",status:"✅",detail:"No effective spec present"};if(!plan)return{name:"Spec Staleness",status:"✅",detail:"No plan to compare spec against"};let titleMatch=specContent.match(/^#\s+(.+)$/m);if(!titleMatch)return{name:"Spec Staleness",status:"✅",detail:"Spec title not detectable"};let specTitle=titleMatch[1].trim(),planTitle=plan.title.trim();if(specTitle.toLowerCase()===planTitle.toLowerCase())return{name:"Spec Staleness",status:"✅",detail:"Spec and plan titles are aligned"};return{name:"Spec Staleness",status:"❌",detail:`Spec/plan title mismatch: spec says '${specTitle}', plan says '${planTitle}'`}}async function checkConfigParseability(directory){let configPath=path168.join(directory,".opencode/opencode-swarm.json");if(!existsSync87(configPath))return{name:"Config Parseability",status:"✅",detail:"No project config file present (using defaults)"};try{let content=readFileSync62(configPath,"utf-8");return JSON.parse(content),{name:"Config Parseability",status:"✅",detail:"Project config is valid JSON"}}catch(err){return{name:"Config Parseability",status:"❌",detail:`Project config at .opencode/opencode-swarm.json is not valid JSON: ${err instanceof Error?err.message:"Unknown error"}`}}}function resolveGrammarDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/services"),isCliBundle=normalized.endsWith("/cli");return isSource||isCliBundle?path168.join(thisDir,"..","lang","grammars"):path168.join(thisDir,"lang","grammars")}async function checkGrammarWasmFiles(){let grammarFiles=["tree-sitter-javascript.wasm","tree-sitter-typescript.wasm","tree-sitter-tsx.wasm","tree-sitter-python.wasm","tree-sitter-go.wasm","tree-sitter-rust.wasm","tree-sitter-cpp.wasm","tree-sitter-c-sharp.wasm","tree-sitter-css.wasm","tree-sitter-bash.wasm","tree-sitter-ruby.wasm","tree-sitter-php.wasm","tree-sitter-java.wasm","tree-sitter-kotlin.wasm","tree-sitter-swift.wasm","tree-sitter-dart.wasm","tree-sitter-powershell.wasm","tree-sitter-ini.wasm","tree-sitter-regex.wasm"],thisDir=path168.dirname(fileURLToPath4(import.meta.url)),grammarDir=resolveGrammarDir(thisDir),missing=[];if(!existsSync87(path168.join(grammarDir,"tree-sitter.wasm")))missing.push("tree-sitter.wasm (core runtime)");for(let file3 of grammarFiles)if(!existsSync87(path168.join(grammarDir,file3)))missing.push(file3);if(missing.length===0)return{name:"Grammar WASM Files",status:"✅",detail:`Core runtime + all ${grammarFiles.length} grammar WASM files present`};return{name:"Grammar WASM Files",status:"❌",detail:`${missing.length} WASM file(s) missing: ${missing.join(", ")}`}}async function checkCheckpointManifest(directory){let manifestPath2=path168.join(directory,".swarm/checkpoints.json");if(!existsSync87(manifestPath2))return{name:"Checkpoint Manifest",status:"✅",detail:"No checkpoint manifest (no checkpoints saved)"};try{let content=readFileSync62(manifestPath2,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json missing 'checkpoints' array"};let invalidCount=0;for(let cp2 of parsed.checkpoints)if(typeof cp2.label!=="string"||typeof cp2.sha!=="string"||typeof cp2.timestamp!=="string")invalidCount++;if(invalidCount>0)return{name:"Checkpoint Manifest",status:"❌",detail:`${invalidCount} checkpoint(s) have invalid structure (missing label/sha/timestamp)`};return{name:"Checkpoint Manifest",status:"✅",detail:`Checkpoint manifest valid — ${parsed.checkpoints.length} checkpoint(s)`}}catch(err){if(err instanceof SyntaxError)return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json is not valid JSON"};return{name:"Checkpoint Manifest",status:"❌",detail:"Could not read checkpoint manifest"}}}async function checkEventStreamIntegrity(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Event Stream",status:"✅",detail:"No events.jsonl present"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
2462
2462
  `).filter((line)=>line.trim()!==""),malformedCount=0;for(let line of lines)try{JSON.parse(line)}catch{malformedCount++}let coverageNote=window2.coverage==="truncated"?" (retained window — compacted history excluded)":"";if(malformedCount===0)return{name:"Event Stream",status:"✅",detail:`events.jsonl is valid — ${lines.length} event(s)${coverageNote}`};return{name:"Event Stream",status:"❌",detail:`events.jsonl has ${malformedCount} malformed line(s) — possible data corruption`}}catch{return{name:"Event Stream",status:"❌",detail:"Could not read events.jsonl"}}}async function checkSteeringDirectives(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Steering Directives",status:"✅",detail:"No events.jsonl — no steering directives to check"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
2463
2463
  `).filter((line)=>line.trim()!==""),directivesIssued=[],consumedIds=new Set;for(let line of lines)try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directivesIssued.push(parsed.directiveId);if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}let unconsumed=directivesIssued.filter((id)=>!consumedIds.has(id));if(unconsumed.length===0)return{name:"Steering Directives",status:"✅",detail:`All steering directives acknowledged (or none issued)${window2.coverage==="truncated"?" (within the retained event window)":""}`};return{name:"Steering Directives",status:"❌",detail:`${unconsumed.length} steering directive(s) not yet acknowledged`}}catch{return{name:"Steering Directives",status:"❌",detail:"Could not read events.jsonl"}}}async function checkLearningHealth(directory){try{let snapshot=await readLearningHealth(directory);if(snapshot.activeAlarms.length===0)return{name:"Learning health",status:"✅",detail:`No active alarms (${snapshot.totalTransitions} transitions recorded)`};let detail=snapshot.activeAlarms.map((alarm)=>{let ageMinutes=Math.floor(alarm.ageMs/60000);return`${alarm.severity} ${alarm.alarm} [${alarm.scopeClass} ${alarm.scopeRef}] age ${ageMinutes}m coverage ${alarm.coverageFacts}`}).join("; ");return{name:"Learning health",status:"⚠️",detail:`${snapshot.activeAlarms.length} active alarm(s): ${detail}`}}catch{return{name:"Learning health",status:"⬜",detail:"Learning-health artifact unreadable (fail-open)"}}}async function checkCurator(directory){try{if(!loadPluginConfig(directory).curator?.enabled)return{name:"Curator",status:"✅",detail:"Disabled (enable via curator.enabled)"};let summaryPath=path168.join(directory,".swarm/curator-summary.json");if(!existsSync87(summaryPath))return{name:"Curator",status:"✅",detail:"Enabled, no summary yet (waiting for first phase)"};try{let content=readFileSync62(summaryPath,"utf-8"),parsed=JSON.parse(content);if(typeof parsed.schema_version!=="number"||parsed.schema_version!==1)return{name:"Curator",status:"❌",detail:`curator-summary.json has invalid schema_version (expected 1, got ${JSON.stringify(parsed.schema_version)})`};let phaseInfo=parsed.last_phase_covered!==void 0?`phase ${parsed.last_phase_covered}`:"unknown phase",timeInfo=parsed.last_updated?`, updated ${parsed.last_updated}`:"";return{name:"Curator",status:"✅",detail:`Summary present — covering ${phaseInfo}${timeInfo}`}}catch(err){return{name:"Curator",status:"❌",detail:`curator-summary.json is corrupt or invalid: ${err instanceof Error?err.message:"Unknown error"}`}}}catch(err){return{name:"Curator",status:"❌",detail:`Could not check curator state: ${err instanceof Error?err.message:"Unknown error"}`}}}async function getSandboxStatus(sessionID){try{let capability=await _internals137.detectSandboxCapability(),mechanism=capability.mechanism??"none",legacyDimension=capability.status==="enabled"?"weak":"none",filesystem=capability.filesystem??legacyDimension,network=capability.network??legacyDimension,processBoundary=capability.process??legacyDimension,effective=capability.effective??legacyDimension,dimensions=`fs=${filesystem} network=${network} process=${processBoundary} effective=${effective}`,reasons=(capability.reasons??[]).join("; "),skipSummary=getSandboxSkipSummary(sessionID),skipDetail=skipSummary.count>0?` | observed skips=${skipSummary.count}: ${skipSummary.reasons.join("; ")}`:"",executor=await _internals137.getSandboxExecutor(),hasExecutor=executor!==null,downgradeReason=executor?.probeResult?.error??executor?.disabledReason??null,downgradeDetail=downgradeReason!==null&&downgradeReason!==void 0?` | downgrade reason: ${sanitizeDiagnosticText(downgradeReason,200)}`:"";if(hasExecutor){let executorStrength=executor?.strength,strength=executorStrength==="weak"||executorStrength==="advisory"?"advisory":capability.strength??executorStrength??"strong";if(effective!=="real"||strength==="advisory")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | ${dimensions} | Partial boundary: ${reasons}${downgradeDetail}${skipDetail}`};return{name:"Sandbox",status:"✅",detail:`Mechanism: ${mechanism.toLowerCase()} | ${dimensions} | Sandboxing requested dimensions: yes${skipDetail}`}}if(mechanism!=="none")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | ${dimensions} | Available: no | ${reasons}${skipDetail}`};return{name:"Sandbox",status:"⬜",detail:`Mechanism: ${mechanism.toLowerCase()} | Commands not sandboxed`}}catch(error93){return{name:"Sandbox",status:"⬜",detail:`Sandbox status unknown (${error93 instanceof Error?error93.message:"Unknown error"})`}}}async function checkResidueInventory(directory){try{let inventory=await inventorySwarmResidue(directory),s=inventory.summary;if(s.matched===0)return{name:"Atomic-write residue",status:"✅",detail:"No registered temp-grammar residue under .swarm/"};let oldestMin=Math.round(s.oldestAgeMs/60000);return{name:"Atomic-write residue",status:"⚠️",detail:`${s.matched} stale temp file(s) (${s.totalBytes} bytes, oldest ${oldestMin}m old): ${s.eligible} quarantine-eligible, ${s.ambiguous} preserved as recent/active/tracked/ambiguous`+(inventory.gitState==="unknown"?" (git tracked-state unknown — nothing auto-quarantined)":"")+". Run /swarm config doctor for the full inventory, /swarm config doctor --quarantine-residue to act."}}catch(err){return{name:"Atomic-write residue",status:"⬜",detail:`Inventory unavailable: ${err instanceof Error?err.message:String(err)}`}}}async function getDiagnoseData(directory,sessionID){let checks5=[],versionCache=readVersionCache(),versionDetail=version4,versionStatus="✅";if(versionCache?.npmLatest){let ageMs=Date.now()-versionCache.checkedAt,ageMin=Math.max(0,Math.round(ageMs/60000));if(compareVersions(versionCache.npmLatest,version4)>0)versionStatus="⚠️",versionDetail=`${version4} (npm latest: ${versionCache.npmLatest}, checked ${ageMin}m ago) `+"— run `bunx opencode-swarm update` to refresh";else versionDetail=`${version4} (npm latest: ${versionCache.npmLatest}, checked ${ageMin}m ago)`}checks5.push({name:"Version",status:versionStatus,detail:versionDetail}),checks5.push(checkSwarmDb(directory));let plan=await loadPlanJsonOnly(directory);if(plan){if(checks5.push({name:"plan.json",status:"✅",detail:"Valid schema (v1.0.0)"}),plan.migration_status==="migrated")checks5.push({name:"Migration",status:"✅",detail:"Plan was migrated from legacy plan.md"});else if(plan.migration_status==="migration_failed")checks5.push({name:"Migration",status:"❌",detail:"Migration from plan.md failed — review manually"});let dagResult=validateTaskDag(plan);if(dagResult.valid)checks5.push({name:"Task DAG",status:"✅",detail:"All dependencies resolved"});else checks5.push({name:"Task DAG",status:"❌",detail:`Missing dependencies: ${dagResult.missingDeps.join(", ")}`});let evidenceCheck=await checkEvidenceCompleteness(directory,plan);checks5.push(evidenceCheck)}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(planContent){let hasPhases=/^## Phase \d+/m.test(planContent),hasTasks=/^- \[[ x]\]/m.test(planContent);if(hasPhases&&hasTasks)checks5.push({name:"plan.md",status:"✅",detail:"Found with valid phase structure"});else checks5.push({name:"plan.md",status:"❌",detail:"Found but missing phase/task structure"})}else checks5.push({name:"plan.md",status:"❌",detail:"Not found"})}try{let{states:settlementStates,truncated}=await listCoderSettlementWalStates(directory),truncationNote=truncated?" MORE settlement WALs exist than the scan cap (200) — older ones are not shown.":"",settlementStatuses=[];for(let entry of settlementStates){let workflow=null;try{workflow=getTaskWorkflowSnapshot(await readTaskEvidence(directory,entry.taskId))}catch{workflow=null}settlementStatuses.push(classifySettlementWalState(entry,workflow))}let wedgeScan=await scanWedgedStageA(directory),wedgeStatuses=wedgeScan.results.filter((status2)=>status2.category==="live_wedge"),knownTaskIds=new Set([...settlementStates.map((entry)=>entry.taskId),...wedgeScan.results.map((status2)=>status2.taskId)]),missingStatuses=[];if(!truncated&&!wedgeScan.truncated){let planTaskIds=(plan?.phases??[]).flatMap((phase)=>phase.tasks.map((task)=>task.id)).slice(0,200);for(let taskId of planTaskIds){if(knownTaskIds.has(taskId))continue;missingStatuses.push(classifyEvidenceRecoveryTask(taskId,null,null))}}let nonHealthy=[...settlementStatuses.filter((s)=>s.category!=="healthy"),...wedgeStatuses],missingLines=missingStatuses.map(renderTaskRecoveryLine).filter(Boolean),healthyCount=settlementStatuses.filter((s)=>s.category==="healthy").length;if(nonHealthy.length===0&&!truncated)checks5.push({name:"Coder Settlements",status:"✅",detail:`${missingLines.length>0?`${missingLines.join("; ")}. `:""}${settlementStates.length===0?"No coder settlement WALs":`${settlementStates.length} settlement(s) all in terminal state`}`});else if(nonHealthy.length===0&&truncated)checks5.push({name:"Coder Settlements",status:"⚠️",detail:`All shown settlements are terminal, but the scan was truncated.${truncationNote} ${renderRecoveryInvocationQuickForms()}`});else{let lines=[...nonHealthy.map(renderTaskRecoveryLine).filter(Boolean),...missingLines];checks5.push({name:"Coder Settlements",status:"⚠️",detail:`${lines.join("; ")}${healthyCount>0?`; ${healthyCount} healthy settlement(s)`:""}. Categories: missing/stale/ambiguous/corrupt/live_wedge — stale settlements block dispatches with CODER_DISPATCH_IN_PROGRESS. ${renderRecoveryInvocationQuickForms()}${truncationNote}`})}}catch(error93){checks5.push({name:"Coder Settlements",status:"⚠️",detail:`could not inspect coder settlements: ${error93 instanceof Error?error93.message:String(error93)}`})}if(await readSwarmFileAsync(directory,"context.md"))checks5.push({name:"context.md",status:"✅",detail:"Found"});else checks5.push({name:"context.md",status:"❌",detail:"Not found"});try{if(loadPluginConfig(directory))checks5.push({name:"Plugin config",status:"✅",detail:"Valid configuration loaded"});else checks5.push({name:"Plugin config",status:"✅",detail:"Using defaults (no custom config)"})}catch{checks5.push({name:"Plugin config",status:"❌",detail:"Invalid configuration"})}checks5.push(await checkSwarmIdentity(plan)),checks5.push(await checkPhaseBoundaries(plan)),checks5.push(await checkOrphanedEvidence(directory,plan)),checks5.push(await checkPlanSync(directory,plan)),checks5.push(await checkConfigBackups(directory)),checks5.push(await checkGitRepository(directory)),checks5.push(await getSandboxStatus(sessionID)),checks5.push(await checkSpecStaleness(directory,plan)),checks5.push(await checkConfigParseability(directory)),checks5.push(await checkGrammarWasmFiles()),checks5.push(await checkCheckpointManifest(directory)),checks5.push(await checkEventStreamIntegrity(directory)),checks5.push(await checkSteeringDirectives(directory)),checks5.push(await checkCurator(directory)),checks5.push(await checkKnowledgeHealth(directory)),checks5.push(await checkLearningHealth(directory)),checks5.push(await checkResidueInventory(directory));try{let evidenceDir=path168.join(directory,".swarm","evidence"),snapshotFiles=existsSync87(evidenceDir)?readdirSync21(evidenceDir).filter((f)=>f.startsWith("agent-tools-")&&f.endsWith(".json")):[];if(snapshotFiles.length>0){let latest=snapshotFiles.sort().pop();checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:`${snapshotFiles.length} snapshot(s) found — latest: ${latest}`})}else checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:"No snapshots yet (snapshots written on next session start)"})}catch{checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:"No snapshots yet (snapshots written on next session start)"})}if(getDeferredWarnings().length>0)checks5.push({name:"Deferred Warnings",status:"⚠️",detail:`${getDeferredWarnings().length} warning(s) deferred from init — see the Deferred Warnings section below (or set OPENCODE_SWARM_DEBUG=1 for full detail)`});let cachePaths=[...getPluginCachePaths(),...discoverVersionPinnedCachePaths()],cacheRows=[];for(let cachePath of cachePaths)try{if(!existsSync87(cachePath)){cacheRows.push(`⬜ ${cachePath} — absent`);continue}let packageRoot=resolveCachePackageRoot(cachePath),cacheLabel=packageRoot===cachePath?cachePath:`${cachePath} -> ${packageRoot}`,missingGrammarAssets=REQUIRED_CACHE_GRAMMAR_ASSETS.filter((file3)=>!existsSync87(path168.join(packageRoot,"dist","lang","grammars",file3))),pkgJsonPath=path168.join(packageRoot,"package.json");try{let raw=readFileSync62(pkgJsonPath,"utf-8"),parsed=JSON.parse(raw),installedVersion=typeof parsed.version==="string"?parsed.version:"?";if(missingGrammarAssets.length>0){cacheRows.push(`⚠️ ${cacheLabel} — v${installedVersion}, missing grammar assets: ${missingGrammarAssets.join(", ")}; run \`bunx opencode-swarm update\` and restart OpenCode`);continue}cacheRows.push(`✅ ${cacheLabel} — v${installedVersion}`)}catch{cacheRows.push(`⚠️ ${cacheLabel} — present (package.json unreadable)`)}}catch{cacheRows.push(`⚠️ ${cachePath} — status unknown (read error)`)}let hasCacheEntry=cacheRows.some((r)=>r.startsWith("✅")),cacheStatus2=cacheRows.some((r)=>r.startsWith("⚠️"))?"⚠️":hasCacheEntry?"✅":"⬜";if(checks5.push({name:"Plugin Caches",status:cacheStatus2,detail:cacheRows.join(" | ")}),!sessionID)checks5.push({name:"Invocation recovery",status:"⬜",detail:"Session unavailable; scoped circuit and model status omitted"});else{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0,circuits=invocationID>0?listBlockingActionCircuitsForInvocation(sessionID,invocationID):[],circuitRows=[...circuits].sort((a,b)=>b.count-a.count||a.actionDigest.localeCompare(b.actionDigest)).slice(0,3).map((entry)=>`${entry.circuitKind} digest ${entry.actionDigest} (count ${entry.count}) → /swarm guardrail reset ${entry.actionDigest} --invocation ${invocationID}`);if(circuits.length>3)circuitRows.push(`+ ${circuits.length-3} more`);circuitRows.push("fresh re-delegation or a full plugin restart also resets (circuits are in-memory, TTL 30m)"),checks5.push({name:"Invocation circuits",status:circuits.length>0?"⚠️":"✅",detail:circuits.length>0?`${circuits.length} exact-action circuit(s) open for invocation ${invocationID}: ${circuitRows.join(" | ")}`:`No exact-action circuits open${invocationID>0?` for invocation ${invocationID}`:""}`});let selections=getTaskModelRoutingStateSnapshot().scopedSelections.filter((entry)=>entry.key.sessionID===sessionID);checks5.push({name:"Model fallback scope",status:selections.length>0?"⚠️":"✅",detail:selections.length>0?`${selections.length} scoped selection(s) active; highest fallback index ${Math.max(...selections.map((entry)=>entry.fallbackIndex))}`:"No scoped model override is active"});let fullAuto=loadFullAutoRunState(directory,sessionID);checks5.push({name:"Full-Auto recovery",status:fullAuto?.status==="paused"?"⚠️":"✅",detail:fullAuto?`status=${fullAuto.status}; recovery_probe=${fullAuto.lastRecoveryProbe?.outcome??"none"}`:"No durable Full-Auto run state for this session"})}let passCount=checks5.filter((c)=>c.status==="✅"||c.status==="⬜").length,totalCount=checks5.length;return{checks:checks5,passCount,totalCount,allPassed:passCount===totalCount,deferredWarnings:getDeferredWarnings()}}function formatDiagnoseMarkdown(diagnose){let lines=["## Swarm Health Check","",...diagnose.checks.map((c)=>`- ${c.status} **${c.name}**: ${c.detail}`),"",`**Result**: ${diagnose.allPassed?"✅ All checks passed":`⚠️ ${diagnose.passCount}/${diagnose.totalCount} checks passed`}`];if(diagnose.deferredWarnings.length>0){lines.push(""),lines.push("## Deferred Warnings"),lines.push("");for(let warning of diagnose.deferredWarnings)lines.push(`- ${warning}`)}return lines.join(`
2464
- `)}async function handleDiagnoseCommand(directory,_args,sessionID){let diagnoseData=await getDiagnoseData(directory,sessionID);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals137,SWARM_DB_QUICK_CHECK_MAX_BYTES2=67108864;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_health();init_core_events();init_gate_bridge();init_manager2();init_action_circuit();init_state3();init_gate_evidence();init_learning_health();init_utils2();init_task_model_routing();init_manager();init_capability_probe();init_executor();init_skip_state();init_path_identity();init_effective_spec();init_state2();init_git_executable();init_coder_settlement();init_recovery_invocation();init_stage_a_repair();init_task_recovery_status();init_knowledge_diagnostics();init_swarm_residue();init_version_check();init_warning_buffer();({version:version4}=package_default),sandboxCapabilityProbe=new SandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS=["tree-sitter.wasm","tree-sitter-javascript.wasm","tree-sitter-typescript.wasm"],_internals137={detectSandboxCapability:()=>sandboxCapabilityProbe.detect(),getSandboxExecutor:getExecutor}});var init_diagnose=__esm(()=>{init_diagnose_service()});var exports_config_doctor={};__export(exports_config_doctor,{writeDoctorArtifact:()=>writeDoctorArtifact,writeBackupArtifact:()=>writeBackupArtifact,shouldRunOnStartup:()=>shouldRunOnStartup,runConfigDoctorWithFixes:()=>runConfigDoctorWithFixes,runConfigDoctor:()=>runConfigDoctor,restoreFromBackup:()=>restoreFromBackup,removeStraySwarmDir:()=>removeStraySwarmDir,readDoctorArtifact:()=>readDoctorArtifact,getConfigPaths:()=>getConfigPaths,detectStraySwarmDirs:()=>detectStraySwarmDirs,createConfigBackup:()=>createConfigBackup,collectLeanTurboGateSatisfiabilityFindings:()=>collectLeanTurboGateSatisfiabilityFindings,applySafeAutoFixes:()=>applySafeAutoFixes,LEAN_TURBO_GATE_PRODUCERS:()=>LEAN_TURBO_GATE_PRODUCERS});import*as crypto9 from"node:crypto";import*as fs91 from"node:fs";import*as os23 from"node:os";import*as path169 from"node:path";function levenshteinDistance(a,b){let al=a.length,bl=b.length,matrix=[];for(let i=0;i<=al;i++)matrix[i]=[i];for(let j=0;j<=bl;j++)matrix[0][j]=j;for(let i=1;i<=al;i++)for(let j=1;j<=bl;j++){let cost=a[i-1]===b[j-1]?0:1;matrix[i][j]=Math.min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+cost)}return matrix[al][bl]}function emitObjectTypeMismatch(key2,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key2}-type`,title:`Invalid ${key2} type`,description:`"${key2}" must be an object, got ${typeof value}`,severity:"error",path:key2,currentValue:value,autoFixable:!1})}function isPlainObject5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function collectRawCouncilPolicyFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.council===void 0)continue;if(!isPlainObject5(raw.council))continue;let council=raw.council;if("parallelTimeoutMs"in council)findings.push({id:"council-parallel-timeout-deprecated",title:"Deprecated and inert: council.parallelTimeoutMs",description:'Config field "council.parallelTimeoutMs" (in '+configPath+") is deprecated and inert: no runtime consumer exists and no timeout is enforced. It is accepted only for parse compatibility. Remove the key — dispatch timeouts are governed by the agent host. The field is scheduled for removal in a future release.",severity:"warn",path:"council.parallelTimeoutMs",currentValue:council.parallelTimeoutMs,autoFixable:!1});if("escalateOnMaxRounds"in council)findings.push({id:"council-escalate-inert",title:"Inert: council.escalateOnMaxRounds",description:'Config field "council.escalateOnMaxRounds" (in '+configPath+") is set, but the handler/webhook remains INERT in this release: no handler, webhook, or outbound execution exists or was added (issue #1650). Max-rounds exhaustion emits a durable structured event (.swarm/council/events/max-rounds-exhaustion.jsonl) and a user escalation message instead; the run stays fail-closed. Wiring real outbound escalation requires a separate security review.",severity:"warn",path:"council.escalateOnMaxRounds",currentValue:"[redacted: handler/webhook strings are never echoed]",autoFixable:!1});if(isPlainObject5(council.finalCompletionPolicy)&&council.finalCompletionPolicy.mode==="quorum")findings.push({id:"council-final-quorum-weaker",title:'council.finalCompletionPolicy.mode "quorum" weakens the strict final council',description:"Final-council completion is configured in quorum mode (in "+configPath+"): a bounded minimum of distinct canonical members can accept the project instead of the strict default (all five canonical roles, zero absentees). This is weaker than the strict default. Any change to this policy invalidates previously accepted final-council evidence.",severity:"warn",path:"council.finalCompletionPolicy",currentValue:council.finalCompletionPolicy,autoFixable:!1})}catch{}}return findings}function collectLeanTurboGateSatisfiabilityFindings(config3,registeredToolNames=TOOL_NAME_SET){let findings=[],lean=config3?.turbo?.lean;for(let entry of LEAN_TURBO_GATE_PRODUCERS){let enabled=lean?.[entry.gate]??!0;if(!enabled)continue;if(registeredToolNames.has(entry.producerTool))continue;findings.push({id:`lean-turbo-gate-unsatisfiable-${entry.gate}`,title:`turbo.lean.${entry.gate} gate has no registered producer tool`,description:`turbo.lean.${entry.gate} is enabled (default true), but its evidence producer tool "${entry.producerTool}" is not registered, so the gate that reads ${entry.evidencePathConvention} is structurally unsatisfiable in production and Lean Turbo phase_complete would dead-end. Re-register the producer tool or disable the gate (issue #2470 / #2007).`,severity:"error",path:`turbo.lean.${entry.gate}`,currentValue:enabled,autoFixable:!1})}return findings}function collectRawGatesConfigFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.gates===void 0)continue;if(!isPlainObject5(raw.gates)){findings.push({id:"invalid-gates-config",title:"Invalid gates config",description:`"gates" in ${configPath} must be an object. The loader ignores that section and keeps other valid config sections active.`,severity:"error",path:"gates",currentValue:raw.gates,autoFixable:!1});continue}for(let[sectionName,sectionValue]of Object.entries(raw.gates)){let schema=GateConfigSchema.shape[sectionName];if(!schema){findings.push({id:"unknown-gates-section",title:"Unknown gates config section",description:`Unknown gates section "gates.${sectionName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1});continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[sectionName];if(knownFields&&isPlainObject5(sectionValue)){let knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(sectionValue))if(!knownFieldSet.has(fieldName))findings.push({id:"unknown-gates-key",title:"Unknown gates config key",description:`Unknown gates key "gates.${sectionName}.${fieldName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}.${fieldName}`,currentValue:sectionValue[fieldName],autoFixable:!1})}if(!schema.safeParse(sectionValue).success)findings.push({id:"invalid-gates-section",title:"Invalid gates config section",description:`"gates.${sectionName}" in ${configPath} failed validation. The loader uses defaults for that gate section and keeps other valid config sections active.`,severity:"error",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1})}}catch{}}return findings}function collectRawStrictSectionFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;let seen=new Set;for(let issue3 of parsed.error.issues){if(issue3.code!=="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let keys=issue3.keys??[];for(let key2 of keys){let dotted2=[...issue3.path.map(String),key2].join(".");if(seen.has(dotted2))continue;seen.add(dotted2),findings.push({id:"unknown-config-key",title:"Unknown config key",description:`Unrecognized key "${dotted2}" in ${configPath} is ignored by the loader (the rest of your config is preserved). Fix or remove it.`,severity:"warn",path:dotted2,currentValue:void 0,autoFixable:!1})}}}catch{}}return findings}function getRawValueAtPath(raw,issuePath){let node=raw;for(let seg of issuePath){if(node===null||typeof node!=="object")return;node=node[seg]}return node}function collectRawValueConstraintFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory),applyTargetPath=fs91.existsSync(projectConfigPath)?projectConfigPath:userConfigPath,seen=new Set,filesInApplyOrder=applyTargetPath===projectConfigPath?[projectConfigPath,userConfigPath]:[userConfigPath,projectConfigPath];for(let configPath of filesInApplyOrder){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;for(let issue3 of parsed.error.issues){if(issue3.code==="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let dotted2=issue3.path.map(String).join("."),dedupeKey=`${dotted2}|${issue3.code}`;if(seen.has(dedupeKey))continue;seen.add(dedupeKey);let current=getRawValueAtPath(raw,issue3.path);if(issue3.code==="too_big"&&dotted2.endsWith("fallback_models")&&Array.isArray(current)&&current.length>FALLBACK_MODELS_MAX){let trimmed=current.slice(0,FALLBACK_MODELS_MAX),dropped=current.slice(FALLBACK_MODELS_MAX).map(String),inApplyTarget=configPath===applyTargetPath,drop=`${dropped.length} entr${dropped.length===1?"y":"ies"}`;findings.push({id:"fallback-models-too-many",title:"Too many fallback models",description:`"${dotted2}" in ${configPath} lists ${current.length} models; the maximum is ${FALLBACK_MODELS_MAX}. A config that fails validation is discarded in favor of safe defaults. `+(inApplyTarget?`Run /swarm config doctor --fix to trim to the first ${FALLBACK_MODELS_MAX} (drops ${drop}: ${dropped.join(", ")}), or edit the file yourself.`:`Remove ${drop} from that file (would drop: ${dropped.join(", ")}).`),severity:"error",path:dotted2,currentValue:current,autoFixable:inApplyTarget,proposedFix:{type:"update",path:dotted2,value:trimmed,description:`Trim "${dotted2}" to the first ${FALLBACK_MODELS_MAX} models`,risk:"low",lossy:!0}});continue}findings.push({id:"invalid-config-value",title:"Invalid config value",description:`"${dotted2||"(root)"}" in ${configPath} is invalid: ${issue3.message}. A config that fails validation is discarded in favor of safe defaults until this is fixed.`,severity:"error",path:dotted2,currentValue:current,autoFixable:!1})}}catch{}}return findings}function collectRawAutoReviewCompatibilityFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf8"));if(!isPlainObject5(raw)||!isPlainObject5(raw.auto_review))continue;let autoReview=raw.auto_review;if(autoReview.structured_findings===!1&&isPlainObject5(autoReview.final_review)&&autoReview.final_review.mode==="gate"){findings.push({id:"invalid-auto-review-gate-compatibility",title:"Invalid auto-review gate configuration",description:'auto_review.final_review.mode="gate" requires auto_review.structured_findings=true so gate evidence is machine-verifiable.',severity:"error",path:"auto_review.structured_findings",currentValue:!1,autoFixable:!1});break}}catch{}}return findings}function emitWorktreeIsolationLayeringAdvisory(config3,findings){let parallelization=config3.parallelization,worktreePolicy=config3.worktree?.policy??"auto";if(parallelization?.enabled===!0&&(parallelization.maxConcurrentTasks??1)>1&&worktreePolicy!=="disabled")findings.push({id:"worktree-isolation-baseline-active",title:"Worktree isolation is already active for standard parallel coders",description:"Standard parallel coders already use baseline worktree isolation through the parallel execution profile plus top-level worktree.policy. Lean Turbo and Epic are additive strategies, not requirements for obtaining worktree isolation.",severity:"warn",path:"worktree.policy",currentValue:worktreePolicy,autoFixable:!1})}function getUserConfigDir3(){return process.env.XDG_CONFIG_HOME||path169.join(os23.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path169.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path169.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto9.createHash("sha256").update(content,"utf-8").digest("hex")}function isValidConfigPath(configPath,directory){let pathParts=configPath.replace(/\\/g,"/").split("/");for(let part of pathParts)if(part===".."||part===""){if(part==="..")return!1}let{userConfigPath,projectConfigPath}=getConfigPaths(directory);try{let resolvedConfig=path169.resolve(configPath),resolvedUser=path169.resolve(userConfigPath),resolvedProject=path169.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs91.existsSync(resolvedConfig)){if(fs91.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs91.writeFileSync(tmpPath,content,"utf-8");try{fs91.renameSync(tmpPath,filePath)}catch{try{fs91.unlinkSync(filePath)}catch{}fs91.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs91.existsSync(projectConfigPath))try{content=fs91.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs91.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs91.readFileSync(userConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] user config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}}if(content===null)return null;return{createdAt:Date.now(),configPath,content,contentHash:computeHash(content)}}function writeBackupArtifact(directory,backup){let swarmDir=path169.join(directory,".swarm");if(!fs91.existsSync(swarmDir))fs91.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path169.join(swarmDir,backupFilename),artifact={createdAt:backup.createdAt,configPath:backup.configPath,contentHash:backup.contentHash,content:backup.content,preview:backup.content.substring(0,500)+(backup.content.length>500?"...":"")};return atomicWriteFileSync(backupPath,JSON.stringify(artifact,null,2)),backupPath}function restoreFromBackup(backupPath,directory){if(!fs91.existsSync(backupPath))return null;let swarmDir=path169.resolve(directory,".swarm"),resolvedBackup=path169.resolve(backupPath);if(!isCanonicalPathWithinRoot(resolvedBackup,swarmDir))return null;try{let artifact=JSON.parse(fs91.readFileSync(backupPath,"utf-8"));if(!artifact.content||!artifact.configPath||!artifact.contentHash)return null;if(!isValidConfigPath(artifact.configPath,directory))return null;let computedHash=computeHash(artifact.content),storedHash=artifact.contentHash;if(!/^\d+$/.test(storedHash)&&computedHash!==storedHash)return null;log("[ConfigDoctor] Warning: restoring from backup with legacy numeric hash (pre-SHA-256). Consider re-backing up.",{});let targetPath=artifact.configPath,targetDir=path169.dirname(targetPath);if(!fs91.existsSync(targetDir))fs91.mkdirSync(targetDir,{recursive:!0});return atomicWriteFileSync(targetPath,artifact.content),targetPath}catch{return null}}function readConfigFromFile(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent=null;if(fs91.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs91.readFileSync(projectConfigPath,"utf-8");else if(fs91.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs91.readFileSync(userConfigPath,"utf-8");if(configContent===null)return null;try{return{config:JSON.parse(configContent),configPath}}catch(error93){return log(`[ConfigDoctor] Failed to parse config file: ${configPath}`,{error:error93 instanceof Error?error93.message:String(error93)}),null}}function validateConfigKey(path170,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path170===depPath&&!depInfo.isDefaultValue(value))findings.push({id:"deprecated-field",title:`Deprecated config field: ${depPath}`,description:`Config field "${depPath}" is deprecated. Replacement: ${depInfo.replacement}.`,severity:"info",path:depPath,currentValue:value,autoFixable:!1});switch(path170){case"agents":{if(value!==void 0)findings.push({id:"deprecated-agents-config",title:"Deprecated agents configuration",description:'The "agents" field is deprecated. Use "swarms" instead for multi-swarm support.',severity:"warn",path:"agents",currentValue:value,autoFixable:!1,proposedFix:{type:"remove",path:"agents",description:"Remove deprecated agents config - use swarms instead",risk:"low"}});break}case"config_format_version":{if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<0)findings.push({id:"type-mismatch",title:`Config field "${path170}" has wrong type`,description:`Expected non-negative integer, got ${typeof value==="number"?Number.isInteger(value)?value:`${value} (non-integer)`:typeof value}`,severity:"error",path:path170,currentValue:value,autoFixable:!1});break}case"guardrails.enabled":{if(value===!1)findings.push({id:"guardrails-disabled",title:"Guardrails disabled",description:"Guardrails have been explicitly disabled. This removes safety limits.",severity:"error",path:"guardrails.enabled",currentValue:value,autoFixable:!1});break}case"guardrails.profiles":{let profiles=value;if(profiles){let validAgents=new Set(ALL_AGENT_NAMES);for(let[agentName,profile]of Object.entries(profiles))if(!validAgents.has(agentName))findings.push({id:"unknown-agent-profile",title:"Unknown agent profile",description:`Profile for unknown agent "${agentName}" will be ignored.`,severity:"info",path:`guardrails.profiles.${agentName}`,currentValue:profile,autoFixable:!0,proposedFix:{type:"remove",path:`guardrails.profiles.${agentName}`,description:`Remove unknown agent profile "${agentName}"`,risk:"low"}})}break}case"automation.mode":{let validModes=["manual","hybrid","auto"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-automation-mode",title:"Invalid automation mode",description:`Invalid automation mode "${value}". Valid: ${validModes.join(", ")}`,severity:"error",path:"automation.mode",currentValue:value,autoFixable:!0,proposedFix:{type:"update",path:"automation.mode",value:"manual",description:'Reset to safe default "manual"',risk:"low"}});break}case"automation.capabilities":{let caps=value;if(caps){let capabilityNames=["plan_sync","phase_preflight","config_doctor_on_startup","evidence_auto_summaries","decision_drift_detection"];for(let[name,capValue]of Object.entries(caps))if(capabilityNames.includes(name)&&typeof capValue!=="boolean")findings.push({id:"invalid-capability-type",title:"Invalid capability type",description:`Capability "${name}" must be boolean, got ${typeof capValue}`,severity:"error",path:`automation.capabilities.${name}`,currentValue:capValue,autoFixable:!0,proposedFix:{type:"update",path:`automation.capabilities.${name}`,value:!1,description:`Reset capability "${name}" to false`,risk:"low"}})}break}case"hooks":{if(emitObjectTypeMismatch("hooks",value,findings),value!==void 0&&typeof value==="object"&&!Array.isArray(value)&&value!==null){let hooks2=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks2))if(!validHooks.includes(hookName))findings.push({id:"unknown-hook-field",title:"Unknown hook configuration",description:`Unknown hook "${hookName}" will be ignored.`,severity:"info",path:`hooks.${hookName}`,currentValue:hooks2[hookName],autoFixable:!0,proposedFix:{type:"remove",path:`hooks.${hookName}`,description:`Remove unknown hook "${hookName}"`,risk:"low"}})}break}case"max_iterations":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-iterations",title:"max_iterations out of bounds",description:`max_iterations must be 1-10, got ${numValue}`,severity:"error",path:"max_iterations",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"max_iterations",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"qa_retry_limit":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-retry-limit",title:"qa_retry_limit out of bounds",description:`qa_retry_limit must be 1-10, got ${numValue}`,severity:"error",path:"qa_retry_limit",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"qa_retry_limit",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"swarms":{if(value!==void 0){if(typeof value!=="object"||Array.isArray(value)||value===null){findings.push({id:"invalid-swarms-type",title:"Invalid swarms type",description:`"swarms" must be an object, got ${typeof value}`,severity:"error",path:"swarms",currentValue:value,autoFixable:!1});break}let swarms=value;if(Object.keys(swarms).length===0)findings.push({id:"empty-swarms",title:"Empty swarms configuration",description:'The "swarms" field is an empty object. No swarm configurations are defined.',severity:"info",path:"swarms",autoFixable:!1});for(let swarmId of Object.keys(swarms))if(swarmId.includes("..")||swarmId.includes("/")||swarmId.includes("\\")||swarmId.includes("\x00"))findings.push({id:"swarm-id-path-traversal",title:"Path traversal in swarm ID",description:`Swarm ID "${swarmId}" contains path traversal characters.`,severity:"error",path:`swarms.${swarmId}`,autoFixable:!1});let validAgents=new Set(ALL_AGENT_NAMES);for(let[swarmId,swarmConfig]of Object.entries(swarms)){let swarm=swarmConfig;if(swarm.agents&&typeof swarm.agents==="object")for(let[agentName]of Object.entries(swarm.agents)){let baseName=stripKnownSwarmPrefix(agentName);if(baseName!==agentName&&agentName.startsWith(`${swarmId}_`)&&validAgents.has(baseName))findings.push({id:"prefixed-swarm-agent-override",title:"Prefixed agent override is ignored",description:`Agent "${agentName}" in swarm "${swarmId}" uses a generated agent name. Per-swarm overrides must use the canonical key "${baseName}", e.g. "swarms.${swarmId}.agents.${baseName}.model". Otherwise the override is ignored and the agent falls back to its default model.`,severity:"warn",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1});else if(!validAgents.has(baseName))findings.push({id:"unknown-swarm-agent",title:"Unknown agent in swarm",description:`Agent "${agentName}" in swarm "${swarmId}" may not be recognized.`,severity:"info",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1})}}}break}case"default_agent":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-default_agent-type",title:"Invalid default_agent type",description:`"default_agent" must be a string, got ${typeof value}`,severity:"error",path:"default_agent",currentValue:value,autoFixable:!1});break}case"auto_select_architect":{if(value!==void 0&&typeof value!=="boolean"&&typeof value!=="string")findings.push({id:"invalid-auto_select_architect-type",title:"Invalid auto_select_architect type",description:`"auto_select_architect" must be a boolean or string, got ${typeof value}`,severity:"error",path:"auto_select_architect",currentValue:value,autoFixable:!1});break}case"pipeline":{emitObjectTypeMismatch("pipeline",value,findings);break}case"harness_evolution":{emitObjectTypeMismatch("harness_evolution",value,findings);break}case"phase_complete":{emitObjectTypeMismatch("phase_complete",value,findings);break}case"execution_mode":{let validModes=["strict","balanced","fast"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-execution_mode-type",title:"Invalid execution_mode",description:`"execution_mode" must be one of: ${validModes.join(", ")}, got "${value}"`,severity:"error",path:"execution_mode",currentValue:value,autoFixable:!1});break}case"inject_phase_reminders":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-inject_phase_reminders-type",title:"Invalid inject_phase_reminders type",description:`"inject_phase_reminders" must be a boolean, got ${typeof value}`,severity:"error",path:"inject_phase_reminders",currentValue:value,autoFixable:!1});break}case"gates":{emitObjectTypeMismatch("gates",value,findings);break}case"context_budget":{emitObjectTypeMismatch("context_budget",value,findings);break}case"pricing":{emitObjectTypeMismatch("pricing",value,findings);break}case"guardrails":{emitObjectTypeMismatch("guardrails",value,findings);break}case"watchdog":{emitObjectTypeMismatch("watchdog",value,findings);break}case"self_review":{emitObjectTypeMismatch("self_review",value,findings);break}case"tool_filter":{emitObjectTypeMismatch("tool_filter",value,findings);break}case"authority":{emitObjectTypeMismatch("authority",value,findings);break}case"plan_cursor":{emitObjectTypeMismatch("plan_cursor",value,findings);break}case"context_map":{emitObjectTypeMismatch("context_map",value,findings);break}case"evidence":{emitObjectTypeMismatch("evidence",value,findings);break}case"summaries":{emitObjectTypeMismatch("summaries",value,findings);break}case"auto_review":{emitObjectTypeMismatch("auto_review",value,findings);break}case"repo_graph":{emitObjectTypeMismatch("repo_graph",value,findings);break}case"retention":{emitObjectTypeMismatch("retention",value,findings);break}case"review_passes":{emitObjectTypeMismatch("review_passes",value,findings);break}case"adversarial_detection":{emitObjectTypeMismatch("adversarial_detection",value,findings);break}case"adversarial_testing":{emitObjectTypeMismatch("adversarial_testing",value,findings);break}case"integration_analysis":{emitObjectTypeMismatch("integration_analysis",value,findings);break}case"docs":{emitObjectTypeMismatch("docs",value,findings);break}case"design_docs":{emitObjectTypeMismatch("design_docs",value,findings);break}case"git":{emitObjectTypeMismatch("git",value,findings);break}case"git.binary":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-git-binary-type",title:"Invalid git.binary type",description:`"git.binary" must be a string, got ${typeof value}`,severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});else if(typeof value==="string"&&value.trim()==="")findings.push({id:"empty-git-binary",title:"Empty git.binary",description:'"git.binary" is blank, so no git executable is named. Remove the key to fall back to the default `git` lookup, or set it to a real git executable path.',severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});break}case"ui_review":{emitObjectTypeMismatch("ui_review",value,findings);break}case"compaction_advisory":{emitObjectTypeMismatch("compaction_advisory",value,findings);break}case"lint":{emitObjectTypeMismatch("lint",value,findings);break}case"secretscan":{emitObjectTypeMismatch("secretscan",value,findings);break}case"checkpoint":{emitObjectTypeMismatch("checkpoint",value,findings);break}case"apply_patch":{emitObjectTypeMismatch("apply_patch",value,findings);break}case"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",value,findings);break}case"observability":{if(emitObjectTypeMismatch("observability",value,findings),typeof value==="object"&&value!==null&&!Array.isArray(value)){let exportCfg=value.export;if(typeof exportCfg==="object"&&exportCfg!==null&&exportCfg.enabled===!0){let endpoint=exportCfg.endpoint,problem=null;if(typeof endpoint!=="string"||endpoint.length===0)problem="observability.export.enabled is true but endpoint is empty — the exporter stays disabled until an endpoint is configured.";else try{let url3=new URL(endpoint),host=url3.hostname.replace(/^\[|\]$/g,""),isLoopback=host==="localhost"||host==="127.0.0.1"||host==="::1";if(url3.protocol!=="https:"&&!isLoopback)problem="observability.export.endpoint uses plain http: for a non-loopback host — exported telemetry would travel unencrypted; use https: outside local test collectors."}catch{problem="observability.export.endpoint is not a valid URL — the exporter stays disabled."}if(problem!==null)findings.push({id:"observability-export-endpoint-policy",title:"OTLP export endpoint policy",description:problem,severity:"warn",path:"observability.export.endpoint",autoFixable:!1})}}break}case"learning":{emitObjectTypeMismatch("learning",value,findings);break}case"consensus":{emitObjectTypeMismatch("consensus",value,findings);break}case"curator":{emitObjectTypeMismatch("curator",value,findings);break}case"architectural_supervision":{emitObjectTypeMismatch("architectural_supervision",value,findings);break}case"knowledge_application":{emitObjectTypeMismatch("knowledge_application",value,findings);break}case"skillPropagation":{emitObjectTypeMismatch("skillPropagation",value,findings);break}case"skill_improver":{emitObjectTypeMismatch("skill_improver",value,findings);break}case"skills":{emitObjectTypeMismatch("skills",value,findings);break}case"spec_writer":{emitObjectTypeMismatch("spec_writer",value,findings);break}case"tool_output":{emitObjectTypeMismatch("tool_output",value,findings);break}case"slop_detector":{emitObjectTypeMismatch("slop_detector",value,findings);break}case"todo_gate":{emitObjectTypeMismatch("todo_gate",value,findings);break}case"incremental_verify":{emitObjectTypeMismatch("incremental_verify",value,findings);break}case"compaction_service":{emitObjectTypeMismatch("compaction_service",value,findings);break}case"prm":{emitObjectTypeMismatch("prm",value,findings);break}case"council":{emitObjectTypeMismatch("council",value,findings);break}case"parallelization":{emitObjectTypeMismatch("parallelization",value,findings);break}case"worktree":{emitObjectTypeMismatch("worktree",value,findings);break}case"turbo":{emitObjectTypeMismatch("turbo",value,findings);break}case"turbo_mode":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-turbo_mode-type",title:"Invalid turbo_mode type",description:`"turbo_mode" must be a boolean, got ${typeof value}`,severity:"error",path:"turbo_mode",currentValue:value,autoFixable:!1});break}case"quiet":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-quiet-type",title:"Invalid quiet type",description:`"quiet" must be a boolean, got ${typeof value}`,severity:"error",path:"quiet",currentValue:value,autoFixable:!1});break}case"version_check":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-version_check-type",title:"Invalid version_check type",description:`"version_check" must be a boolean, got ${typeof value}`,severity:"error",path:"version_check",currentValue:value,autoFixable:!1});break}case"$schema":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-$schema-type",title:"Invalid $schema type",description:`"$schema" must be a string (JSON Schema URL), got ${typeof value}`,severity:"error",path:"$schema",currentValue:value,autoFixable:!1});break}case"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"pr_review_resilience":{emitObjectTypeMismatch("pr_review_resilience",value,findings);break}case"review_routing":{if(emitObjectTypeMismatch("review_routing",value,findings),isPlainObject5(value)){let enforceReceipts=value.enforce_receipts;if(enforceReceipts!==void 0&&typeof enforceReceipts!=="boolean")findings.push({id:"invalid-review_routing-enforce_receipts-type",title:"Invalid review_routing.enforce_receipts type",description:`"review_routing.enforce_receipts" must be a boolean, got ${typeof enforceReceipts}`,severity:"error",path:"review_routing.enforce_receipts",currentValue:enforceReceipts,autoFixable:!1})}break}case"lane_liveness_watchdog":{emitObjectTypeMismatch("lane_liveness_watchdog",value,findings);break}case"dispatch_protection":{emitObjectTypeMismatch("dispatch_protection",value,findings);break}case"pr_review_legacy_transcript_compatibility":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-pr_review_legacy_transcript_compatibility-type",title:"Invalid pr_review_legacy_transcript_compatibility type",description:`"pr_review_legacy_transcript_compatibility" must be a boolean, got ${typeof value}`,severity:"error",path:"pr_review_legacy_transcript_compatibility",currentValue:value,autoFixable:!1});break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}case"skill_opt":{emitObjectTypeMismatch("skill_opt",value,findings);break}default:{let topLevel=path170.split(".")[0];if(KNOWN_TOP_LEVEL_KEYS.has(topLevel))break;let MAX_SUGGESTION_KEY_LENGTH=100,lowerTopLevel=topLevel.toLowerCase(),suggestion,matchCount=0;if(lowerTopLevel.length<=MAX_SUGGESTION_KEY_LENGTH){for(let knownKey of KNOWN_TOP_LEVEL_KEYS)if(levenshteinDistance(lowerTopLevel,knownKey.toLowerCase())<=2){if(matchCount++,matchCount===1)suggestion=knownKey}}if(matchCount===1&&suggestion)findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path170}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path170,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path170}" is not in the schema.`,severity:"warn",path:path170,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path170,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path170&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path170,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path170,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path170}`,description:`Config value at "${path170}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path170,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path170,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path170}[${index}]`,findings,visited)});return}for(let[key2,value]of Object.entries(obj)){let newPath=path170?`${path170}.${key2}`:key2;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory){let findings=[];walkConfigAndValidate(config3,"",findings),findings.push(...collectRawGatesConfigFindings(directory)),findings.push(...collectRawCouncilPolicyFindings(directory)),findings.push(...collectRawStrictSectionFindings(directory)),findings.push(...collectRawValueConstraintFindings(directory)),findings.push(...collectRawAutoReviewCompatibilityFindings(directory)),findings.push(...collectLeanTurboGateSatisfiabilityFindings(config3)),emitWorktreeIsolationLayeringAdvisory(config3,findings);let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length},hasAutoFixableIssues=findings.some((f)=>f.autoFixable&&f.proposedFix?.risk==="low"),{userConfigPath,projectConfigPath}=getConfigPaths(directory),configSource="defaults";if(fs91.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs91.existsSync(userConfigPath))configSource=userConfigPath;let rawConfigVersion=config3.config_format_version,configVersion=typeof rawConfigVersion==="number"&&Number.isFinite(rawConfigVersion)&&Number.isInteger(rawConfigVersion)&&rawConfigVersion>=0?rawConfigVersion:1,availableMigrations=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(configVersion<depInfo.deprecatedIn)availableMigrations.push({field:depPath,replacement:depInfo.replacement,deprecatedIn:depInfo.deprecatedIn,sinceVersion:depInfo.sinceVersion,currentFormatVersion:configVersion});return{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource,...availableMigrations.length>0?{availableMigrations}:{}}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe3(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result,options={}){let applyLossy=options.applyLossy===!0,appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs91.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs91.readFileSync(projectConfigPath,"utf-8");else if(fs91.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs91.readFileSync(userConfigPath,"utf-8");else return{appliedFixes,updatedConfigPath:null};let config3;try{config3=JSON.parse(configContent)}catch{return{appliedFixes,updatedConfigPath:null}}let safeFixes=result.findings.filter((f)=>f.autoFixable&&f.proposedFix?.risk==="low"&&(applyLossy||!f.proposedFix?.lossy));for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe3(fix.path))continue;let pathParts=fix.path.split("."),current=config3,navigated=!0;for(let i=0;i<pathParts.length-1;i++){let part=pathParts[i];if(current===null||current===void 0){navigated=!1;break}if(typeof current!=="object"||Array.isArray(current)){navigated=!1;break}let obj=current;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null){navigated=!1;break}else if(typeof obj[part]!=="object"){navigated=!1;break}current=obj[part]}if(!navigated)continue;let lastPart=pathParts[pathParts.length-1];switch(fix.type){case"remove":if(current!==null&&current!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(applyLossy&&result.availableMigrations&&result.availableMigrations.length>0)for(let migration of result.availableMigrations){if(!isPathSafe3(migration.field)||!isPathSafe3(migration.replacement))continue;let legacyParts=migration.field.split("."),legacyParent=config3,legacyNavigated=!0;for(let i=0;i<legacyParts.length-1;i++){let part=legacyParts[i];if(legacyParent===null||legacyParent===void 0||typeof legacyParent!=="object"||Array.isArray(legacyParent)){legacyNavigated=!1;break}let obj=legacyParent;if(obj[part]===void 0||obj[part]===null){legacyNavigated=!1;break}legacyParent=obj[part]}if(!legacyNavigated)continue;let legacyKey=legacyParts[legacyParts.length-1],legacyHolder=legacyParent;if(!(legacyKey in legacyHolder))continue;let legacyValue=legacyHolder[legacyKey],depInfo=DEPRECATED_FIELDS.get(migration.field);if(!depInfo||depInfo.isDefaultValue(legacyValue))continue;let replParts=migration.replacement.split("."),replParent=config3,replNavigated=!0;for(let i=0;i<replParts.length-1;i++){let part=replParts[i];if(replParent===null||replParent===void 0||typeof replParent!=="object"||Array.isArray(replParent)){replNavigated=!1;break}let obj=replParent;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null||typeof obj[part]!=="object"){replNavigated=!1;break}replParent=obj[part]}if(!replNavigated)continue;let replKey=replParts[replParts.length-1];replParent[replKey]=legacyValue,delete legacyHolder[legacyKey],appliedFixes.push({type:"update",path:migration.replacement,value:legacyValue,description:`Migrate deprecated field \`${migration.field}\` → \`${migration.replacement}\``,risk:"low",lossy:!0}),appliedFixes.push({type:"remove",path:migration.field,description:`Remove deprecated field \`${migration.field}\` (migrated to \`${migration.replacement}\`)`,risk:"low",lossy:!0})}if(appliedFixes.length>0){let configDir=path169.dirname(configPath);if(!fs91.existsSync(configDir))fs91.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path169.join(directory,".swarm","config-doctor.json");if(!fs91.existsSync(artifactPath))return null;let content=fs91.readFileSync(artifactPath,"utf-8"),artifact=JSON.parse(content),summary=artifact.summary;if(!summary||typeof summary!=="object")return null;let{info:infoVal,warn:warnVal,error:errorVal}=summary;if(typeof infoVal!=="number"||!Number.isFinite(infoVal)||typeof warnVal!=="number"||!Number.isFinite(warnVal)||typeof errorVal!=="number"||!Number.isFinite(errorVal))return null;let ts=artifact.timestamp;if(typeof ts!=="number"||!Number.isFinite(ts))return null;let findingsCount=infoVal+warnVal+errorVal,findings=artifact.findings,autoFixableCount=Array.isArray(findings)?findings.filter((f)=>f.autoFixable===!0).length:0;return{timestamp:new Date(ts).toISOString(),findingsCount,autoFixableCount}}catch{return null}}function writeDoctorArtifact(directory,result){let swarmDir=path169.join(directory,".swarm");if(!fs91.existsSync(swarmDir))fs91.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path169.join(swarmDir,"config-doctor.json"),guiOutput={timestamp:result.timestamp,summary:result.summary,hasAutoFixableIssues:result.hasAutoFixableIssues,configSource:result.configSource,findings:result.findings.map((f)=>({id:f.id,title:f.title,description:f.description,severity:f.severity,path:f.path,autoFixable:f.autoFixable,proposedFix:f.proposedFix?{type:f.proposedFix.type,path:f.proposedFix.path,description:f.proposedFix.description,risk:f.proposedFix.risk,lossy:f.proposedFix.lossy===!0}:null}))};return atomicWriteFileSync(artifactPath,JSON.stringify(guiOutput,null,2)),artifactPath}function shouldRunOnStartup(automationConfig){if(!automationConfig)return!1;if(automationConfig.mode==="manual")return!1;return automationConfig.capabilities?.config_doctor_on_startup===!0}async function runConfigDoctorWithFixes(directory,config3,autoFix=!1,options={}){let result=runConfigDoctor(config3,directory),artifactPath=writeDoctorArtifact(directory,result);if(!autoFix)return{result,backupPath:null,appliedFixes:[],updatedConfigPath:null,artifactPath};let backup=createConfigBackup(directory),backupPath=null;if(backup)backupPath=writeBackupArtifact(directory,backup);let{appliedFixes,updatedConfigPath}=applySafeAutoFixes(directory,result,options);if(appliedFixes.length>0){let freshConfig=readConfigFromFile(directory);if(freshConfig){let newResult=runConfigDoctor(freshConfig.config,directory);writeDoctorArtifact(directory,newResult)}}return{result,backupPath,appliedFixes,updatedConfigPath,artifactPath}}function detectStraySwarmDirs(projectRoot){let findings=[],SKIP_DIRS=new Set(["node_modules",".git","dist",".cache",".next","coverage",".turbo",".vercel",".terraform","__pycache__",".tox"]),MAX_DEPTH=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries2;try{entries2=fs91.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path169.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path169.join(fullPath,".git");try{let gitStat=fs91.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path169.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs91.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path169.relative(projectRoot,fullPath).replace(/\\/g,"/"),absolutePath:fullPath,contents:contents.slice(0,20),totalEntries:contents.length});continue}walk(fullPath,depth+1)}}return walk(projectRoot,0),findings}function removeStraySwarmDir(projectRoot,strayPath){let canonicalRoot,canonicalStray;try{canonicalRoot=fs91.realpathSync(projectRoot),canonicalStray=fs91.realpathSync(path169.isAbsolute(strayPath)?strayPath:path169.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path169.join(canonicalRoot,".swarm");if(sameExistingFilesystemPath(canonicalStray,rootSwarm)||sameExistingFilesystemPath(canonicalStray,canonicalRoot))return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!isCanonicalPathWithinRoot(canonicalStray,canonicalRoot))return{success:!1,message:"Path is outside project root — refusing to remove"};if(!canonicalStray.replace(/\\/g,"/").endsWith("/.swarm"))return{success:!1,message:"Path is not a .swarm directory — refusing to remove"};try{return fs91.rmSync(canonicalStray,{recursive:!0,force:!0}),{success:!0,message:`Removed stray .swarm directory: ${canonicalStray}`}}catch(err){return{success:!1,message:`Failed to remove: ${err instanceof Error?err.message:String(err)}`}}}var CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES=102400,KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,LEAN_TURBO_GATE_PRODUCERS,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_schema();init_tool_metadata();init_utils();init_filesystem_identity();init_path_security();KNOWN_TOP_LEVEL_KEYS=new Set(Object.keys(PluginConfigSchema.shape)),DEPRECATED_FIELDS=new Map([["skill_improver.model",{message:"deprecated",replacement:"agents.skill_improver.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}]]);LEAN_TURBO_GATE_PRODUCERS=[{gate:"phase_critic",producerTool:"lean_turbo_critic",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-critic.json"},{gate:"phase_reviewer",producerTool:"lean_turbo_review",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-reviewer.json"},{gate:"integrated_diff_required",producerTool:"lean_turbo_run_phase",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo/lean-turbo-phase.json"}];DANGEROUS_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"])});class LanguageRegistry{profiles;extensionIndex;constructor(){this.profiles=new Map,this.extensionIndex=new Map}unregister(id){let profile=this.profiles.get(id);if(!profile)return;if(this.profiles.delete(id),!profile.parserOnly){for(let ext of profile.extensions)if(this.extensionIndex.get(ext)===id)this.extensionIndex.delete(ext)}}register(profile){let existing=this.profiles.get(profile.id);if(existing&&existing!==profile)throw Error(`LanguageRegistry: profile id "${profile.id}" registered twice. Each LanguageProfile.id must be unique. Got: ${profile.displayName} vs existing ${existing.displayName}.`);if(!profile.parserOnly)for(let ext of profile.extensions){let claimedBy=this.extensionIndex.get(ext);if(claimedBy&&claimedBy!==profile.id)throw Error(`LanguageRegistry: extension "${ext}" registered by both "${claimedBy}" and "${profile.id}". A non-parserOnly profile must not collide on extensions. If both languages legitimately share an extension, mark one parserOnly: true.`);this.extensionIndex.set(ext,profile.id)}this.profiles.set(profile.id,profile)}get(id){return this.profiles.get(id)}getById(id){return this.profiles.get(id)}getByExtension(ext){let profileId=this.extensionIndex.get(ext);if(profileId)return this.profiles.get(profileId);return}getAll(){return Array.from(this.profiles.values())}getTier(tier){return Array.from(this.profiles.values()).filter((p)=>p.tier===tier)}}var LANGUAGE_REGISTRY;var init_profiles=__esm(()=>{LANGUAGE_REGISTRY=new LanguageRegistry;LANGUAGE_REGISTRY.register({id:"typescript",displayName:"TypeScript",tier:1,extensions:[".ts",".tsx"],treeSitter:{grammarId:"typescript",wasmFile:"tree-sitter-typescript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"javascript",displayName:"JavaScript",tier:1,extensions:[".js",".jsx",".mjs",".cjs"],treeSitter:{grammarId:"javascript",wasmFile:"tree-sitter-javascript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"python",displayName:"Python",tier:1,extensions:[".py",".pyw"],treeSitter:{grammarId:"python",wasmFile:"tree-sitter-python.wasm",commentNodes:["comment"]},build:{detectFiles:["setup.py","pyproject.toml","setup.cfg"],commands:[{name:"pip install",cmd:"pip install -e .",detectFile:"setup.py",priority:10},{name:"build",cmd:"python -m build",detectFile:"pyproject.toml",priority:9}]},test:{detectFiles:["pytest.ini","pyproject.toml","setup.cfg","conftest.py"],frameworks:[{name:"pytest",detect:"pytest.ini",cmd:"pytest",priority:10},{name:"unittest",detect:"setup.py",cmd:"python -m unittest discover",priority:8}]},lint:{detectFiles:["pyproject.toml",".ruff.toml","setup.cfg"],linters:[{name:"ruff",detect:"pyproject.toml",cmd:"ruff check --fix .",priority:10},{name:"flake8",detect:"setup.cfg",cmd:"flake8 .",priority:8}]},audit:{detectFiles:["requirements.txt","Pipfile.lock","pyproject.toml"],command:"pip-audit --format json",outputFormat:"json"},sast:{nativeRuleSet:"python",semgrepSupport:"ga"},prompts:{coderConstraints:["Use type annotations on all function signatures (PEP 484)","Prefer f-strings over .format() or % formatting","Use pathlib.Path over os.path for filesystem operations","Never use bare except:; catch specific exception types","Follow PEP 8 style; max line length 120 characters"],reviewerChecklist:["Verify type annotations are present on all public functions","Check for bare except clauses or overly broad exception handling","Confirm no mutable default arguments (def f(x=[]) anti-pattern)","Validate f-string usage and no format string injection risks","Check imports are organized (stdlib → third-party → local)"]}});LANGUAGE_REGISTRY.register({id:"rust",displayName:"Rust",tier:1,extensions:[".rs"],treeSitter:{grammarId:"rust",wasmFile:"tree-sitter-rust.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["Cargo.toml"],commands:[{name:"cargo build",cmd:"cargo build",detectFile:"Cargo.toml",priority:10},{name:"cargo check",cmd:"cargo check",detectFile:"Cargo.toml",priority:9}]},test:{detectFiles:["Cargo.toml"],frameworks:[{name:"cargo",detect:"Cargo.toml",cmd:"cargo test",priority:10}]},lint:{detectFiles:["Cargo.toml"],linters:[{name:"clippy",detect:"Cargo.toml",cmd:"cargo clippy --fix --allow-dirty",priority:10},{name:"rustfmt",detect:"Cargo.toml",cmd:"cargo fmt",priority:9}]},audit:{detectFiles:["Cargo.lock"],command:"cargo audit --json",outputFormat:"json"},sast:{nativeRuleSet:"rust",semgrepSupport:"ga"},prompts:{coderConstraints:["Prefer owned types over references where ownership is clear; use lifetimes sparingly","Use Result<T, E> and ? operator for error propagation; never unwrap() in library code","Prefer iterators and combinators over explicit loops","Derive standard traits (Debug, Clone, PartialEq) whenever sensible","Avoid unsafe blocks; document any unsafe usage with SAFETY comments"],reviewerChecklist:["Verify no unwrap() or expect() calls in library/production paths","Check for potential panics in indexing, arithmetic overflow, or slice operations","Confirm error types implement std::error::Error and are propagated correctly","Validate lifetime annotations are minimal and correct","Check unsafe blocks have SAFETY comments explaining invariants"]}});LANGUAGE_REGISTRY.register({id:"go",displayName:"Go",tier:1,extensions:[".go"],treeSitter:{grammarId:"go",wasmFile:"tree-sitter-go.wasm",commentNodes:["comment"]},build:{detectFiles:["go.mod"],commands:[{name:"go build",cmd:"go build ./...",detectFile:"go.mod",priority:10},{name:"go vet",cmd:"go vet ./...",detectFile:"go.mod",priority:9}]},test:{detectFiles:["go.mod"],frameworks:[{name:"go-test",detect:"go.mod",cmd:"go test ./...",priority:10}]},lint:{detectFiles:["go.mod",".golangci.yml",".golangci.yaml"],linters:[{name:"golangci-lint",detect:".golangci.yml",cmd:"golangci-lint run --fix",priority:10},{name:"gofmt",detect:"go.mod",cmd:"gofmt -w .",priority:9}]},audit:{detectFiles:["go.mod"],command:"govulncheck -json ./...",outputFormat:"json"},sast:{nativeRuleSet:"go",semgrepSupport:"ga"},prompts:{coderConstraints:["Always check and return errors; never discard error return values","Use idiomatic Go error wrapping with fmt.Errorf and %w verb","Prefer table-driven tests; use t.Run for subtests","Avoid global mutable state; use dependency injection via interfaces","Use context.Context as first parameter for all I/O-bound functions"],reviewerChecklist:["Verify all error return values are checked (no _ = err pattern)","Check goroutine usage — confirm no goroutine leaks or missing WaitGroups","Validate context propagation through call chains","Confirm exported types/functions have doc comments","Check for data races in concurrent code (verify sync usage)"]}});LANGUAGE_REGISTRY.register({id:"java",displayName:"Java",tier:2,extensions:[".java"],treeSitter:{grammarId:"java",wasmFile:"tree-sitter-java.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],commands:[{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:8}]},test:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],frameworks:[{name:"maven",detect:"pom.xml",cmd:"mvn test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["checkstyle.xml","pom.xml"],linters:[{name:"checkstyle",detect:"checkstyle.xml",cmd:"mvn checkstyle:check",priority:10}]},audit:{detectFiles:["pom.xml","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"java",semgrepSupport:"ga"},prompts:{coderConstraints:["Use checked exceptions for recoverable conditions; unchecked for programming errors","Prefer composition over inheritance; favor interfaces over abstract classes","Use Optional<T> for nullable return values rather than returning null","Follow Java naming conventions: PascalCase classes, camelCase methods/fields","Close resources in try-with-resources blocks; never rely on finalizers"],reviewerChecklist:["Check for unclosed resources — verify try-with-resources or explicit close()","Verify null checks are present for all external/injected dependencies","Confirm thread safety for shared mutable state (synchronized, volatile, atomic)","Validate exception handling — no swallowed exceptions or empty catch blocks","Check for proper equals()/hashCode() overrides on value objects"]}});LANGUAGE_REGISTRY.register({id:"kotlin",displayName:"Kotlin",tier:2,extensions:[".kt",".kts"],treeSitter:{grammarId:"kotlin",wasmFile:"tree-sitter-kotlin.wasm",commentNodes:["line_comment","multiline_comment"]},build:{detectFiles:["build.gradle.kts","build.gradle","pom.xml"],commands:[{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:8}]},test:{detectFiles:["build.gradle.kts","build.gradle"],frameworks:[{name:"gradle",detect:"build.gradle.kts",cmd:"gradle test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["build.gradle.kts","build.gradle"],linters:[{name:"ktlint",detect:"build.gradle.kts",cmd:"ktlint --format",priority:10}]},audit:{detectFiles:["build.gradle.kts","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"beta"},prompts:{coderConstraints:["Prefer val over var; use data classes for value objects","Use Kotlin coroutines for async operations; avoid blocking calls on Dispatchers.Main","Leverage extension functions instead of utility classes","Use sealed classes for exhaustive when expressions","Avoid platform types; always declare explicit nullability in API surfaces"],reviewerChecklist:["Verify no non-null assertions (!!) in production code without justification","Check coroutine scope lifecycle — confirm scopes are cancelled when no longer needed","Validate when expressions are exhaustive (sealed class coverage)","Confirm data class equals/hashCode/copy semantics are appropriate","Check for blocking I/O on the wrong coroutine dispatcher"]}});LANGUAGE_REGISTRY.register({id:"csharp",displayName:"C# / .NET",tier:2,extensions:[".cs",".csx"],treeSitter:{grammarId:"csharp",wasmFile:"tree-sitter-c-sharp.wasm",commentNodes:["comment"]},build:{detectFiles:["*.csproj","*.sln","Directory.Build.props"],commands:[{name:"dotnet build",cmd:"dotnet build -v quiet",detectFile:"*.csproj",priority:10},{name:"dotnet build sln",cmd:"dotnet build -v quiet",detectFile:"*.sln",priority:9}]},test:{detectFiles:["*.csproj","*.sln"],frameworks:[{name:"dotnet-test",detect:"*.csproj",cmd:"dotnet test",priority:10}]},lint:{detectFiles:["*.csproj",".editorconfig"],linters:[{name:"dotnet-format",detect:"*.csproj",cmd:"dotnet format",priority:10}]},audit:{detectFiles:["*.csproj","packages.lock.json"],command:"dotnet list package --vulnerable --include-transitive",outputFormat:"text"},sast:{nativeRuleSet:"csharp",semgrepSupport:"ga"},prompts:{coderConstraints:["Use async/await throughout; avoid .Result or .Wait() which can deadlock","Prefer records for immutable value types; use struct only for small value types","Use nullable reference types (NRT) — enable <Nullable>enable</Nullable>","Dispose IDisposable resources with using statements or declarations","Follow C# naming conventions: PascalCase for public members, _camelCase for private fields"],reviewerChecklist:["Verify no .Result or .Wait() calls that could cause deadlocks","Check all IDisposable are properly disposed (using / IAsyncDisposable)","Confirm nullable reference type annotations are present and correct","Validate LINQ queries do not cause N+1 query patterns in EF contexts","Check for missing ConfigureAwait(false) in library code"]}});LANGUAGE_REGISTRY.register({id:"cpp",displayName:"C / C++",tier:2,extensions:[".c",".h",".cpp",".hpp",".cc",".cxx"],treeSitter:{grammarId:"cpp",wasmFile:"tree-sitter-cpp.wasm",commentNodes:["comment"]},build:{detectFiles:["CMakeLists.txt","Makefile","meson.build"],commands:[{name:"cmake",cmd:"cmake --build build",detectFile:"CMakeLists.txt",priority:10},{name:"make",cmd:"make",detectFile:"Makefile",priority:9},{name:"meson",cmd:"meson compile -C builddir",detectFile:"meson.build",priority:8}]},test:{detectFiles:["CMakeLists.txt"],frameworks:[{name:"ctest",detect:"CMakeLists.txt",cmd:"ctest --test-dir build",priority:10}]},lint:{detectFiles:[".clang-tidy","CMakeLists.txt"],linters:[{name:"cppcheck",detect:"CMakeLists.txt",cmd:"cppcheck --error-exitcode=1 .",priority:10},{name:"clang-tidy",detect:".clang-tidy",cmd:"clang-tidy -p build",priority:9}]},audit:{detectFiles:["CMakeLists.txt","vcpkg.json","conanfile.txt"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"cpp",semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer RAII and smart pointers (unique_ptr, shared_ptr) over raw pointers","Use const-correctness throughout; mark all non-mutating methods const","Avoid undefined behaviour: no out-of-bounds access, no use-after-free","Initialize all variables; prefer in-class initializers for member variables","Use std::array or std::vector instead of C-style arrays"],reviewerChecklist:["Verify no raw owning pointers; confirm smart pointer ownership semantics","Check for memory leaks — every new has a corresponding delete or smart pointer","Validate bounds checking on all array/buffer accesses","Confirm no undefined behavior patterns (signed overflow, strict aliasing violations)","Check thread safety for shared data (mutex, atomic, lock-free patterns)"]}});LANGUAGE_REGISTRY.register({id:"swift",displayName:"Swift",tier:2,extensions:[".swift"],treeSitter:{grammarId:"swift",wasmFile:"tree-sitter-swift.wasm",commentNodes:["comment","multiline_comment"]},build:{detectFiles:["Package.swift","*.xcodeproj","*.xcworkspace"],commands:[{name:"swift build",cmd:"swift build",detectFile:"Package.swift",priority:10},{name:"xcodebuild",cmd:"xcodebuild build -quiet",detectFile:"*.xcodeproj",priority:9}]},test:{detectFiles:["Package.swift","*.xcodeproj"],frameworks:[{name:"swift-test",detect:"Package.swift",cmd:"swift test",priority:10},{name:"xcodebuild-test",detect:"*.xcodeproj",cmd:"xcodebuild test -quiet",priority:9}]},lint:{detectFiles:[".swiftlint.yml","Package.swift"],linters:[{name:"swiftlint",detect:".swiftlint.yml",cmd:"swiftlint --fix",priority:10}]},audit:{detectFiles:["Package.resolved","Package.swift"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer value types (structs, enums) over classes; use classes only for reference semantics","Use Swift concurrency (async/await, actors) over GCD for new code","Avoid force unwrap (!) and force cast (as!); use guard let or if let","Use Swift Package Manager for dependencies where possible","Mark types and methods as final when subclassing is not intended"],reviewerChecklist:["Verify no force unwraps (!) or force casts (as!) in production code","Check for retain cycles in closures — confirm [weak self] where needed","Validate Swift concurrency usage — no data races across actor boundaries","Confirm proper error handling with do-try-catch or Result<T,E>","Check value vs reference type choice is appropriate for the use case"]}});LANGUAGE_REGISTRY.register({id:"dart",displayName:"Dart / Flutter",tier:3,extensions:[".dart"],treeSitter:{grammarId:"dart",wasmFile:"tree-sitter-dart.wasm",commentNodes:["comment","documentation_comment"]},build:{detectFiles:["pubspec.yaml"],commands:[{name:"flutter build",cmd:"flutter build apk",detectFile:"pubspec.yaml",priority:10},{name:"dart compile",cmd:"dart compile exe .",detectFile:"pubspec.yaml",priority:9}]},test:{detectFiles:["pubspec.yaml"],frameworks:[{name:"flutter test",detect:"pubspec.yaml",cmd:"flutter test",priority:10},{name:"dart test",detect:"pubspec.yaml",cmd:"dart test",priority:9}]},lint:{detectFiles:["analysis_options.yaml","pubspec.yaml"],linters:[{name:"dart analyze",detect:"pubspec.yaml",cmd:"dart analyze",priority:10}]},audit:{detectFiles:["pubspec.yaml","pubspec.lock"],command:"dart pub outdated --json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"none"},prompts:{coderConstraints:["Use null safety features — prefer late, required, and ? annotations over dynamic","Follow Dart effective style: lowerCamelCase for variables, UpperCamelCase for types","Prefer const constructors where possible for performance","Use async/await over raw Future callbacks","Separate business logic from UI widgets; use BLoC or Provider patterns"],reviewerChecklist:["Verify null safety annotations are correct (no unnecessary ?)","Check that const constructors are used where the widget tree is static","Confirm async operations handle error states (catchError or try-catch)","Validate no direct UI state mutation outside setState or stream","Check for platform-specific code isolation (dart:io vs dart:html)"]}});LANGUAGE_REGISTRY.register({id:"ruby",displayName:"Ruby",tier:3,extensions:[".rb",".rake",".gemspec"],treeSitter:{grammarId:"ruby",wasmFile:"tree-sitter-ruby.wasm",commentNodes:["comment"]},build:{detectFiles:["Gemfile","Rakefile"],commands:[{name:"bundle install",cmd:"bundle install",detectFile:"Gemfile",priority:10},{name:"rake",cmd:"rake",detectFile:"Rakefile",priority:9}]},test:{detectFiles:["Gemfile",".rspec","spec/spec_helper.rb"],frameworks:[{name:"rspec",detect:".rspec",cmd:"bundle exec rspec",priority:10},{name:"minitest",detect:"Rakefile",cmd:"bundle exec rake test",priority:9}]},lint:{detectFiles:[".rubocop.yml","Gemfile"],linters:[{name:"rubocop",detect:".rubocop.yml",cmd:"rubocop --autocorrect",priority:10}]},audit:{detectFiles:["Gemfile.lock"],command:"bundle-audit check --format json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Follow Ruby community style (Rubocop defaults); 120-char line limit","Prefer symbols over strings for hash keys","Use frozen_string_literal: true magic comment in all files","Avoid monkey-patching core classes; prefer refinements","Use keyword arguments for methods with more than 2 parameters"],reviewerChecklist:["Verify frozen_string_literal comment is present in new files","Check for N+1 query patterns in ActiveRecord code","Validate no eval or send with user-controlled input (code injection risk)","Confirm exception handling is specific — no bare rescue","Check for missing validations on ActiveRecord models"]}});LANGUAGE_REGISTRY.register({id:"php",displayName:"PHP",tier:3,extensions:[".php",".phtml",".blade.php"],treeSitter:{grammarId:"php",wasmFile:"tree-sitter-php.wasm",commentNodes:["comment"]},build:{detectFiles:["composer.json"],commands:[{name:"Composer Install",cmd:"composer install --no-interaction --prefer-dist",detectFile:"composer.json",priority:10}]},test:{detectFiles:["Pest.php","phpunit.xml","phpunit.xml.dist"],frameworks:[{name:"Pest",detect:"Pest.php",cmd:"vendor/bin/pest",priority:10},{name:"PHPUnit",detect:"phpunit.xml",cmd:"vendor/bin/phpunit",priority:8},{name:"PHPUnit",detect:"phpunit.xml.dist",cmd:"vendor/bin/phpunit",priority:7}]},lint:{detectFiles:["phpstan.neon","phpstan.neon.dist","pint.json",".php-cs-fixer.php","phpcs.xml"],linters:[{name:"PHPStan",detect:"phpstan.neon",cmd:"vendor/bin/phpstan analyse",priority:10},{name:"PHPStan",detect:"phpstan.neon.dist",cmd:"vendor/bin/phpstan analyse",priority:9},{name:"Pint",detect:"pint.json",cmd:"vendor/bin/pint --test",priority:8},{name:"PHP-CS-Fixer",detect:".php-cs-fixer.php",cmd:"vendor/bin/php-cs-fixer fix --dry-run --diff",priority:7}]},audit:{detectFiles:["composer.lock"],command:"composer audit --locked --format=json",outputFormat:"json"},sast:{nativeRuleSet:"php",semgrepSupport:"ga"},prompts:{coderConstraints:["Follow PSR-12 coding standards","Use strict types declaration: declare(strict_types=1)","Prefer type hints and return type declarations on all functions","Use dependency injection over static methods and singletons","Prefer named constructors and value objects over primitive obsession"],reviewerChecklist:["Verify no user input reaches SQL queries without parameterised binding","Check for XSS — all output must be escaped with htmlspecialchars()","Confirm no eval(), exec(), or shell_exec() with user-controlled input","Validate proper error handling — no bare catch blocks that swallow errors","Challenge any PHP/Laravel documentation or README claim that exceeds what is implemented and CI-verified in v6.49.0 (composer build, PHPUnit/Pest/artisan test, Pint/PHP-CS-Fixer lint, PHPStan static analysis, composer audit, Laravel detection, Blade scanning, 3 Laravel SAST rules). If a PR adds docs claiming broader support, verify it is backed by tests."],testConstraints:["Prefer feature tests for HTTP, middleware, and authentication flows — use Laravel RefreshDatabase or DatabaseTransactions traits","Use unit tests for isolated business logic classes that do not require the full Laravel application container","Pest and PHPUnit coexist in many Laravel repos — php artisan test runs both; do not assume PHPUnit-only","Use .env.testing for test environment configuration; run php artisan config:clear when environment changes affect tests","For database tests, prefer RefreshDatabase over manual setUp/tearDown to avoid state leakage between tests","Run php artisan config:clear and php artisan cache:clear before running tests if environment variables changed","Use separate .env.testing file for test-specific configuration; never rely on .env for CI test runs","For parallel testing with php artisan test --parallel, ensure database connections use separate databases per worker (APP_ENV=testing + test database suffix pattern)"]}})});import{access as access4,readdir as readdir12}from"node:fs/promises";import{extname as extname9,join as join127}from"node:path";function getProfileForFile(filePath){let ext=extname9(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries2;try{dirEntries=await readdir12(dir,{withFileTypes:!0}),entries2=dirEntries.map((e)=>e.name)}catch{return}for(let profile of LANGUAGE_REGISTRY.getAll())for(let detectFile of profile.build.detectFiles){if(detectFile.includes("*")||detectFile.includes("?")){let regex=new RegExp(`^${detectFile.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);if(dirEntries.some((e)=>!e.isDirectory()&&regex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join127(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries2){let ext=extname9(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir12(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join127(projectDir,entry.name))}catch{}let result=[];for(let id of detected){let profile=LANGUAGE_REGISTRY.getById(id);if(profile)result.push(profile)}return result.sort((a,b)=>a.tier-b.tier),result}var init_detector=__esm(()=>{init_profiles()});import*as fs92 from"node:fs";import*as path170 from"node:path";function tokenizeCommand(command){let out=[],buf="",quote=null;for(let ch of command.trim()){if(quote){if(ch===quote)quote=null;else buf+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch===" "||ch==="\t"){if(buf.length>0)out.push(buf),buf="";continue}buf+=ch}if(buf.length>0)out.push(buf);return out}function findCommandSuffixStart(command){let quote=null,sawTokenChar=!1;for(let i=0;i<command.length;i++){let ch=command[i];if(quote){if(ch===quote)quote=null;else sawTokenChar=!0;continue}if(ch==='"'||ch==="'"){quote=ch,sawTokenChar=!0;continue}if((ch===" "||ch==="\t")&&sawTokenChar)return i;if(ch!==" "&&ch!=="\t")sawTokenChar=!0}return command.length}function resolveLocalCandidate(binary,workingDir,platform=process.platform,isAvailable){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`,absolute=path170.join(workingDir,"node_modules",".bin",executable);if(!fs92.existsSync(absolute))continue;if(candidate.requiresNode&&isAvailable&&!isAvailable("node"))continue;let relative37=platform==="win32"?path170.win32.join("node_modules",".bin",executable):path170.posix.join("node_modules",".bin",executable);return{absolute,relative:relative37,requiresNode:candidate.requiresNode}}return null}function hasAnyLocalCandidate(binary,workingDir,platform=process.platform){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`;if(fs92.existsSync(path170.join(workingDir,"node_modules",".bin",executable)))return!0}return!1}function resolveLocalCommand(command,workingDir,isAvailable,platform=process.platform){let tokens2=tokenizeCommand(command);if(tokens2.length===0)return null;let[binary,...args2]=tokens2;if(["npx","bunx","pnpx"].includes(binary))return null;if(binary.includes("/")||binary.includes("\\"))return null;let trimmed=command.trim(),local=resolveLocalCandidate(binary,workingDir,platform,isAvailable);if(local){let shellPath=platform==="win32"?local.relative:`./${local.relative}`;return{argv:[local.absolute,...args2],shellCommand:`${shellPath}${trimmed.slice(findCommandSuffixStart(trimmed))}`}}if(hasAnyLocalCandidate(binary,workingDir,platform))return null;return isAvailable(binary)?{argv:tokens2,shellCommand:command}:null}function resolveLocalNodeTool(tool3,args2,workingDir,platform=process.platform,isAvailable){let local=resolveLocalCandidate(tool3,workingDir,platform,platform==="win32"?isAvailable:void 0);if(local)return[local.absolute,...args2];if(hasAnyLocalCandidate(tool3,workingDir,platform))return null;return isAvailable?.(tool3)?[tool3,...args2]:null}var WINDOWS_LOCAL_SHIM_CANDIDATES;var init_command_resolution=__esm(()=>{WINDOWS_LOCAL_SHIM_CANDIDATES=[{suffix:".cmd",requiresNode:!0},{suffix:".exe",requiresNode:!1},{suffix:".bat",requiresNode:!0},{suffix:".ps1",requiresNode:!0},{suffix:"",requiresNode:!0}]});import*as fs93 from"node:fs";import*as path171 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32";try{let searchName=isWindows?command:command,available=_internals138.spawnSyncImpl(isWindows?["where",searchName]:["which",searchName],{cwd:process.cwd(),stdin:"ignore",stdout:"ignore",stderr:"ignore",timeout:IS_COMMAND_AVAILABLE_TIMEOUT_MS}).success;return toolchainCache.set(command,available),available}catch{return toolchainCache.set(command,!1),!1}}function checkToolchain(commands){return commands.some((cmd)=>_internals138.isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs93.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path171.join(dir,matches[0])}catch{}}else{let filePath=path171.join(workingDir,pattern);if(fs93.existsSync(filePath))return filePath}return null}function sanitizeEvidenceText(raw,maxChars){let withoutControls="";for(let char of raw){let code=char.charCodeAt(0);withoutControls+=code<32||code===127?" ":char}let normalized=withoutControls.replace(/\s+/g," ").trim();if(!normalized)return"(empty)";if(normalized.length<=maxChars)return normalized;if(maxChars<=3)return normalized.slice(0,maxChars);return`${normalized.slice(0,maxChars-3)}...`}function sanitizeRequiredCommand(command){let sanitized=sanitizeEvidenceText(command,40);return sanitized==="(empty)"?null:sanitized}function getBinaryFromCommand(command){return command.trim().split(/\s+/)[0]??""}function getProfileRequiredCommands(commands){let uniqueCommands=new Set;for(let command of commands){let binary=sanitizeRequiredCommand(getBinaryFromCommand(command.cmd));if(binary)uniqueCommands.add(binary)}return Array.from(uniqueCommands)}function getNoMatchingBuildFilesReason(profileId,commands){let detectFiles=Array.from(new Set(commands.map((command)=>command.detectFile?.trim()).filter((detectFile)=>Boolean(detectFile))));if(detectFiles.length===0)return`No matching build files for profile ${profileId}`;return`No matching build files for profile ${profileId}: expected ${detectFiles.join(" or ")}`}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path171.join(workingDir,"package.json");if(!fs93.existsSync(packageJsonPath))return{commands:[],hasScripts:!1};try{let content=fs93.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return{commands:[],hasScripts:!1};let scriptNames=scripts.filter((name)=>typeof pkg.scripts[name]==="string"&&pkg.scripts[name].trim());if(scriptNames.length===0)return{commands:[],hasScripts:!1};let rawPackageManager=typeof pkg.packageManager==="string"?pkg.packageManager.trim():void 0,declared=rawPackageManager?.split("@")[0]?.trim(),supported=[...SUPPORTED_NODE_PACKAGE_MANAGERS],sanitizedDeclared=declared?sanitizeRequiredCommand(declared):null,candidates=declared?[declared]:supported;if(rawPackageManager!==void 0&&(!declared||!supported.includes(declared)))return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:sanitizedDeclared?[sanitizedDeclared]:[],reason:`Unsupported packageManager: ${sanitizeEvidenceText(rawPackageManager,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS)}`}};let manager=candidates.find((candidate)=>_internals138.isCommandAvailable(candidate));if(!manager)return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:candidates,reason:`Package manager not available: ${candidates.join(" or ")}`}};return{hasScripts:!0,commands:scriptNames.map((scriptName)=>({command:`${manager} run ${scriptName}`,priority:100}))}}catch{return{commands:[],hasScripts:!1}}}function filterByScope(workingDir,scope,changedFiles){if(scope==="all")return findAllBuildFiles(workingDir);if(!changedFiles||changedFiles.length===0)return[];return changedFiles}function findAllBuildFiles(workingDir){let allBuildFiles=new Set;for(let ecosystem of ECOSYSTEMS)for(let pattern of ecosystem.buildFiles)if(pattern.includes("*")){let regex=simpleGlobToRegex(pattern);findFilesRecursive(workingDir,regex,allBuildFiles)}else{let filePath=path171.join(workingDir,pattern);if(fs93.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries2=fs93.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path171.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&&regex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await _internals138.detectProjectLanguagesImpl(workingDir);for(let profile of detectedProfiles){let fullProfile=_internals138.getLanguageProfileImpl(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>b.priority-a.priority),applicableCommands=sortedCommands.filter((cmd)=>{if(!cmd.detectFile)return!0;let detectFilePath=path171.join(workingDir,cmd.detectFile);return fs93.existsSync(detectFilePath)});if(applicableCommands.length===0){skipped.push({ecosystem:fullProfile.id,reason:getNoMatchingBuildFilesReason(fullProfile.id,sortedCommands)});continue}let foundCommand=!1;for(let cmd of applicableCommands){let resolved=resolveLocalCommand(cmd.cmd,workingDir,_internals138.isCommandAvailable);if(resolved){commands.push({ecosystem:fullProfile.id,command:resolved.shellCommand,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let requiredCommands=getProfileRequiredCommands(applicableCommands),triedBinaries=requiredCommands.join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,code:"environment_unavailable",required_commands:requiredCommands,reason}),warn(`[build-discovery] profile ${fullProfile.id}: no binary available, skipping`)}}return{commands,skipped}}async function discoverBuildCommands(workingDir,options){let scope=options?.scope??"all",changedFiles=options?.changedFiles??[],_filesToCheck=filterByScope(workingDir,scope,changedFiles),profileResult=await _internals138.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,repoDefinedScriptsByEcosystem=new Map,repoScriptSkips=[],repoDeclaredEcosystems=new Set;for(let ecosystem of ECOSYSTEMS){if(!ecosystem.repoDefinedScripts)continue;let repoResult=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoResult.commands.length>0)repoDefinedScriptsByEcosystem.set(ecosystem.ecosystem,repoResult.commands);if(repoResult.hasScripts)repoDeclaredEcosystems.add(ecosystem.ecosystem);if(repoResult.skip)repoScriptSkips.push(repoResult.skip)}let filteredProfileCommands=profileCommands.filter((cmd)=>{return(PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[]).every((name)=>!repoDeclaredEcosystems.has(name))}),coveredEcosystems=new Set;for(let cmd of filteredProfileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...filteredProfileCommands],skipped=[...profileSkipped,...repoScriptSkips];for(let ecosystem of ECOSYSTEMS){if(!findBuildFiles(workingDir,ecosystem.buildFiles))continue;let repoScripts=repoDefinedScriptsByEcosystem.get(ecosystem.ecosystem);if(repoScripts&&repoScripts.length>0){for(let script of repoScripts)commands.push({ecosystem:ecosystem.ecosystem,command:script.command,cwd:workingDir,priority:script.priority});continue}if(repoDeclaredEcosystems.has(ecosystem.ecosystem))continue;if(coveredEcosystems.has(ecosystem.ecosystem)){skipped.push({ecosystem:ecosystem.ecosystem,reason:"Covered by profile detection"});continue}if(!checkToolchain(ecosystem.toolchainCommands)){skipped.push({ecosystem:ecosystem.ecosystem,code:"environment_unavailable",required_commands:ecosystem.toolchainCommands,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}let availableCommands=ecosystem.commands;for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>b.priority-a.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var SUPPORTED_NODE_PACKAGE_MANAGERS,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS=120,ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals138,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();init_command_resolution();SUPPORTED_NODE_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn"],ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:[...SUPPORTED_NODE_PACKAGE_MANAGERS],commands:[{command:"npm run build",priority:30},{command:"npm run typecheck",priority:20},{command:"npm run check",priority:10}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:20},{command:"cargo check",priority:10}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:10}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m build",priority:20},{command:"python -m py_compile",priority:10}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:10}]},{ecosystem:"java-gradle",buildFiles:["build.gradle","build.gradle.kts","gradle.properties"],toolchainCommands:["gradle","gradlew"],commands:[{command:process.platform==="win32"?"gradlew.bat build":"./gradlew build",priority:20},{command:"gradle build",priority:10}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:10}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:10}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart compile",priority:20},{command:"dart analyze",priority:10}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:20},{command:"cmake -B build && cmake --build build",priority:10}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:10}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["node"],javascript:["node"],python:["python"],rust:["rust"],go:["go"],java:["java-maven","java-gradle"],kotlin:["java-gradle"],csharp:["dotnet"],cpp:["cpp"],swift:["swift"],dart:["dart"],ruby:[],php:["php-composer"]},toolchainCache=new Map;_internals138={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,detectProjectLanguagesImpl:detectProjectLanguages,getLanguageProfileImpl:LANGUAGE_REGISTRY.get.bind(LANGUAGE_REGISTRY),spawnSyncImpl:bunSpawnSync};build_discovery=tool({description:"Discover build commands for various ecosystems in a project directory",args:{workingDir:tool.schema.string().describe("Directory to scan for build commands (defaults to current directory)"),scope:tool.schema.string().optional().describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changedFiles:tool.schema.array(tool.schema.string()).optional().describe('List of changed files when scope is "changed"')},async execute(args2,_context){let result=await discoverBuildCommands(args2.workingDir,{scope:args2.scope??"all",changedFiles:args2.changedFiles??[]});return JSON.stringify(result,null,2)}})});var init_tool_names=__esm(()=>{init_tool_metadata()});var exports_tool_doctor={};__export(exports_tool_doctor,{runToolDoctor:()=>runToolDoctor,getBinaryReadinessAdvisory:()=>getBinaryReadinessAdvisory,checkAgentToolMapAlignment:()=>checkAgentToolMapAlignment});function getRegisteredToolKeys(){return new Set(TOOL_NAME_SET)}function checkAgentToolMapAlignment(registeredKeys){let findings=[];for(let[agentName,tools]of Object.entries(AGENT_TOOL_MAP))for(let toolName of tools)if(!registeredKeys.has(toolName))findings.push({id:`agent-tool-map-mismatch-${agentName}-${toolName}`,title:"AGENT_TOOL_MAP alignment gap",description:`Tool "${toolName}" is assigned to agent "${agentName}" in AGENT_TOOL_MAP but is not a registered tool name. The agent will not be able to use this tool.`,severity:"error",path:`AGENT_TOOL_MAP.${agentName}`,currentValue:toolName,autoFixable:!1});return findings}function checkBinaryReadiness(){let findings=[];for(let{binary,language}of BINARY_CHECKLIST)if(!isCommandAvailable(binary))findings.push({id:`missing-binary-${binary}`,title:"Class 3 tool binary not found",description:`Binary "${binary}" is not available on PATH. ${language} linting will not be available. Install ${binary} to enable ${language} language support.`,severity:"warn",path:`toolchain.${binary}`,currentValue:void 0,autoFixable:!1});return findings}function getBinaryReadinessAdvisory(){let findings=checkBinaryReadiness();if(findings.length===0)return null;return["[PRE-FLIGHT ADVISORY] The following Class 3 tool binaries were not found on PATH at session start.","These tools will soft-skip at invocation. Plan tasks accordingly.",...findings.map((f)=>`- MISSING BINARY: ${f.currentValue??f.path?.split(".")[1]??"unknown"} — ${f.description}`)].join(`
2464
+ `)}async function handleDiagnoseCommand(directory,_args,sessionID){let diagnoseData=await getDiagnoseData(directory,sessionID);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals137,SWARM_DB_QUICK_CHECK_MAX_BYTES2=67108864,GIT_REPOSITORY_CHECK_TIMEOUT_MS=5000,GIT_REPOSITORY_CHECK_MAX_BUFFER_BYTES=65536;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_health();init_core_events();init_gate_bridge();init_manager2();init_action_circuit();init_state3();init_gate_evidence();init_learning_health();init_utils2();init_task_model_routing();init_manager();init_capability_probe();init_executor();init_skip_state();init_path_identity();init_effective_spec();init_state2();init_git_executable();init_coder_settlement();init_recovery_invocation();init_stage_a_repair();init_task_recovery_status();init_knowledge_diagnostics();init_swarm_residue();init_version_check();init_warning_buffer();({version:version4}=package_default),sandboxCapabilityProbe=new SandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS=["tree-sitter.wasm","tree-sitter-javascript.wasm","tree-sitter-typescript.wasm"],_internals137={detectSandboxCapability:()=>sandboxCapabilityProbe.detect(),getSandboxExecutor:getExecutor,execFileSync:(...args2)=>child_process7.execFileSync(...args2)}});var init_diagnose=__esm(()=>{init_diagnose_service()});var exports_config_doctor={};__export(exports_config_doctor,{writeDoctorArtifact:()=>writeDoctorArtifact,writeBackupArtifact:()=>writeBackupArtifact,shouldRunOnStartup:()=>shouldRunOnStartup,runConfigDoctorWithFixes:()=>runConfigDoctorWithFixes,runConfigDoctor:()=>runConfigDoctor,restoreFromBackup:()=>restoreFromBackup,removeStraySwarmDir:()=>removeStraySwarmDir,readDoctorArtifact:()=>readDoctorArtifact,getConfigPaths:()=>getConfigPaths,detectStraySwarmDirs:()=>detectStraySwarmDirs,createConfigBackup:()=>createConfigBackup,collectLeanTurboGateSatisfiabilityFindings:()=>collectLeanTurboGateSatisfiabilityFindings,applySafeAutoFixes:()=>applySafeAutoFixes,LEAN_TURBO_GATE_PRODUCERS:()=>LEAN_TURBO_GATE_PRODUCERS});import*as crypto9 from"node:crypto";import*as fs91 from"node:fs";import*as os23 from"node:os";import*as path169 from"node:path";function levenshteinDistance(a,b){let al=a.length,bl=b.length,matrix=[];for(let i=0;i<=al;i++)matrix[i]=[i];for(let j=0;j<=bl;j++)matrix[0][j]=j;for(let i=1;i<=al;i++)for(let j=1;j<=bl;j++){let cost=a[i-1]===b[j-1]?0:1;matrix[i][j]=Math.min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+cost)}return matrix[al][bl]}function emitObjectTypeMismatch(key2,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key2}-type`,title:`Invalid ${key2} type`,description:`"${key2}" must be an object, got ${typeof value}`,severity:"error",path:key2,currentValue:value,autoFixable:!1})}function isPlainObject5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function collectRawCouncilPolicyFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.council===void 0)continue;if(!isPlainObject5(raw.council))continue;let council=raw.council;if("parallelTimeoutMs"in council)findings.push({id:"council-parallel-timeout-deprecated",title:"Deprecated and inert: council.parallelTimeoutMs",description:'Config field "council.parallelTimeoutMs" (in '+configPath+") is deprecated and inert: no runtime consumer exists and no timeout is enforced. It is accepted only for parse compatibility. Remove the key — dispatch timeouts are governed by the agent host. The field is scheduled for removal in a future release.",severity:"warn",path:"council.parallelTimeoutMs",currentValue:council.parallelTimeoutMs,autoFixable:!1});if("escalateOnMaxRounds"in council)findings.push({id:"council-escalate-inert",title:"Inert: council.escalateOnMaxRounds",description:'Config field "council.escalateOnMaxRounds" (in '+configPath+") is set, but the handler/webhook remains INERT in this release: no handler, webhook, or outbound execution exists or was added (issue #1650). Max-rounds exhaustion emits a durable structured event (.swarm/council/events/max-rounds-exhaustion.jsonl) and a user escalation message instead; the run stays fail-closed. Wiring real outbound escalation requires a separate security review.",severity:"warn",path:"council.escalateOnMaxRounds",currentValue:"[redacted: handler/webhook strings are never echoed]",autoFixable:!1});if(isPlainObject5(council.finalCompletionPolicy)&&council.finalCompletionPolicy.mode==="quorum")findings.push({id:"council-final-quorum-weaker",title:'council.finalCompletionPolicy.mode "quorum" weakens the strict final council',description:"Final-council completion is configured in quorum mode (in "+configPath+"): a bounded minimum of distinct canonical members can accept the project instead of the strict default (all five canonical roles, zero absentees). This is weaker than the strict default. Any change to this policy invalidates previously accepted final-council evidence.",severity:"warn",path:"council.finalCompletionPolicy",currentValue:council.finalCompletionPolicy,autoFixable:!1})}catch{}}return findings}function collectLeanTurboGateSatisfiabilityFindings(config3,registeredToolNames=TOOL_NAME_SET){let findings=[],lean=config3?.turbo?.lean;for(let entry of LEAN_TURBO_GATE_PRODUCERS){let enabled=lean?.[entry.gate]??!0;if(!enabled)continue;if(registeredToolNames.has(entry.producerTool))continue;findings.push({id:`lean-turbo-gate-unsatisfiable-${entry.gate}`,title:`turbo.lean.${entry.gate} gate has no registered producer tool`,description:`turbo.lean.${entry.gate} is enabled (default true), but its evidence producer tool "${entry.producerTool}" is not registered, so the gate that reads ${entry.evidencePathConvention} is structurally unsatisfiable in production and Lean Turbo phase_complete would dead-end. Re-register the producer tool or disable the gate (issue #2470 / #2007).`,severity:"error",path:`turbo.lean.${entry.gate}`,currentValue:enabled,autoFixable:!1})}return findings}function collectRawGatesConfigFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.gates===void 0)continue;if(!isPlainObject5(raw.gates)){findings.push({id:"invalid-gates-config",title:"Invalid gates config",description:`"gates" in ${configPath} must be an object. The loader ignores that section and keeps other valid config sections active.`,severity:"error",path:"gates",currentValue:raw.gates,autoFixable:!1});continue}for(let[sectionName,sectionValue]of Object.entries(raw.gates)){let schema=GateConfigSchema.shape[sectionName];if(!schema){findings.push({id:"unknown-gates-section",title:"Unknown gates config section",description:`Unknown gates section "gates.${sectionName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1});continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[sectionName];if(knownFields&&isPlainObject5(sectionValue)){let knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(sectionValue))if(!knownFieldSet.has(fieldName))findings.push({id:"unknown-gates-key",title:"Unknown gates config key",description:`Unknown gates key "gates.${sectionName}.${fieldName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}.${fieldName}`,currentValue:sectionValue[fieldName],autoFixable:!1})}if(!schema.safeParse(sectionValue).success)findings.push({id:"invalid-gates-section",title:"Invalid gates config section",description:`"gates.${sectionName}" in ${configPath} failed validation. The loader uses defaults for that gate section and keeps other valid config sections active.`,severity:"error",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1})}}catch{}}return findings}function collectRawStrictSectionFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;let seen=new Set;for(let issue3 of parsed.error.issues){if(issue3.code!=="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let keys=issue3.keys??[];for(let key2 of keys){let dotted2=[...issue3.path.map(String),key2].join(".");if(seen.has(dotted2))continue;seen.add(dotted2),findings.push({id:"unknown-config-key",title:"Unknown config key",description:`Unrecognized key "${dotted2}" in ${configPath} is ignored by the loader (the rest of your config is preserved). Fix or remove it.`,severity:"warn",path:dotted2,currentValue:void 0,autoFixable:!1})}}}catch{}}return findings}function getRawValueAtPath(raw,issuePath){let node=raw;for(let seg of issuePath){if(node===null||typeof node!=="object")return;node=node[seg]}return node}function collectRawValueConstraintFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory),applyTargetPath=fs91.existsSync(projectConfigPath)?projectConfigPath:userConfigPath,seen=new Set,filesInApplyOrder=applyTargetPath===projectConfigPath?[projectConfigPath,userConfigPath]:[userConfigPath,projectConfigPath];for(let configPath of filesInApplyOrder){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;for(let issue3 of parsed.error.issues){if(issue3.code==="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let dotted2=issue3.path.map(String).join("."),dedupeKey=`${dotted2}|${issue3.code}`;if(seen.has(dedupeKey))continue;seen.add(dedupeKey);let current=getRawValueAtPath(raw,issue3.path);if(issue3.code==="too_big"&&dotted2.endsWith("fallback_models")&&Array.isArray(current)&&current.length>FALLBACK_MODELS_MAX){let trimmed=current.slice(0,FALLBACK_MODELS_MAX),dropped=current.slice(FALLBACK_MODELS_MAX).map(String),inApplyTarget=configPath===applyTargetPath,drop=`${dropped.length} entr${dropped.length===1?"y":"ies"}`;findings.push({id:"fallback-models-too-many",title:"Too many fallback models",description:`"${dotted2}" in ${configPath} lists ${current.length} models; the maximum is ${FALLBACK_MODELS_MAX}. A config that fails validation is discarded in favor of safe defaults. `+(inApplyTarget?`Run /swarm config doctor --fix to trim to the first ${FALLBACK_MODELS_MAX} (drops ${drop}: ${dropped.join(", ")}), or edit the file yourself.`:`Remove ${drop} from that file (would drop: ${dropped.join(", ")}).`),severity:"error",path:dotted2,currentValue:current,autoFixable:inApplyTarget,proposedFix:{type:"update",path:dotted2,value:trimmed,description:`Trim "${dotted2}" to the first ${FALLBACK_MODELS_MAX} models`,risk:"low",lossy:!0}});continue}findings.push({id:"invalid-config-value",title:"Invalid config value",description:`"${dotted2||"(root)"}" in ${configPath} is invalid: ${issue3.message}. A config that fails validation is discarded in favor of safe defaults until this is fixed.`,severity:"error",path:dotted2,currentValue:current,autoFixable:!1})}}catch{}}return findings}function collectRawAutoReviewCompatibilityFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs91.existsSync(configPath))continue;try{if(fs91.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs91.readFileSync(configPath,"utf8"));if(!isPlainObject5(raw)||!isPlainObject5(raw.auto_review))continue;let autoReview=raw.auto_review;if(autoReview.structured_findings===!1&&isPlainObject5(autoReview.final_review)&&autoReview.final_review.mode==="gate"){findings.push({id:"invalid-auto-review-gate-compatibility",title:"Invalid auto-review gate configuration",description:'auto_review.final_review.mode="gate" requires auto_review.structured_findings=true so gate evidence is machine-verifiable.',severity:"error",path:"auto_review.structured_findings",currentValue:!1,autoFixable:!1});break}}catch{}}return findings}function emitWorktreeIsolationLayeringAdvisory(config3,findings){let parallelization=config3.parallelization,worktreePolicy=config3.worktree?.policy??"auto";if(parallelization?.enabled===!0&&(parallelization.maxConcurrentTasks??1)>1&&worktreePolicy!=="disabled")findings.push({id:"worktree-isolation-baseline-active",title:"Worktree isolation is already active for standard parallel coders",description:"Standard parallel coders already use baseline worktree isolation through the parallel execution profile plus top-level worktree.policy. Lean Turbo and Epic are additive strategies, not requirements for obtaining worktree isolation.",severity:"warn",path:"worktree.policy",currentValue:worktreePolicy,autoFixable:!1})}function getUserConfigDir3(){return process.env.XDG_CONFIG_HOME||path169.join(os23.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path169.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path169.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto9.createHash("sha256").update(content,"utf-8").digest("hex")}function isValidConfigPath(configPath,directory){let pathParts=configPath.replace(/\\/g,"/").split("/");for(let part of pathParts)if(part===".."||part===""){if(part==="..")return!1}let{userConfigPath,projectConfigPath}=getConfigPaths(directory);try{let resolvedConfig=path169.resolve(configPath),resolvedUser=path169.resolve(userConfigPath),resolvedProject=path169.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs91.existsSync(resolvedConfig)){if(fs91.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs91.writeFileSync(tmpPath,content,"utf-8");try{fs91.renameSync(tmpPath,filePath)}catch{try{fs91.unlinkSync(filePath)}catch{}fs91.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs91.existsSync(projectConfigPath))try{content=fs91.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs91.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs91.readFileSync(userConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] user config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}}if(content===null)return null;return{createdAt:Date.now(),configPath,content,contentHash:computeHash(content)}}function writeBackupArtifact(directory,backup){let swarmDir=path169.join(directory,".swarm");if(!fs91.existsSync(swarmDir))fs91.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path169.join(swarmDir,backupFilename),artifact={createdAt:backup.createdAt,configPath:backup.configPath,contentHash:backup.contentHash,content:backup.content,preview:backup.content.substring(0,500)+(backup.content.length>500?"...":"")};return atomicWriteFileSync(backupPath,JSON.stringify(artifact,null,2)),backupPath}function restoreFromBackup(backupPath,directory){if(!fs91.existsSync(backupPath))return null;let swarmDir=path169.resolve(directory,".swarm"),resolvedBackup=path169.resolve(backupPath);if(!isCanonicalPathWithinRoot(resolvedBackup,swarmDir))return null;try{let artifact=JSON.parse(fs91.readFileSync(backupPath,"utf-8"));if(!artifact.content||!artifact.configPath||!artifact.contentHash)return null;if(!isValidConfigPath(artifact.configPath,directory))return null;let computedHash=computeHash(artifact.content),storedHash=artifact.contentHash;if(!/^\d+$/.test(storedHash)&&computedHash!==storedHash)return null;log("[ConfigDoctor] Warning: restoring from backup with legacy numeric hash (pre-SHA-256). Consider re-backing up.",{});let targetPath=artifact.configPath,targetDir=path169.dirname(targetPath);if(!fs91.existsSync(targetDir))fs91.mkdirSync(targetDir,{recursive:!0});return atomicWriteFileSync(targetPath,artifact.content),targetPath}catch{return null}}function readConfigFromFile(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent=null;if(fs91.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs91.readFileSync(projectConfigPath,"utf-8");else if(fs91.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs91.readFileSync(userConfigPath,"utf-8");if(configContent===null)return null;try{return{config:JSON.parse(configContent),configPath}}catch(error93){return log(`[ConfigDoctor] Failed to parse config file: ${configPath}`,{error:error93 instanceof Error?error93.message:String(error93)}),null}}function validateConfigKey(path170,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path170===depPath&&!depInfo.isDefaultValue(value))findings.push({id:"deprecated-field",title:`Deprecated config field: ${depPath}`,description:`Config field "${depPath}" is deprecated. Replacement: ${depInfo.replacement}.`,severity:"info",path:depPath,currentValue:value,autoFixable:!1});switch(path170){case"agents":{if(value!==void 0)findings.push({id:"deprecated-agents-config",title:"Deprecated agents configuration",description:'The "agents" field is deprecated. Use "swarms" instead for multi-swarm support.',severity:"warn",path:"agents",currentValue:value,autoFixable:!1,proposedFix:{type:"remove",path:"agents",description:"Remove deprecated agents config - use swarms instead",risk:"low"}});break}case"config_format_version":{if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<0)findings.push({id:"type-mismatch",title:`Config field "${path170}" has wrong type`,description:`Expected non-negative integer, got ${typeof value==="number"?Number.isInteger(value)?value:`${value} (non-integer)`:typeof value}`,severity:"error",path:path170,currentValue:value,autoFixable:!1});break}case"guardrails.enabled":{if(value===!1)findings.push({id:"guardrails-disabled",title:"Guardrails disabled",description:"Guardrails have been explicitly disabled. This removes safety limits.",severity:"error",path:"guardrails.enabled",currentValue:value,autoFixable:!1});break}case"guardrails.profiles":{let profiles=value;if(profiles){let validAgents=new Set(ALL_AGENT_NAMES);for(let[agentName,profile]of Object.entries(profiles))if(!validAgents.has(agentName))findings.push({id:"unknown-agent-profile",title:"Unknown agent profile",description:`Profile for unknown agent "${agentName}" will be ignored.`,severity:"info",path:`guardrails.profiles.${agentName}`,currentValue:profile,autoFixable:!0,proposedFix:{type:"remove",path:`guardrails.profiles.${agentName}`,description:`Remove unknown agent profile "${agentName}"`,risk:"low"}})}break}case"automation.mode":{let validModes=["manual","hybrid","auto"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-automation-mode",title:"Invalid automation mode",description:`Invalid automation mode "${value}". Valid: ${validModes.join(", ")}`,severity:"error",path:"automation.mode",currentValue:value,autoFixable:!0,proposedFix:{type:"update",path:"automation.mode",value:"manual",description:'Reset to safe default "manual"',risk:"low"}});break}case"automation.capabilities":{let caps=value;if(caps){let capabilityNames=["plan_sync","phase_preflight","config_doctor_on_startup","evidence_auto_summaries","decision_drift_detection"];for(let[name,capValue]of Object.entries(caps))if(capabilityNames.includes(name)&&typeof capValue!=="boolean")findings.push({id:"invalid-capability-type",title:"Invalid capability type",description:`Capability "${name}" must be boolean, got ${typeof capValue}`,severity:"error",path:`automation.capabilities.${name}`,currentValue:capValue,autoFixable:!0,proposedFix:{type:"update",path:`automation.capabilities.${name}`,value:!1,description:`Reset capability "${name}" to false`,risk:"low"}})}break}case"hooks":{if(emitObjectTypeMismatch("hooks",value,findings),value!==void 0&&typeof value==="object"&&!Array.isArray(value)&&value!==null){let hooks2=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks2))if(!validHooks.includes(hookName))findings.push({id:"unknown-hook-field",title:"Unknown hook configuration",description:`Unknown hook "${hookName}" will be ignored.`,severity:"info",path:`hooks.${hookName}`,currentValue:hooks2[hookName],autoFixable:!0,proposedFix:{type:"remove",path:`hooks.${hookName}`,description:`Remove unknown hook "${hookName}"`,risk:"low"}})}break}case"max_iterations":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-iterations",title:"max_iterations out of bounds",description:`max_iterations must be 1-10, got ${numValue}`,severity:"error",path:"max_iterations",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"max_iterations",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"qa_retry_limit":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-retry-limit",title:"qa_retry_limit out of bounds",description:`qa_retry_limit must be 1-10, got ${numValue}`,severity:"error",path:"qa_retry_limit",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"qa_retry_limit",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"swarms":{if(value!==void 0){if(typeof value!=="object"||Array.isArray(value)||value===null){findings.push({id:"invalid-swarms-type",title:"Invalid swarms type",description:`"swarms" must be an object, got ${typeof value}`,severity:"error",path:"swarms",currentValue:value,autoFixable:!1});break}let swarms=value;if(Object.keys(swarms).length===0)findings.push({id:"empty-swarms",title:"Empty swarms configuration",description:'The "swarms" field is an empty object. No swarm configurations are defined.',severity:"info",path:"swarms",autoFixable:!1});for(let swarmId of Object.keys(swarms))if(swarmId.includes("..")||swarmId.includes("/")||swarmId.includes("\\")||swarmId.includes("\x00"))findings.push({id:"swarm-id-path-traversal",title:"Path traversal in swarm ID",description:`Swarm ID "${swarmId}" contains path traversal characters.`,severity:"error",path:`swarms.${swarmId}`,autoFixable:!1});let validAgents=new Set(ALL_AGENT_NAMES);for(let[swarmId,swarmConfig]of Object.entries(swarms)){let swarm=swarmConfig;if(swarm.agents&&typeof swarm.agents==="object")for(let[agentName]of Object.entries(swarm.agents)){let baseName=stripKnownSwarmPrefix(agentName);if(baseName!==agentName&&agentName.startsWith(`${swarmId}_`)&&validAgents.has(baseName))findings.push({id:"prefixed-swarm-agent-override",title:"Prefixed agent override is ignored",description:`Agent "${agentName}" in swarm "${swarmId}" uses a generated agent name. Per-swarm overrides must use the canonical key "${baseName}", e.g. "swarms.${swarmId}.agents.${baseName}.model". Otherwise the override is ignored and the agent falls back to its default model.`,severity:"warn",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1});else if(!validAgents.has(baseName))findings.push({id:"unknown-swarm-agent",title:"Unknown agent in swarm",description:`Agent "${agentName}" in swarm "${swarmId}" may not be recognized.`,severity:"info",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1})}}}break}case"default_agent":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-default_agent-type",title:"Invalid default_agent type",description:`"default_agent" must be a string, got ${typeof value}`,severity:"error",path:"default_agent",currentValue:value,autoFixable:!1});break}case"auto_select_architect":{if(value!==void 0&&typeof value!=="boolean"&&typeof value!=="string")findings.push({id:"invalid-auto_select_architect-type",title:"Invalid auto_select_architect type",description:`"auto_select_architect" must be a boolean or string, got ${typeof value}`,severity:"error",path:"auto_select_architect",currentValue:value,autoFixable:!1});break}case"pipeline":{emitObjectTypeMismatch("pipeline",value,findings);break}case"harness_evolution":{emitObjectTypeMismatch("harness_evolution",value,findings);break}case"phase_complete":{emitObjectTypeMismatch("phase_complete",value,findings);break}case"execution_mode":{let validModes=["strict","balanced","fast"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-execution_mode-type",title:"Invalid execution_mode",description:`"execution_mode" must be one of: ${validModes.join(", ")}, got "${value}"`,severity:"error",path:"execution_mode",currentValue:value,autoFixable:!1});break}case"inject_phase_reminders":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-inject_phase_reminders-type",title:"Invalid inject_phase_reminders type",description:`"inject_phase_reminders" must be a boolean, got ${typeof value}`,severity:"error",path:"inject_phase_reminders",currentValue:value,autoFixable:!1});break}case"gates":{emitObjectTypeMismatch("gates",value,findings);break}case"context_budget":{emitObjectTypeMismatch("context_budget",value,findings);break}case"pricing":{emitObjectTypeMismatch("pricing",value,findings);break}case"guardrails":{emitObjectTypeMismatch("guardrails",value,findings);break}case"watchdog":{emitObjectTypeMismatch("watchdog",value,findings);break}case"self_review":{emitObjectTypeMismatch("self_review",value,findings);break}case"tool_filter":{emitObjectTypeMismatch("tool_filter",value,findings);break}case"authority":{emitObjectTypeMismatch("authority",value,findings);break}case"plan_cursor":{emitObjectTypeMismatch("plan_cursor",value,findings);break}case"context_map":{emitObjectTypeMismatch("context_map",value,findings);break}case"evidence":{emitObjectTypeMismatch("evidence",value,findings);break}case"summaries":{emitObjectTypeMismatch("summaries",value,findings);break}case"auto_review":{emitObjectTypeMismatch("auto_review",value,findings);break}case"repo_graph":{emitObjectTypeMismatch("repo_graph",value,findings);break}case"retention":{emitObjectTypeMismatch("retention",value,findings);break}case"review_passes":{emitObjectTypeMismatch("review_passes",value,findings);break}case"adversarial_detection":{emitObjectTypeMismatch("adversarial_detection",value,findings);break}case"adversarial_testing":{emitObjectTypeMismatch("adversarial_testing",value,findings);break}case"integration_analysis":{emitObjectTypeMismatch("integration_analysis",value,findings);break}case"docs":{emitObjectTypeMismatch("docs",value,findings);break}case"design_docs":{emitObjectTypeMismatch("design_docs",value,findings);break}case"git":{emitObjectTypeMismatch("git",value,findings);break}case"git.binary":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-git-binary-type",title:"Invalid git.binary type",description:`"git.binary" must be a string, got ${typeof value}`,severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});else if(typeof value==="string"&&value.trim()==="")findings.push({id:"empty-git-binary",title:"Empty git.binary",description:'"git.binary" is blank, so no git executable is named. Remove the key to fall back to the default `git` lookup, or set it to a real git executable path.',severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});break}case"ui_review":{emitObjectTypeMismatch("ui_review",value,findings);break}case"compaction_advisory":{emitObjectTypeMismatch("compaction_advisory",value,findings);break}case"lint":{emitObjectTypeMismatch("lint",value,findings);break}case"secretscan":{emitObjectTypeMismatch("secretscan",value,findings);break}case"checkpoint":{emitObjectTypeMismatch("checkpoint",value,findings);break}case"apply_patch":{emitObjectTypeMismatch("apply_patch",value,findings);break}case"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",value,findings);break}case"observability":{if(emitObjectTypeMismatch("observability",value,findings),typeof value==="object"&&value!==null&&!Array.isArray(value)){let exportCfg=value.export;if(typeof exportCfg==="object"&&exportCfg!==null&&exportCfg.enabled===!0){let endpoint=exportCfg.endpoint,problem=null;if(typeof endpoint!=="string"||endpoint.length===0)problem="observability.export.enabled is true but endpoint is empty — the exporter stays disabled until an endpoint is configured.";else try{let url3=new URL(endpoint),host=url3.hostname.replace(/^\[|\]$/g,""),isLoopback=host==="localhost"||host==="127.0.0.1"||host==="::1";if(url3.protocol!=="https:"&&!isLoopback)problem="observability.export.endpoint uses plain http: for a non-loopback host — exported telemetry would travel unencrypted; use https: outside local test collectors."}catch{problem="observability.export.endpoint is not a valid URL — the exporter stays disabled."}if(problem!==null)findings.push({id:"observability-export-endpoint-policy",title:"OTLP export endpoint policy",description:problem,severity:"warn",path:"observability.export.endpoint",autoFixable:!1})}}break}case"learning":{emitObjectTypeMismatch("learning",value,findings);break}case"consensus":{emitObjectTypeMismatch("consensus",value,findings);break}case"curator":{emitObjectTypeMismatch("curator",value,findings);break}case"architectural_supervision":{emitObjectTypeMismatch("architectural_supervision",value,findings);break}case"knowledge_application":{emitObjectTypeMismatch("knowledge_application",value,findings);break}case"skillPropagation":{emitObjectTypeMismatch("skillPropagation",value,findings);break}case"skill_improver":{emitObjectTypeMismatch("skill_improver",value,findings);break}case"skills":{emitObjectTypeMismatch("skills",value,findings);break}case"spec_writer":{emitObjectTypeMismatch("spec_writer",value,findings);break}case"tool_output":{emitObjectTypeMismatch("tool_output",value,findings);break}case"slop_detector":{emitObjectTypeMismatch("slop_detector",value,findings);break}case"todo_gate":{emitObjectTypeMismatch("todo_gate",value,findings);break}case"incremental_verify":{emitObjectTypeMismatch("incremental_verify",value,findings);break}case"compaction_service":{emitObjectTypeMismatch("compaction_service",value,findings);break}case"prm":{emitObjectTypeMismatch("prm",value,findings);break}case"council":{emitObjectTypeMismatch("council",value,findings);break}case"parallelization":{emitObjectTypeMismatch("parallelization",value,findings);break}case"worktree":{emitObjectTypeMismatch("worktree",value,findings);break}case"turbo":{emitObjectTypeMismatch("turbo",value,findings);break}case"turbo_mode":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-turbo_mode-type",title:"Invalid turbo_mode type",description:`"turbo_mode" must be a boolean, got ${typeof value}`,severity:"error",path:"turbo_mode",currentValue:value,autoFixable:!1});break}case"quiet":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-quiet-type",title:"Invalid quiet type",description:`"quiet" must be a boolean, got ${typeof value}`,severity:"error",path:"quiet",currentValue:value,autoFixable:!1});break}case"version_check":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-version_check-type",title:"Invalid version_check type",description:`"version_check" must be a boolean, got ${typeof value}`,severity:"error",path:"version_check",currentValue:value,autoFixable:!1});break}case"$schema":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-$schema-type",title:"Invalid $schema type",description:`"$schema" must be a string (JSON Schema URL), got ${typeof value}`,severity:"error",path:"$schema",currentValue:value,autoFixable:!1});break}case"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"pr_review_resilience":{emitObjectTypeMismatch("pr_review_resilience",value,findings);break}case"review_routing":{if(emitObjectTypeMismatch("review_routing",value,findings),isPlainObject5(value)){let enforceReceipts=value.enforce_receipts;if(enforceReceipts!==void 0&&typeof enforceReceipts!=="boolean")findings.push({id:"invalid-review_routing-enforce_receipts-type",title:"Invalid review_routing.enforce_receipts type",description:`"review_routing.enforce_receipts" must be a boolean, got ${typeof enforceReceipts}`,severity:"error",path:"review_routing.enforce_receipts",currentValue:enforceReceipts,autoFixable:!1})}break}case"lane_liveness_watchdog":{emitObjectTypeMismatch("lane_liveness_watchdog",value,findings);break}case"dispatch_protection":{emitObjectTypeMismatch("dispatch_protection",value,findings);break}case"pr_review_legacy_transcript_compatibility":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-pr_review_legacy_transcript_compatibility-type",title:"Invalid pr_review_legacy_transcript_compatibility type",description:`"pr_review_legacy_transcript_compatibility" must be a boolean, got ${typeof value}`,severity:"error",path:"pr_review_legacy_transcript_compatibility",currentValue:value,autoFixable:!1});break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}case"skill_opt":{emitObjectTypeMismatch("skill_opt",value,findings);break}default:{let topLevel=path170.split(".")[0];if(KNOWN_TOP_LEVEL_KEYS.has(topLevel))break;let MAX_SUGGESTION_KEY_LENGTH=100,lowerTopLevel=topLevel.toLowerCase(),suggestion,matchCount=0;if(lowerTopLevel.length<=MAX_SUGGESTION_KEY_LENGTH){for(let knownKey of KNOWN_TOP_LEVEL_KEYS)if(levenshteinDistance(lowerTopLevel,knownKey.toLowerCase())<=2){if(matchCount++,matchCount===1)suggestion=knownKey}}if(matchCount===1&&suggestion)findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path170}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path170,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path170}" is not in the schema.`,severity:"warn",path:path170,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path170,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path170&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path170,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path170,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path170}`,description:`Config value at "${path170}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path170,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path170,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path170}[${index}]`,findings,visited)});return}for(let[key2,value]of Object.entries(obj)){let newPath=path170?`${path170}.${key2}`:key2;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory){let findings=[];walkConfigAndValidate(config3,"",findings),findings.push(...collectRawGatesConfigFindings(directory)),findings.push(...collectRawCouncilPolicyFindings(directory)),findings.push(...collectRawStrictSectionFindings(directory)),findings.push(...collectRawValueConstraintFindings(directory)),findings.push(...collectRawAutoReviewCompatibilityFindings(directory)),findings.push(...collectLeanTurboGateSatisfiabilityFindings(config3)),emitWorktreeIsolationLayeringAdvisory(config3,findings);let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length},hasAutoFixableIssues=findings.some((f)=>f.autoFixable&&f.proposedFix?.risk==="low"),{userConfigPath,projectConfigPath}=getConfigPaths(directory),configSource="defaults";if(fs91.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs91.existsSync(userConfigPath))configSource=userConfigPath;let rawConfigVersion=config3.config_format_version,configVersion=typeof rawConfigVersion==="number"&&Number.isFinite(rawConfigVersion)&&Number.isInteger(rawConfigVersion)&&rawConfigVersion>=0?rawConfigVersion:1,availableMigrations=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(configVersion<depInfo.deprecatedIn)availableMigrations.push({field:depPath,replacement:depInfo.replacement,deprecatedIn:depInfo.deprecatedIn,sinceVersion:depInfo.sinceVersion,currentFormatVersion:configVersion});return{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource,...availableMigrations.length>0?{availableMigrations}:{}}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe3(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result,options={}){let applyLossy=options.applyLossy===!0,appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs91.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs91.readFileSync(projectConfigPath,"utf-8");else if(fs91.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs91.readFileSync(userConfigPath,"utf-8");else return{appliedFixes,updatedConfigPath:null};let config3;try{config3=JSON.parse(configContent)}catch{return{appliedFixes,updatedConfigPath:null}}let safeFixes=result.findings.filter((f)=>f.autoFixable&&f.proposedFix?.risk==="low"&&(applyLossy||!f.proposedFix?.lossy));for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe3(fix.path))continue;let pathParts=fix.path.split("."),current=config3,navigated=!0;for(let i=0;i<pathParts.length-1;i++){let part=pathParts[i];if(current===null||current===void 0){navigated=!1;break}if(typeof current!=="object"||Array.isArray(current)){navigated=!1;break}let obj=current;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null){navigated=!1;break}else if(typeof obj[part]!=="object"){navigated=!1;break}current=obj[part]}if(!navigated)continue;let lastPart=pathParts[pathParts.length-1];switch(fix.type){case"remove":if(current!==null&&current!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(applyLossy&&result.availableMigrations&&result.availableMigrations.length>0)for(let migration of result.availableMigrations){if(!isPathSafe3(migration.field)||!isPathSafe3(migration.replacement))continue;let legacyParts=migration.field.split("."),legacyParent=config3,legacyNavigated=!0;for(let i=0;i<legacyParts.length-1;i++){let part=legacyParts[i];if(legacyParent===null||legacyParent===void 0||typeof legacyParent!=="object"||Array.isArray(legacyParent)){legacyNavigated=!1;break}let obj=legacyParent;if(obj[part]===void 0||obj[part]===null){legacyNavigated=!1;break}legacyParent=obj[part]}if(!legacyNavigated)continue;let legacyKey=legacyParts[legacyParts.length-1],legacyHolder=legacyParent;if(!(legacyKey in legacyHolder))continue;let legacyValue=legacyHolder[legacyKey],depInfo=DEPRECATED_FIELDS.get(migration.field);if(!depInfo||depInfo.isDefaultValue(legacyValue))continue;let replParts=migration.replacement.split("."),replParent=config3,replNavigated=!0;for(let i=0;i<replParts.length-1;i++){let part=replParts[i];if(replParent===null||replParent===void 0||typeof replParent!=="object"||Array.isArray(replParent)){replNavigated=!1;break}let obj=replParent;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null||typeof obj[part]!=="object"){replNavigated=!1;break}replParent=obj[part]}if(!replNavigated)continue;let replKey=replParts[replParts.length-1];replParent[replKey]=legacyValue,delete legacyHolder[legacyKey],appliedFixes.push({type:"update",path:migration.replacement,value:legacyValue,description:`Migrate deprecated field \`${migration.field}\` → \`${migration.replacement}\``,risk:"low",lossy:!0}),appliedFixes.push({type:"remove",path:migration.field,description:`Remove deprecated field \`${migration.field}\` (migrated to \`${migration.replacement}\`)`,risk:"low",lossy:!0})}if(appliedFixes.length>0){let configDir=path169.dirname(configPath);if(!fs91.existsSync(configDir))fs91.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path169.join(directory,".swarm","config-doctor.json");if(!fs91.existsSync(artifactPath))return null;let content=fs91.readFileSync(artifactPath,"utf-8"),artifact=JSON.parse(content),summary=artifact.summary;if(!summary||typeof summary!=="object")return null;let{info:infoVal,warn:warnVal,error:errorVal}=summary;if(typeof infoVal!=="number"||!Number.isFinite(infoVal)||typeof warnVal!=="number"||!Number.isFinite(warnVal)||typeof errorVal!=="number"||!Number.isFinite(errorVal))return null;let ts=artifact.timestamp;if(typeof ts!=="number"||!Number.isFinite(ts))return null;let findingsCount=infoVal+warnVal+errorVal,findings=artifact.findings,autoFixableCount=Array.isArray(findings)?findings.filter((f)=>f.autoFixable===!0).length:0;return{timestamp:new Date(ts).toISOString(),findingsCount,autoFixableCount}}catch{return null}}function writeDoctorArtifact(directory,result){let swarmDir=path169.join(directory,".swarm");if(!fs91.existsSync(swarmDir))fs91.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path169.join(swarmDir,"config-doctor.json"),guiOutput={timestamp:result.timestamp,summary:result.summary,hasAutoFixableIssues:result.hasAutoFixableIssues,configSource:result.configSource,findings:result.findings.map((f)=>({id:f.id,title:f.title,description:f.description,severity:f.severity,path:f.path,autoFixable:f.autoFixable,proposedFix:f.proposedFix?{type:f.proposedFix.type,path:f.proposedFix.path,description:f.proposedFix.description,risk:f.proposedFix.risk,lossy:f.proposedFix.lossy===!0}:null}))};return atomicWriteFileSync(artifactPath,JSON.stringify(guiOutput,null,2)),artifactPath}function shouldRunOnStartup(automationConfig){if(!automationConfig)return!1;if(automationConfig.mode==="manual")return!1;return automationConfig.capabilities?.config_doctor_on_startup===!0}async function runConfigDoctorWithFixes(directory,config3,autoFix=!1,options={}){let result=runConfigDoctor(config3,directory),artifactPath=writeDoctorArtifact(directory,result);if(!autoFix)return{result,backupPath:null,appliedFixes:[],updatedConfigPath:null,artifactPath};let backup=createConfigBackup(directory),backupPath=null;if(backup)backupPath=writeBackupArtifact(directory,backup);let{appliedFixes,updatedConfigPath}=applySafeAutoFixes(directory,result,options);if(appliedFixes.length>0){let freshConfig=readConfigFromFile(directory);if(freshConfig){let newResult=runConfigDoctor(freshConfig.config,directory);writeDoctorArtifact(directory,newResult)}}return{result,backupPath,appliedFixes,updatedConfigPath,artifactPath}}function detectStraySwarmDirs(projectRoot){let findings=[],SKIP_DIRS=new Set(["node_modules",".git","dist",".cache",".next","coverage",".turbo",".vercel",".terraform","__pycache__",".tox"]),MAX_DEPTH=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries2;try{entries2=fs91.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path169.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path169.join(fullPath,".git");try{let gitStat=fs91.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path169.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs91.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path169.relative(projectRoot,fullPath).replace(/\\/g,"/"),absolutePath:fullPath,contents:contents.slice(0,20),totalEntries:contents.length});continue}walk(fullPath,depth+1)}}return walk(projectRoot,0),findings}function removeStraySwarmDir(projectRoot,strayPath){let canonicalRoot,canonicalStray;try{canonicalRoot=fs91.realpathSync(projectRoot),canonicalStray=fs91.realpathSync(path169.isAbsolute(strayPath)?strayPath:path169.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path169.join(canonicalRoot,".swarm");if(sameExistingFilesystemPath(canonicalStray,rootSwarm)||sameExistingFilesystemPath(canonicalStray,canonicalRoot))return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!isCanonicalPathWithinRoot(canonicalStray,canonicalRoot))return{success:!1,message:"Path is outside project root — refusing to remove"};if(!canonicalStray.replace(/\\/g,"/").endsWith("/.swarm"))return{success:!1,message:"Path is not a .swarm directory — refusing to remove"};try{return fs91.rmSync(canonicalStray,{recursive:!0,force:!0}),{success:!0,message:`Removed stray .swarm directory: ${canonicalStray}`}}catch(err){return{success:!1,message:`Failed to remove: ${err instanceof Error?err.message:String(err)}`}}}var CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES=102400,KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,LEAN_TURBO_GATE_PRODUCERS,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_schema();init_tool_metadata();init_utils();init_filesystem_identity();init_path_security();KNOWN_TOP_LEVEL_KEYS=new Set(Object.keys(PluginConfigSchema.shape)),DEPRECATED_FIELDS=new Map([["skill_improver.model",{message:"deprecated",replacement:"agents.skill_improver.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}]]);LEAN_TURBO_GATE_PRODUCERS=[{gate:"phase_critic",producerTool:"lean_turbo_critic",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-critic.json"},{gate:"phase_reviewer",producerTool:"lean_turbo_review",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-reviewer.json"},{gate:"integrated_diff_required",producerTool:"lean_turbo_run_phase",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo/lean-turbo-phase.json"}];DANGEROUS_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"])});class LanguageRegistry{profiles;extensionIndex;constructor(){this.profiles=new Map,this.extensionIndex=new Map}unregister(id){let profile=this.profiles.get(id);if(!profile)return;if(this.profiles.delete(id),!profile.parserOnly){for(let ext of profile.extensions)if(this.extensionIndex.get(ext)===id)this.extensionIndex.delete(ext)}}register(profile){let existing=this.profiles.get(profile.id);if(existing&&existing!==profile)throw Error(`LanguageRegistry: profile id "${profile.id}" registered twice. Each LanguageProfile.id must be unique. Got: ${profile.displayName} vs existing ${existing.displayName}.`);if(!profile.parserOnly)for(let ext of profile.extensions){let claimedBy=this.extensionIndex.get(ext);if(claimedBy&&claimedBy!==profile.id)throw Error(`LanguageRegistry: extension "${ext}" registered by both "${claimedBy}" and "${profile.id}". A non-parserOnly profile must not collide on extensions. If both languages legitimately share an extension, mark one parserOnly: true.`);this.extensionIndex.set(ext,profile.id)}this.profiles.set(profile.id,profile)}get(id){return this.profiles.get(id)}getById(id){return this.profiles.get(id)}getByExtension(ext){let profileId=this.extensionIndex.get(ext);if(profileId)return this.profiles.get(profileId);return}getAll(){return Array.from(this.profiles.values())}getTier(tier){return Array.from(this.profiles.values()).filter((p)=>p.tier===tier)}}var LANGUAGE_REGISTRY;var init_profiles=__esm(()=>{LANGUAGE_REGISTRY=new LanguageRegistry;LANGUAGE_REGISTRY.register({id:"typescript",displayName:"TypeScript",tier:1,extensions:[".ts",".tsx"],treeSitter:{grammarId:"typescript",wasmFile:"tree-sitter-typescript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"javascript",displayName:"JavaScript",tier:1,extensions:[".js",".jsx",".mjs",".cjs"],treeSitter:{grammarId:"javascript",wasmFile:"tree-sitter-javascript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"python",displayName:"Python",tier:1,extensions:[".py",".pyw"],treeSitter:{grammarId:"python",wasmFile:"tree-sitter-python.wasm",commentNodes:["comment"]},build:{detectFiles:["setup.py","pyproject.toml","setup.cfg"],commands:[{name:"pip install",cmd:"pip install -e .",detectFile:"setup.py",priority:10},{name:"build",cmd:"python -m build",detectFile:"pyproject.toml",priority:9}]},test:{detectFiles:["pytest.ini","pyproject.toml","setup.cfg","conftest.py"],frameworks:[{name:"pytest",detect:"pytest.ini",cmd:"pytest",priority:10},{name:"unittest",detect:"setup.py",cmd:"python -m unittest discover",priority:8}]},lint:{detectFiles:["pyproject.toml",".ruff.toml","setup.cfg"],linters:[{name:"ruff",detect:"pyproject.toml",cmd:"ruff check --fix .",priority:10},{name:"flake8",detect:"setup.cfg",cmd:"flake8 .",priority:8}]},audit:{detectFiles:["requirements.txt","Pipfile.lock","pyproject.toml"],command:"pip-audit --format json",outputFormat:"json"},sast:{nativeRuleSet:"python",semgrepSupport:"ga"},prompts:{coderConstraints:["Use type annotations on all function signatures (PEP 484)","Prefer f-strings over .format() or % formatting","Use pathlib.Path over os.path for filesystem operations","Never use bare except:; catch specific exception types","Follow PEP 8 style; max line length 120 characters"],reviewerChecklist:["Verify type annotations are present on all public functions","Check for bare except clauses or overly broad exception handling","Confirm no mutable default arguments (def f(x=[]) anti-pattern)","Validate f-string usage and no format string injection risks","Check imports are organized (stdlib → third-party → local)"]}});LANGUAGE_REGISTRY.register({id:"rust",displayName:"Rust",tier:1,extensions:[".rs"],treeSitter:{grammarId:"rust",wasmFile:"tree-sitter-rust.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["Cargo.toml"],commands:[{name:"cargo build",cmd:"cargo build",detectFile:"Cargo.toml",priority:10},{name:"cargo check",cmd:"cargo check",detectFile:"Cargo.toml",priority:9}]},test:{detectFiles:["Cargo.toml"],frameworks:[{name:"cargo",detect:"Cargo.toml",cmd:"cargo test",priority:10}]},lint:{detectFiles:["Cargo.toml"],linters:[{name:"clippy",detect:"Cargo.toml",cmd:"cargo clippy --fix --allow-dirty",priority:10},{name:"rustfmt",detect:"Cargo.toml",cmd:"cargo fmt",priority:9}]},audit:{detectFiles:["Cargo.lock"],command:"cargo audit --json",outputFormat:"json"},sast:{nativeRuleSet:"rust",semgrepSupport:"ga"},prompts:{coderConstraints:["Prefer owned types over references where ownership is clear; use lifetimes sparingly","Use Result<T, E> and ? operator for error propagation; never unwrap() in library code","Prefer iterators and combinators over explicit loops","Derive standard traits (Debug, Clone, PartialEq) whenever sensible","Avoid unsafe blocks; document any unsafe usage with SAFETY comments"],reviewerChecklist:["Verify no unwrap() or expect() calls in library/production paths","Check for potential panics in indexing, arithmetic overflow, or slice operations","Confirm error types implement std::error::Error and are propagated correctly","Validate lifetime annotations are minimal and correct","Check unsafe blocks have SAFETY comments explaining invariants"]}});LANGUAGE_REGISTRY.register({id:"go",displayName:"Go",tier:1,extensions:[".go"],treeSitter:{grammarId:"go",wasmFile:"tree-sitter-go.wasm",commentNodes:["comment"]},build:{detectFiles:["go.mod"],commands:[{name:"go build",cmd:"go build ./...",detectFile:"go.mod",priority:10},{name:"go vet",cmd:"go vet ./...",detectFile:"go.mod",priority:9}]},test:{detectFiles:["go.mod"],frameworks:[{name:"go-test",detect:"go.mod",cmd:"go test ./...",priority:10}]},lint:{detectFiles:["go.mod",".golangci.yml",".golangci.yaml"],linters:[{name:"golangci-lint",detect:".golangci.yml",cmd:"golangci-lint run --fix",priority:10},{name:"gofmt",detect:"go.mod",cmd:"gofmt -w .",priority:9}]},audit:{detectFiles:["go.mod"],command:"govulncheck -json ./...",outputFormat:"json"},sast:{nativeRuleSet:"go",semgrepSupport:"ga"},prompts:{coderConstraints:["Always check and return errors; never discard error return values","Use idiomatic Go error wrapping with fmt.Errorf and %w verb","Prefer table-driven tests; use t.Run for subtests","Avoid global mutable state; use dependency injection via interfaces","Use context.Context as first parameter for all I/O-bound functions"],reviewerChecklist:["Verify all error return values are checked (no _ = err pattern)","Check goroutine usage — confirm no goroutine leaks or missing WaitGroups","Validate context propagation through call chains","Confirm exported types/functions have doc comments","Check for data races in concurrent code (verify sync usage)"]}});LANGUAGE_REGISTRY.register({id:"java",displayName:"Java",tier:2,extensions:[".java"],treeSitter:{grammarId:"java",wasmFile:"tree-sitter-java.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],commands:[{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:8}]},test:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],frameworks:[{name:"maven",detect:"pom.xml",cmd:"mvn test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["checkstyle.xml","pom.xml"],linters:[{name:"checkstyle",detect:"checkstyle.xml",cmd:"mvn checkstyle:check",priority:10}]},audit:{detectFiles:["pom.xml","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"java",semgrepSupport:"ga"},prompts:{coderConstraints:["Use checked exceptions for recoverable conditions; unchecked for programming errors","Prefer composition over inheritance; favor interfaces over abstract classes","Use Optional<T> for nullable return values rather than returning null","Follow Java naming conventions: PascalCase classes, camelCase methods/fields","Close resources in try-with-resources blocks; never rely on finalizers"],reviewerChecklist:["Check for unclosed resources — verify try-with-resources or explicit close()","Verify null checks are present for all external/injected dependencies","Confirm thread safety for shared mutable state (synchronized, volatile, atomic)","Validate exception handling — no swallowed exceptions or empty catch blocks","Check for proper equals()/hashCode() overrides on value objects"]}});LANGUAGE_REGISTRY.register({id:"kotlin",displayName:"Kotlin",tier:2,extensions:[".kt",".kts"],treeSitter:{grammarId:"kotlin",wasmFile:"tree-sitter-kotlin.wasm",commentNodes:["line_comment","multiline_comment"]},build:{detectFiles:["build.gradle.kts","build.gradle","pom.xml"],commands:[{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:8}]},test:{detectFiles:["build.gradle.kts","build.gradle"],frameworks:[{name:"gradle",detect:"build.gradle.kts",cmd:"gradle test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["build.gradle.kts","build.gradle"],linters:[{name:"ktlint",detect:"build.gradle.kts",cmd:"ktlint --format",priority:10}]},audit:{detectFiles:["build.gradle.kts","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"beta"},prompts:{coderConstraints:["Prefer val over var; use data classes for value objects","Use Kotlin coroutines for async operations; avoid blocking calls on Dispatchers.Main","Leverage extension functions instead of utility classes","Use sealed classes for exhaustive when expressions","Avoid platform types; always declare explicit nullability in API surfaces"],reviewerChecklist:["Verify no non-null assertions (!!) in production code without justification","Check coroutine scope lifecycle — confirm scopes are cancelled when no longer needed","Validate when expressions are exhaustive (sealed class coverage)","Confirm data class equals/hashCode/copy semantics are appropriate","Check for blocking I/O on the wrong coroutine dispatcher"]}});LANGUAGE_REGISTRY.register({id:"csharp",displayName:"C# / .NET",tier:2,extensions:[".cs",".csx"],treeSitter:{grammarId:"csharp",wasmFile:"tree-sitter-c-sharp.wasm",commentNodes:["comment"]},build:{detectFiles:["*.csproj","*.sln","Directory.Build.props"],commands:[{name:"dotnet build",cmd:"dotnet build -v quiet",detectFile:"*.csproj",priority:10},{name:"dotnet build sln",cmd:"dotnet build -v quiet",detectFile:"*.sln",priority:9}]},test:{detectFiles:["*.csproj","*.sln"],frameworks:[{name:"dotnet-test",detect:"*.csproj",cmd:"dotnet test",priority:10}]},lint:{detectFiles:["*.csproj",".editorconfig"],linters:[{name:"dotnet-format",detect:"*.csproj",cmd:"dotnet format",priority:10}]},audit:{detectFiles:["*.csproj","packages.lock.json"],command:"dotnet list package --vulnerable --include-transitive",outputFormat:"text"},sast:{nativeRuleSet:"csharp",semgrepSupport:"ga"},prompts:{coderConstraints:["Use async/await throughout; avoid .Result or .Wait() which can deadlock","Prefer records for immutable value types; use struct only for small value types","Use nullable reference types (NRT) — enable <Nullable>enable</Nullable>","Dispose IDisposable resources with using statements or declarations","Follow C# naming conventions: PascalCase for public members, _camelCase for private fields"],reviewerChecklist:["Verify no .Result or .Wait() calls that could cause deadlocks","Check all IDisposable are properly disposed (using / IAsyncDisposable)","Confirm nullable reference type annotations are present and correct","Validate LINQ queries do not cause N+1 query patterns in EF contexts","Check for missing ConfigureAwait(false) in library code"]}});LANGUAGE_REGISTRY.register({id:"cpp",displayName:"C / C++",tier:2,extensions:[".c",".h",".cpp",".hpp",".cc",".cxx"],treeSitter:{grammarId:"cpp",wasmFile:"tree-sitter-cpp.wasm",commentNodes:["comment"]},build:{detectFiles:["CMakeLists.txt","Makefile","meson.build"],commands:[{name:"cmake",cmd:"cmake --build build",detectFile:"CMakeLists.txt",priority:10},{name:"make",cmd:"make",detectFile:"Makefile",priority:9},{name:"meson",cmd:"meson compile -C builddir",detectFile:"meson.build",priority:8}]},test:{detectFiles:["CMakeLists.txt"],frameworks:[{name:"ctest",detect:"CMakeLists.txt",cmd:"ctest --test-dir build",priority:10}]},lint:{detectFiles:[".clang-tidy","CMakeLists.txt"],linters:[{name:"cppcheck",detect:"CMakeLists.txt",cmd:"cppcheck --error-exitcode=1 .",priority:10},{name:"clang-tidy",detect:".clang-tidy",cmd:"clang-tidy -p build",priority:9}]},audit:{detectFiles:["CMakeLists.txt","vcpkg.json","conanfile.txt"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"cpp",semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer RAII and smart pointers (unique_ptr, shared_ptr) over raw pointers","Use const-correctness throughout; mark all non-mutating methods const","Avoid undefined behaviour: no out-of-bounds access, no use-after-free","Initialize all variables; prefer in-class initializers for member variables","Use std::array or std::vector instead of C-style arrays"],reviewerChecklist:["Verify no raw owning pointers; confirm smart pointer ownership semantics","Check for memory leaks — every new has a corresponding delete or smart pointer","Validate bounds checking on all array/buffer accesses","Confirm no undefined behavior patterns (signed overflow, strict aliasing violations)","Check thread safety for shared data (mutex, atomic, lock-free patterns)"]}});LANGUAGE_REGISTRY.register({id:"swift",displayName:"Swift",tier:2,extensions:[".swift"],treeSitter:{grammarId:"swift",wasmFile:"tree-sitter-swift.wasm",commentNodes:["comment","multiline_comment"]},build:{detectFiles:["Package.swift","*.xcodeproj","*.xcworkspace"],commands:[{name:"swift build",cmd:"swift build",detectFile:"Package.swift",priority:10},{name:"xcodebuild",cmd:"xcodebuild build -quiet",detectFile:"*.xcodeproj",priority:9}]},test:{detectFiles:["Package.swift","*.xcodeproj"],frameworks:[{name:"swift-test",detect:"Package.swift",cmd:"swift test",priority:10},{name:"xcodebuild-test",detect:"*.xcodeproj",cmd:"xcodebuild test -quiet",priority:9}]},lint:{detectFiles:[".swiftlint.yml","Package.swift"],linters:[{name:"swiftlint",detect:".swiftlint.yml",cmd:"swiftlint --fix",priority:10}]},audit:{detectFiles:["Package.resolved","Package.swift"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer value types (structs, enums) over classes; use classes only for reference semantics","Use Swift concurrency (async/await, actors) over GCD for new code","Avoid force unwrap (!) and force cast (as!); use guard let or if let","Use Swift Package Manager for dependencies where possible","Mark types and methods as final when subclassing is not intended"],reviewerChecklist:["Verify no force unwraps (!) or force casts (as!) in production code","Check for retain cycles in closures — confirm [weak self] where needed","Validate Swift concurrency usage — no data races across actor boundaries","Confirm proper error handling with do-try-catch or Result<T,E>","Check value vs reference type choice is appropriate for the use case"]}});LANGUAGE_REGISTRY.register({id:"dart",displayName:"Dart / Flutter",tier:3,extensions:[".dart"],treeSitter:{grammarId:"dart",wasmFile:"tree-sitter-dart.wasm",commentNodes:["comment","documentation_comment"]},build:{detectFiles:["pubspec.yaml"],commands:[{name:"flutter build",cmd:"flutter build apk",detectFile:"pubspec.yaml",priority:10},{name:"dart compile",cmd:"dart compile exe .",detectFile:"pubspec.yaml",priority:9}]},test:{detectFiles:["pubspec.yaml"],frameworks:[{name:"flutter test",detect:"pubspec.yaml",cmd:"flutter test",priority:10},{name:"dart test",detect:"pubspec.yaml",cmd:"dart test",priority:9}]},lint:{detectFiles:["analysis_options.yaml","pubspec.yaml"],linters:[{name:"dart analyze",detect:"pubspec.yaml",cmd:"dart analyze",priority:10}]},audit:{detectFiles:["pubspec.yaml","pubspec.lock"],command:"dart pub outdated --json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"none"},prompts:{coderConstraints:["Use null safety features — prefer late, required, and ? annotations over dynamic","Follow Dart effective style: lowerCamelCase for variables, UpperCamelCase for types","Prefer const constructors where possible for performance","Use async/await over raw Future callbacks","Separate business logic from UI widgets; use BLoC or Provider patterns"],reviewerChecklist:["Verify null safety annotations are correct (no unnecessary ?)","Check that const constructors are used where the widget tree is static","Confirm async operations handle error states (catchError or try-catch)","Validate no direct UI state mutation outside setState or stream","Check for platform-specific code isolation (dart:io vs dart:html)"]}});LANGUAGE_REGISTRY.register({id:"ruby",displayName:"Ruby",tier:3,extensions:[".rb",".rake",".gemspec"],treeSitter:{grammarId:"ruby",wasmFile:"tree-sitter-ruby.wasm",commentNodes:["comment"]},build:{detectFiles:["Gemfile","Rakefile"],commands:[{name:"bundle install",cmd:"bundle install",detectFile:"Gemfile",priority:10},{name:"rake",cmd:"rake",detectFile:"Rakefile",priority:9}]},test:{detectFiles:["Gemfile",".rspec","spec/spec_helper.rb"],frameworks:[{name:"rspec",detect:".rspec",cmd:"bundle exec rspec",priority:10},{name:"minitest",detect:"Rakefile",cmd:"bundle exec rake test",priority:9}]},lint:{detectFiles:[".rubocop.yml","Gemfile"],linters:[{name:"rubocop",detect:".rubocop.yml",cmd:"rubocop --autocorrect",priority:10}]},audit:{detectFiles:["Gemfile.lock"],command:"bundle-audit check --format json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Follow Ruby community style (Rubocop defaults); 120-char line limit","Prefer symbols over strings for hash keys","Use frozen_string_literal: true magic comment in all files","Avoid monkey-patching core classes; prefer refinements","Use keyword arguments for methods with more than 2 parameters"],reviewerChecklist:["Verify frozen_string_literal comment is present in new files","Check for N+1 query patterns in ActiveRecord code","Validate no eval or send with user-controlled input (code injection risk)","Confirm exception handling is specific — no bare rescue","Check for missing validations on ActiveRecord models"]}});LANGUAGE_REGISTRY.register({id:"php",displayName:"PHP",tier:3,extensions:[".php",".phtml",".blade.php"],treeSitter:{grammarId:"php",wasmFile:"tree-sitter-php.wasm",commentNodes:["comment"]},build:{detectFiles:["composer.json"],commands:[{name:"Composer Install",cmd:"composer install --no-interaction --prefer-dist",detectFile:"composer.json",priority:10}]},test:{detectFiles:["Pest.php","phpunit.xml","phpunit.xml.dist"],frameworks:[{name:"Pest",detect:"Pest.php",cmd:"vendor/bin/pest",priority:10},{name:"PHPUnit",detect:"phpunit.xml",cmd:"vendor/bin/phpunit",priority:8},{name:"PHPUnit",detect:"phpunit.xml.dist",cmd:"vendor/bin/phpunit",priority:7}]},lint:{detectFiles:["phpstan.neon","phpstan.neon.dist","pint.json",".php-cs-fixer.php","phpcs.xml"],linters:[{name:"PHPStan",detect:"phpstan.neon",cmd:"vendor/bin/phpstan analyse",priority:10},{name:"PHPStan",detect:"phpstan.neon.dist",cmd:"vendor/bin/phpstan analyse",priority:9},{name:"Pint",detect:"pint.json",cmd:"vendor/bin/pint --test",priority:8},{name:"PHP-CS-Fixer",detect:".php-cs-fixer.php",cmd:"vendor/bin/php-cs-fixer fix --dry-run --diff",priority:7}]},audit:{detectFiles:["composer.lock"],command:"composer audit --locked --format=json",outputFormat:"json"},sast:{nativeRuleSet:"php",semgrepSupport:"ga"},prompts:{coderConstraints:["Follow PSR-12 coding standards","Use strict types declaration: declare(strict_types=1)","Prefer type hints and return type declarations on all functions","Use dependency injection over static methods and singletons","Prefer named constructors and value objects over primitive obsession"],reviewerChecklist:["Verify no user input reaches SQL queries without parameterised binding","Check for XSS — all output must be escaped with htmlspecialchars()","Confirm no eval(), exec(), or shell_exec() with user-controlled input","Validate proper error handling — no bare catch blocks that swallow errors","Challenge any PHP/Laravel documentation or README claim that exceeds what is implemented and CI-verified in v6.49.0 (composer build, PHPUnit/Pest/artisan test, Pint/PHP-CS-Fixer lint, PHPStan static analysis, composer audit, Laravel detection, Blade scanning, 3 Laravel SAST rules). If a PR adds docs claiming broader support, verify it is backed by tests."],testConstraints:["Prefer feature tests for HTTP, middleware, and authentication flows — use Laravel RefreshDatabase or DatabaseTransactions traits","Use unit tests for isolated business logic classes that do not require the full Laravel application container","Pest and PHPUnit coexist in many Laravel repos — php artisan test runs both; do not assume PHPUnit-only","Use .env.testing for test environment configuration; run php artisan config:clear when environment changes affect tests","For database tests, prefer RefreshDatabase over manual setUp/tearDown to avoid state leakage between tests","Run php artisan config:clear and php artisan cache:clear before running tests if environment variables changed","Use separate .env.testing file for test-specific configuration; never rely on .env for CI test runs","For parallel testing with php artisan test --parallel, ensure database connections use separate databases per worker (APP_ENV=testing + test database suffix pattern)"]}})});import{access as access4,readdir as readdir12}from"node:fs/promises";import{extname as extname9,join as join127}from"node:path";function getProfileForFile(filePath){let ext=extname9(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries2;try{dirEntries=await readdir12(dir,{withFileTypes:!0}),entries2=dirEntries.map((e)=>e.name)}catch{return}for(let profile of LANGUAGE_REGISTRY.getAll())for(let detectFile of profile.build.detectFiles){if(detectFile.includes("*")||detectFile.includes("?")){let regex=new RegExp(`^${detectFile.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);if(dirEntries.some((e)=>!e.isDirectory()&&regex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join127(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries2){let ext=extname9(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir12(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join127(projectDir,entry.name))}catch{}let result=[];for(let id of detected){let profile=LANGUAGE_REGISTRY.getById(id);if(profile)result.push(profile)}return result.sort((a,b)=>a.tier-b.tier),result}var init_detector=__esm(()=>{init_profiles()});import*as fs92 from"node:fs";import*as path170 from"node:path";function tokenizeCommand(command){let out=[],buf="",quote=null;for(let ch of command.trim()){if(quote){if(ch===quote)quote=null;else buf+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch===" "||ch==="\t"){if(buf.length>0)out.push(buf),buf="";continue}buf+=ch}if(buf.length>0)out.push(buf);return out}function findCommandSuffixStart(command){let quote=null,sawTokenChar=!1;for(let i=0;i<command.length;i++){let ch=command[i];if(quote){if(ch===quote)quote=null;else sawTokenChar=!0;continue}if(ch==='"'||ch==="'"){quote=ch,sawTokenChar=!0;continue}if((ch===" "||ch==="\t")&&sawTokenChar)return i;if(ch!==" "&&ch!=="\t")sawTokenChar=!0}return command.length}function resolveLocalCandidate(binary,workingDir,platform=process.platform,isAvailable){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`,absolute=path170.join(workingDir,"node_modules",".bin",executable);if(!fs92.existsSync(absolute))continue;if(candidate.requiresNode&&isAvailable&&!isAvailable("node"))continue;let relative37=platform==="win32"?path170.win32.join("node_modules",".bin",executable):path170.posix.join("node_modules",".bin",executable);return{absolute,relative:relative37,requiresNode:candidate.requiresNode}}return null}function hasAnyLocalCandidate(binary,workingDir,platform=process.platform){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`;if(fs92.existsSync(path170.join(workingDir,"node_modules",".bin",executable)))return!0}return!1}function resolveLocalCommand(command,workingDir,isAvailable,platform=process.platform){let tokens2=tokenizeCommand(command);if(tokens2.length===0)return null;let[binary,...args2]=tokens2;if(["npx","bunx","pnpx"].includes(binary))return null;if(binary.includes("/")||binary.includes("\\"))return null;let trimmed=command.trim(),local=resolveLocalCandidate(binary,workingDir,platform,isAvailable);if(local){let shellPath=platform==="win32"?local.relative:`./${local.relative}`;return{argv:[local.absolute,...args2],shellCommand:`${shellPath}${trimmed.slice(findCommandSuffixStart(trimmed))}`}}if(hasAnyLocalCandidate(binary,workingDir,platform))return null;return isAvailable(binary)?{argv:tokens2,shellCommand:command}:null}function resolveLocalNodeTool(tool3,args2,workingDir,platform=process.platform,isAvailable){let local=resolveLocalCandidate(tool3,workingDir,platform,platform==="win32"?isAvailable:void 0);if(local)return[local.absolute,...args2];if(hasAnyLocalCandidate(tool3,workingDir,platform))return null;return isAvailable?.(tool3)?[tool3,...args2]:null}var WINDOWS_LOCAL_SHIM_CANDIDATES;var init_command_resolution=__esm(()=>{WINDOWS_LOCAL_SHIM_CANDIDATES=[{suffix:".cmd",requiresNode:!0},{suffix:".exe",requiresNode:!1},{suffix:".bat",requiresNode:!0},{suffix:".ps1",requiresNode:!0},{suffix:"",requiresNode:!0}]});import*as fs93 from"node:fs";import*as path171 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32";try{let searchName=isWindows?command:command,available=_internals138.spawnSyncImpl(isWindows?["where",searchName]:["which",searchName],{cwd:process.cwd(),stdin:"ignore",stdout:"ignore",stderr:"ignore",timeout:IS_COMMAND_AVAILABLE_TIMEOUT_MS}).success;return toolchainCache.set(command,available),available}catch{return toolchainCache.set(command,!1),!1}}function checkToolchain(commands){return commands.some((cmd)=>_internals138.isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs93.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path171.join(dir,matches[0])}catch{}}else{let filePath=path171.join(workingDir,pattern);if(fs93.existsSync(filePath))return filePath}return null}function sanitizeEvidenceText(raw,maxChars){let withoutControls="";for(let char of raw){let code=char.charCodeAt(0);withoutControls+=code<32||code===127?" ":char}let normalized=withoutControls.replace(/\s+/g," ").trim();if(!normalized)return"(empty)";if(normalized.length<=maxChars)return normalized;if(maxChars<=3)return normalized.slice(0,maxChars);return`${normalized.slice(0,maxChars-3)}...`}function sanitizeRequiredCommand(command){let sanitized=sanitizeEvidenceText(command,40);return sanitized==="(empty)"?null:sanitized}function getBinaryFromCommand(command){return command.trim().split(/\s+/)[0]??""}function getProfileRequiredCommands(commands){let uniqueCommands=new Set;for(let command of commands){let binary=sanitizeRequiredCommand(getBinaryFromCommand(command.cmd));if(binary)uniqueCommands.add(binary)}return Array.from(uniqueCommands)}function getNoMatchingBuildFilesReason(profileId,commands){let detectFiles=Array.from(new Set(commands.map((command)=>command.detectFile?.trim()).filter((detectFile)=>Boolean(detectFile))));if(detectFiles.length===0)return`No matching build files for profile ${profileId}`;return`No matching build files for profile ${profileId}: expected ${detectFiles.join(" or ")}`}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path171.join(workingDir,"package.json");if(!fs93.existsSync(packageJsonPath))return{commands:[],hasScripts:!1};try{let content=fs93.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return{commands:[],hasScripts:!1};let scriptNames=scripts.filter((name)=>typeof pkg.scripts[name]==="string"&&pkg.scripts[name].trim());if(scriptNames.length===0)return{commands:[],hasScripts:!1};let rawPackageManager=typeof pkg.packageManager==="string"?pkg.packageManager.trim():void 0,declared=rawPackageManager?.split("@")[0]?.trim(),supported=[...SUPPORTED_NODE_PACKAGE_MANAGERS],sanitizedDeclared=declared?sanitizeRequiredCommand(declared):null,candidates=declared?[declared]:supported;if(rawPackageManager!==void 0&&(!declared||!supported.includes(declared)))return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:sanitizedDeclared?[sanitizedDeclared]:[],reason:`Unsupported packageManager: ${sanitizeEvidenceText(rawPackageManager,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS)}`}};let manager=candidates.find((candidate)=>_internals138.isCommandAvailable(candidate));if(!manager)return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:candidates,reason:`Package manager not available: ${candidates.join(" or ")}`}};return{hasScripts:!0,commands:scriptNames.map((scriptName)=>({command:`${manager} run ${scriptName}`,priority:100}))}}catch{return{commands:[],hasScripts:!1}}}function filterByScope(workingDir,scope,changedFiles){if(scope==="all")return findAllBuildFiles(workingDir);if(!changedFiles||changedFiles.length===0)return[];return changedFiles}function findAllBuildFiles(workingDir){let allBuildFiles=new Set;for(let ecosystem of ECOSYSTEMS)for(let pattern of ecosystem.buildFiles)if(pattern.includes("*")){let regex=simpleGlobToRegex(pattern);findFilesRecursive(workingDir,regex,allBuildFiles)}else{let filePath=path171.join(workingDir,pattern);if(fs93.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries2=fs93.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path171.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&&regex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await _internals138.detectProjectLanguagesImpl(workingDir);for(let profile of detectedProfiles){let fullProfile=_internals138.getLanguageProfileImpl(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>b.priority-a.priority),applicableCommands=sortedCommands.filter((cmd)=>{if(!cmd.detectFile)return!0;let detectFilePath=path171.join(workingDir,cmd.detectFile);return fs93.existsSync(detectFilePath)});if(applicableCommands.length===0){skipped.push({ecosystem:fullProfile.id,reason:getNoMatchingBuildFilesReason(fullProfile.id,sortedCommands)});continue}let foundCommand=!1;for(let cmd of applicableCommands){let resolved=resolveLocalCommand(cmd.cmd,workingDir,_internals138.isCommandAvailable);if(resolved){commands.push({ecosystem:fullProfile.id,command:resolved.shellCommand,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let requiredCommands=getProfileRequiredCommands(applicableCommands),triedBinaries=requiredCommands.join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,code:"environment_unavailable",required_commands:requiredCommands,reason}),warn(`[build-discovery] profile ${fullProfile.id}: no binary available, skipping`)}}return{commands,skipped}}async function discoverBuildCommands(workingDir,options){let scope=options?.scope??"all",changedFiles=options?.changedFiles??[],_filesToCheck=filterByScope(workingDir,scope,changedFiles),profileResult=await _internals138.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,repoDefinedScriptsByEcosystem=new Map,repoScriptSkips=[],repoDeclaredEcosystems=new Set;for(let ecosystem of ECOSYSTEMS){if(!ecosystem.repoDefinedScripts)continue;let repoResult=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoResult.commands.length>0)repoDefinedScriptsByEcosystem.set(ecosystem.ecosystem,repoResult.commands);if(repoResult.hasScripts)repoDeclaredEcosystems.add(ecosystem.ecosystem);if(repoResult.skip)repoScriptSkips.push(repoResult.skip)}let filteredProfileCommands=profileCommands.filter((cmd)=>{return(PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[]).every((name)=>!repoDeclaredEcosystems.has(name))}),coveredEcosystems=new Set;for(let cmd of filteredProfileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...filteredProfileCommands],skipped=[...profileSkipped,...repoScriptSkips];for(let ecosystem of ECOSYSTEMS){if(!findBuildFiles(workingDir,ecosystem.buildFiles))continue;let repoScripts=repoDefinedScriptsByEcosystem.get(ecosystem.ecosystem);if(repoScripts&&repoScripts.length>0){for(let script of repoScripts)commands.push({ecosystem:ecosystem.ecosystem,command:script.command,cwd:workingDir,priority:script.priority});continue}if(repoDeclaredEcosystems.has(ecosystem.ecosystem))continue;if(coveredEcosystems.has(ecosystem.ecosystem)){skipped.push({ecosystem:ecosystem.ecosystem,reason:"Covered by profile detection"});continue}if(!checkToolchain(ecosystem.toolchainCommands)){skipped.push({ecosystem:ecosystem.ecosystem,code:"environment_unavailable",required_commands:ecosystem.toolchainCommands,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}let availableCommands=ecosystem.commands;for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>b.priority-a.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var SUPPORTED_NODE_PACKAGE_MANAGERS,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS=120,ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals138,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();init_command_resolution();SUPPORTED_NODE_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn"],ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:[...SUPPORTED_NODE_PACKAGE_MANAGERS],commands:[{command:"npm run build",priority:30},{command:"npm run typecheck",priority:20},{command:"npm run check",priority:10}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:20},{command:"cargo check",priority:10}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:10}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m build",priority:20},{command:"python -m py_compile",priority:10}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:10}]},{ecosystem:"java-gradle",buildFiles:["build.gradle","build.gradle.kts","gradle.properties"],toolchainCommands:["gradle","gradlew"],commands:[{command:process.platform==="win32"?"gradlew.bat build":"./gradlew build",priority:20},{command:"gradle build",priority:10}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:10}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:10}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart compile",priority:20},{command:"dart analyze",priority:10}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:20},{command:"cmake -B build && cmake --build build",priority:10}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:10}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["node"],javascript:["node"],python:["python"],rust:["rust"],go:["go"],java:["java-maven","java-gradle"],kotlin:["java-gradle"],csharp:["dotnet"],cpp:["cpp"],swift:["swift"],dart:["dart"],ruby:[],php:["php-composer"]},toolchainCache=new Map;_internals138={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,detectProjectLanguagesImpl:detectProjectLanguages,getLanguageProfileImpl:LANGUAGE_REGISTRY.get.bind(LANGUAGE_REGISTRY),spawnSyncImpl:bunSpawnSync};build_discovery=tool({description:"Discover build commands for various ecosystems in a project directory",args:{workingDir:tool.schema.string().describe("Directory to scan for build commands (defaults to current directory)"),scope:tool.schema.string().optional().describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changedFiles:tool.schema.array(tool.schema.string()).optional().describe('List of changed files when scope is "changed"')},async execute(args2,_context){let result=await discoverBuildCommands(args2.workingDir,{scope:args2.scope??"all",changedFiles:args2.changedFiles??[]});return JSON.stringify(result,null,2)}})});var init_tool_names=__esm(()=>{init_tool_metadata()});var exports_tool_doctor={};__export(exports_tool_doctor,{runToolDoctor:()=>runToolDoctor,getBinaryReadinessAdvisory:()=>getBinaryReadinessAdvisory,checkAgentToolMapAlignment:()=>checkAgentToolMapAlignment});function getRegisteredToolKeys(){return new Set(TOOL_NAME_SET)}function checkAgentToolMapAlignment(registeredKeys){let findings=[];for(let[agentName,tools]of Object.entries(AGENT_TOOL_MAP))for(let toolName of tools)if(!registeredKeys.has(toolName))findings.push({id:`agent-tool-map-mismatch-${agentName}-${toolName}`,title:"AGENT_TOOL_MAP alignment gap",description:`Tool "${toolName}" is assigned to agent "${agentName}" in AGENT_TOOL_MAP but is not a registered tool name. The agent will not be able to use this tool.`,severity:"error",path:`AGENT_TOOL_MAP.${agentName}`,currentValue:toolName,autoFixable:!1});return findings}function checkBinaryReadiness(){let findings=[];for(let{binary,language}of BINARY_CHECKLIST)if(!isCommandAvailable(binary))findings.push({id:`missing-binary-${binary}`,title:"Class 3 tool binary not found",description:`Binary "${binary}" is not available on PATH. ${language} linting will not be available. Install ${binary} to enable ${language} language support.`,severity:"warn",path:`toolchain.${binary}`,currentValue:void 0,autoFixable:!1});return findings}function getBinaryReadinessAdvisory(){let findings=checkBinaryReadiness();if(findings.length===0)return null;return["[PRE-FLIGHT ADVISORY] The following Class 3 tool binaries were not found on PATH at session start.","These tools will soft-skip at invocation. Plan tasks accordingly.",...findings.map((f)=>`- MISSING BINARY: ${f.currentValue??f.path?.split(".")[1]??"unknown"} — ${f.description}`)].join(`
2465
2465
  `)}function runToolDoctor(_directory2,_pluginRoot){let findings=[],registeredKeys=getRegisteredToolKeys();for(let toolName of TOOL_NAMES)if(!registeredKeys.has(toolName))findings.push({id:`missing-tool-registration-${toolName}`,title:"Missing tool registration",description:`Tool "${toolName}" is defined in TOOL_NAMES but is not present in the plugin tool object derived from TOOL_MANIFEST. This means the tool will not be available at runtime.`,severity:"error",path:`tool.${toolName}`,currentValue:void 0,autoFixable:!1});findings.push(...checkAgentToolMapAlignment(registeredKeys)),findings.push(...checkBinaryReadiness());let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length};return{findings,summary,hasAutoFixableIssues:!1,timestamp:Date.now(),configSource:"src/tools/manifest.ts"}}var BINARY_CHECKLIST;var init_tool_doctor=__esm(()=>{init_discovery();init_constants();init_tool_names();BINARY_CHECKLIST=[{binary:"ruff",language:"Python"},{binary:"cargo",language:"Rust (via clippy)"},{binary:"golangci-lint",language:"Go"},{binary:"mvn",language:"Java (Maven)"},{binary:"gradle",language:"Java (Gradle)"},{binary:"dotnet",language:".NET"},{binary:"swift",language:"Swift"},{binary:"swiftlint",language:"Swift (linting)"},{binary:"dart",language:"Dart"},{binary:"flutter",language:"Flutter/Dart"},{binary:"biome",language:"JS/TS (already in project)"},{binary:"eslint",language:"JS/TS"}]});function formatToolDoctorMarkdown(result){let lines=["## Tool Doctor Report","",`**Tool Registry**: ${result.configSource}`,"","### Summary",`- **Info**: ${result.summary.info}`,`- **Warnings**: ${result.summary.warn}`,`- **Errors**: ${result.summary.error}`,""];if(result.findings.length===0)lines.push("No issues found. All tools are properly registered!");else{lines.push("### Findings","");let errors5=result.findings.filter((f)=>f.severity==="error"),warnings=result.findings.filter((f)=>f.severity==="warn"),infos=result.findings.filter((f)=>f.severity==="info");for(let finding of[...errors5,...warnings,...infos]){let icon=finding.severity==="error"?"❌":finding.severity==="warn"?"⚠️":"ℹ️";if(lines.push(`${icon} **${finding.severity.toUpperCase()}**: ${finding.description}`),finding.autoFixable)lines.push(" - \uD83D\uDD27 Auto-fixable");lines.push("")}if(result.summary.error>0)lines.push("---",""),lines.push(`**BLOCKING**: ${result.summary.error} error-severity finding(s) must be resolved before release. `+"AGENT_TOOL_MAP alignment errors mean an agent's system prompt instructs the model to call a tool that opencode has not registered — the agent's workflow will silently fail at runtime."),lines.push("")}return lines.join(`
2466
2466
  `)}function stripControlChars(s){return s.replace(/[\x00-\x1f\x7f]+/g," ")}function sanitizeForMarkdownCodeSpan(s){return stripControlChars(s).replace(/`/g,"'")}function sanitizeForMarkdownText(s){return stripControlChars(s).replace(/([\\`*_[\]|])/g,"\\$1")}function formatDoctorMarkdown(result){let lines=["## Config Doctor Report","",`**Config Source**: ${result.configSource}`,"","### Summary",`- **Info**: ${result.summary.info}`,`- **Warnings**: ${result.summary.warn}`,`- **Errors**: ${result.summary.error}`,""];if(result.findings.length===0)lines.push("No issues found. Your configuration looks good!");else{lines.push("### Findings","");let errors5=result.findings.filter((f)=>f.severity==="error"),warnings=result.findings.filter((f)=>f.severity==="warn"),infos=result.findings.filter((f)=>f.severity==="info");for(let finding of[...errors5,...warnings,...infos]){let icon=finding.severity==="error"?"❌":finding.severity==="warn"?"⚠️":"ℹ️";if(lines.push(`${icon} **${finding.severity.toUpperCase()}**: ${finding.description}`),finding.autoFixable)lines.push(" - \uD83D\uDD27 Auto-fixable");lines.push("")}}if(result.availableMigrations&&result.availableMigrations.length>0){lines.push("---",""),lines.push("### Migrations Available","");let firstMigration=result.availableMigrations[0],userConfigVersion=firstMigration.currentFormatVersion,earliestDeprecatedIn=firstMigration.deprecatedIn;lines.push(`ℹ️ Your config is at version ${userConfigVersion}. Fields with cleaner replacements (introduced in config version ${earliestDeprecatedIn}) can be migrated:`);for(let migration of result.availableMigrations)lines.push(` - \`${migration.field}\` → \`${migration.replacement}\` (available since config version ${migration.sinceVersion}, superseded in config version ${migration.deprecatedIn})`);lines.push(""),lines.push("Run `/swarm config doctor --fix` to apply available migrations.")}if(result.hasAutoFixableIssues)lines.push("---"),lines.push(""),lines.push("Tip: Some issues can be auto-fixed. Run `/swarm config doctor --fix` to apply fixes.");return lines.join(`
2467
2467
  `)}async function handleDoctorCommand(directory,args2){let enableAutoFix=args2.includes("--fix")||args2.includes("-f"),meta3=loadPluginConfigWithMeta(directory),config3=meta3.config,result=runConfigDoctor(config3,directory),output;if(enableAutoFix&&result.hasAutoFixableIssues){let{runConfigDoctorWithFixes:runConfigDoctorWithFixes2}=await Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)),fixResult=await runConfigDoctorWithFixes2(directory,config3,!0,{applyLossy:!0});output=formatDoctorMarkdown(fixResult.result)}else{let lastRun=readDoctorArtifact(directory),markdown=formatDoctorMarkdown(result);if(lastRun)markdown=`Last run: ${lastRun.timestamp}, ${lastRun.findingsCount} findings (${lastRun.autoFixableCount} auto-fixable)
@@ -7278,7 +7278,7 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
7278
7278
  `)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath2=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath2)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath2,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs168.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals242.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals242.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
7279
7279
  `)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals242={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_zod();init_authorization();init_create_tool();var AuthorizePrReviewReentryArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),role:exports_external.enum(["reviewer","test_engineer"])}).strict();async function executeAuthorizePrReviewReentry(args2,directory,context={}){let parsed=AuthorizePrReviewReentryArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR-review re-entry authorization: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR-review re-entry authorization requires an active sessionID"});try{let record3=await issuePrReviewReentryAuthorization(directory,context.sessionID,{...parsed.data.run_id?{runId:parsed.data.run_id}:{},prHeadSha:parsed.data.pr_head_sha,role:parsed.data.role});return JSON.stringify({success:!0,authorization_id:record3.authorizationId,role:record3.role,pr_head_sha:record3.prHeadSha,run_id:record3.runId,generation:record3.generation,revision_digest:record3.revisionDigest,expires_at:record3.expiresAt,instructions:`Immediately dispatch exactly one direct subagent_type Task call with role "${record3.role}" for this PR-review re-entry; if a plan or task workflow state exists, include the exact task_id (or task identifier in the prompt). A taskless dispatch is allowed only for a plan-free standalone review and does not advance plan-task gate state. The PR workflow controller admits and reserves this authorization once, and the delegation gate verifies the same call-bound reservation; a later unrelated gate rejection still burns it. Any other dispatch falls back to normal gating.`},null,2)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var authorize_pr_review_reentry=createSwarmTool({description:"Issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383). The authorization is reserved atomically by the PR workflow controller for the very next direct subagent_type Task dispatch of the declared role (admitting that one dispatch past the PR_REVIEW read-only restriction), then verified for that same call by the delegation gate, which bypasses ONLY the generic Stage-A task-workflow requirement; all other delegation gates remain authoritative. If a plan or task workflow state exists, the dispatch must include an exact task_id or task identifier; taskless dispatch is standalone-only and never guesses from plan/session state. Bound to the exact session, workflow, run, PR head SHA, worktree revision digest, role, and gate generation; replay, cross-session use, wrong role, expiry (10 minutes), or workflow progress since issuance fails closed. A dispatch the delegation gate later rejects for another reason still burns the authorization. Requires an active head-bound PR_REVIEW gate. Issue immediately before the Task dispatch; unconsumed same-role authorizations at the same generation are refused.",args:{run_id:AuthorizePrReviewReentryArgsSchema.shape.run_id,pr_head_sha:AuthorizePrReviewReentryArgsSchema.shape.pr_head_sha,role:AuthorizePrReviewReentryArgsSchema.shape.role},execute:executeAuthorizePrReviewReentry});init_dist();init_create_tool();init_symbols();init_path_security();import*as fs169 from"node:fs";import*as path295 from"node:path";var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path295.resolve(workspace,filePath);if(!fs169.existsSync(resolvedPath))return!0;let realWorkspace=fs169.realpathSync(workspace),realResolvedPath=fs169.realpathSync(resolvedPath),relativePath2=path295.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path295.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path295.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path295.join(cwd,file3);if(!fs169.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs169.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs169.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_config();init_manager2();init_bun_compat();init_logger();init_create_tool();var _internals243={loadGateOverrides},DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100,NO_BUILD_FILES_DISCOVERED_REASON="No build commands discovered (no supported build files found)";function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
7280
7280
  `);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
7281
- `);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason,environmentUnavailable=discoveryResult.skipped.filter((skip)=>skip.code==="environment_unavailable");if(runs.length===0)if(verdict=environmentUnavailable.length>0?"skip":"info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason=NO_BUILD_FILES_DISCOVERED_REASON;else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason,environment_unavailable:environmentUnavailable.length>0?environmentUnavailable:void 0}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){if(_internals243.loadGateOverrides(directory)?.build_check?.enabled===!1)return JSON.stringify({verdict:"skip",runs:[],summary:{files_scanned:0,runs_count:0,failed_count:0,skipped_reason:"build_check disabled by configuration"}},null,2);let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason,environment_unavailable:result.summary.environment_unavailable};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs170 from"node:fs";import*as path296 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path296.resolve(workspaceRoot),swarmPath3=path296.join(normalizedWorkspace,".swarm","evidence");return path296.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs170.existsSync(evidencePath))return null;let content;try{content=fs170.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path296.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status2=requiredGates.length>0&&missingGates.length===0?"all_passed":"incomplete",message;if(status2==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else if(requiredGates.length===0)message=`Task "${taskIdInput}" is incomplete. No required gates are configured for this task generation.`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status2="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status2==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status:status2,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_loader();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80),report_verdict:exports_external.enum(["APPROVE","REQUEST_CHANGES","INCOMPLETE"]).optional()}).strict().superRefine((value,ctx)=>{if(value.mode==="PR_REVIEW"&&value.report_verdict===void 0)ctx.addIssue({code:"custom",path:["report_verdict"],message:"is required for PR_REVIEW completion (issue #2383 terminal report)"})});async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={},laneLiveness;try{let config3=loadPluginConfig(directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}try{let settlement=await _internals244.settlePresumedStalePrWorkflowLanes(directory,context.sessionID,laneLiveness);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason;if(settlement.horizonConflictNote)staleDisclosure.horizon_conflict=settlement.horizonConflictNote}catch{}let amendmentDisclosure={};try{let gateState=await _internals244.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let terminalReport;if(parsed.data.mode==="PR_REVIEW"){let coverage=null;try{coverage=await _internals244.readPrReviewTerminalCoverageForReport(directory,context.sessionID)}catch{}if(coverage){let findingPolicy;try{findingPolicy=await _internals244.readPrReviewFinalFindingPolicyForReport(directory,context.sessionID)}catch{}terminalReport={kind:coverage.kind,covered_dimensions:coverage.coveredDimensions,unresolved_dimensions:coverage.unresolvedDimensions,live_dimensions:coverage.liveDimensions,allowed_verdicts:findingPolicy?.permittedVerdicts??coverage.allowedVerdicts,...findingPolicy?{finding_policy_version:findingPolicy.policyVersion,blocking_finding_ids:findingPolicy.blockingFindingIds}:{},report_verdict:parsed.data.report_verdict}}}let status2=await _internals244.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha,parsed.data.mode==="PR_REVIEW"?{reportVerdict:parsed.data.report_verdict,...laneLiveness?{laneLiveness}:{}}:laneLiveness?{laneLiveness}:void 0),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status2==="completed")try{checkoutRestoreReceipts=await _internals244.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status:status2,ready_to_publish:status2==="ready-to-publish",verified_no_change:status2==="verified-no-change",gate_cleared:status2==="completed"||status2==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...terminalReport?{terminal_report:terminalReport}:{},...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha,report_verdict:CompletePrWorkflowArgsSchema.shape.report_verdict},execute:executeCompletePrWorkflow}),_internals244={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,readPrReviewTerminalCoverageForReport,readPrReviewFinalFindingPolicyForReport,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs171 from"node:fs";import*as path297 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs171.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath=filePath.replace(/\\/g,"/"),resolvedPath=path297.resolve(directory,normalizedPath),projectRoot=path297.resolve(directory),relative76=path297.relative(projectRoot,resolvedPath);if(!(relative76===""||!relative76.startsWith("..")&&!path297.isAbsolute(relative76))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs171.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path297.join(directory,".swarm","evidence",`${phase}`),evidencePath=path297.join(evidenceDir,"completion-verify.json");fs171.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs171.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import*as fs172 from"node:fs";import*as path298 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals245={bunSpawn,resolveGitExecutable};async function getGitChurn(days,directory){let churnMap=new Map,proc=_internals245.bunSpawn([_internals245.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath=line.replace(/\\/g,"/");if(!normalizedPath||normalizedPath.trim()==="")continue;if(normalizedPath.includes("node_modules")||normalizedPath.includes("/.git/")||normalizedPath.includes("/dist/")||normalizedPath.includes("/build/")||normalizedPath.includes("__tests__"))continue;if(normalizedPath.includes(".test.")||normalizedPath.includes(".spec."))continue;churnMap.set(normalizedPath,(churnMap.get(normalizedPath)||0)+1)}return churnMap}function getComplexityForFile2(filePath){try{if(fs172.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs172.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path298.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs172.existsSync(fullPath))fullPath=path298.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store4();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store4();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals246.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected2=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected2+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected:rejected2,failed,...error93?{error:error93}:{}}}var _internals246={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_state2();init_create_tool();var _internals247={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity,directory){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimitResolution=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit,directory),modelLimit=modelLimitResolution.limit,usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,modelLimitSource:modelLimitResolution.source,modelLimitResolution:modelLimitResolution.resolution,fallbackActive:modelLimitResolution.source==="provider_cap"||modelLimitResolution.source==="native"||modelLimitResolution.source==="fallback",usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Report current context-window headroom for the active session. Returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none|warn|critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals247.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals247.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID},directory);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
7281
+ `);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason,environmentUnavailable=discoveryResult.skipped.filter((skip)=>skip.code==="environment_unavailable");if(runs.length===0)if(verdict=environmentUnavailable.length>0?"skip":"info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason=NO_BUILD_FILES_DISCOVERED_REASON;else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason,environment_unavailable:environmentUnavailable.length>0?environmentUnavailable:void 0}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){if(_internals243.loadGateOverrides(directory)?.build_check?.enabled===!1)return JSON.stringify({verdict:"skip",runs:[],summary:{files_scanned:0,runs_count:0,failed_count:0,skipped_reason:"build_check disabled by configuration"}},null,2);let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason,environment_unavailable:result.summary.environment_unavailable};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs170 from"node:fs";import*as path296 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path296.resolve(workspaceRoot),swarmPath3=path296.join(normalizedWorkspace,".swarm","evidence");return path296.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs170.existsSync(evidencePath))return null;let content;try{content=fs170.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path296.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status2=requiredGates.length>0&&missingGates.length===0?"all_passed":"incomplete",message;if(status2==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else if(requiredGates.length===0)message=`Task "${taskIdInput}" is incomplete. No required gates are configured for this task generation.`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status2="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status2==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status:status2,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_loader();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80),report_verdict:exports_external.enum(["APPROVE","REQUEST_CHANGES","INCOMPLETE"]).optional()}).strict().superRefine((value,ctx)=>{if(value.mode==="PR_REVIEW"&&value.report_verdict===void 0)ctx.addIssue({code:"custom",path:["report_verdict"],message:"is required for PR_REVIEW completion (issue #2383 terminal report)"})});async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={},laneLiveness;try{let config3=loadPluginConfig(directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}try{let settlement=await _internals244.settlePresumedStalePrWorkflowLanes(directory,context.sessionID,laneLiveness);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason;if(settlement.horizonConflictNote)staleDisclosure.horizon_conflict=settlement.horizonConflictNote}catch{}let amendmentDisclosure={};try{let gateState=await _internals244.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let terminalReport;if(parsed.data.mode==="PR_REVIEW"){let coverage=null;try{coverage=await _internals244.readPrReviewTerminalCoverageForReport(directory,context.sessionID)}catch{}if(coverage){let findingPolicy;try{findingPolicy=await _internals244.readPrReviewFinalFindingPolicyForReport(directory,context.sessionID)}catch{}terminalReport={kind:coverage.kind,covered_dimensions:coverage.coveredDimensions,unresolved_dimensions:coverage.unresolvedDimensions,live_dimensions:coverage.liveDimensions,allowed_verdicts:findingPolicy?.permittedVerdicts??coverage.allowedVerdicts,...findingPolicy?{finding_policy_version:findingPolicy.policyVersion,blocking_finding_ids:findingPolicy.blockingFindingIds}:{},report_verdict:parsed.data.report_verdict}}}let status2=await _internals244.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha,parsed.data.mode==="PR_REVIEW"?{reportVerdict:parsed.data.report_verdict,...laneLiveness?{laneLiveness}:{}}:laneLiveness?{laneLiveness}:void 0),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status2==="completed")try{checkoutRestoreReceipts=await _internals244.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status:status2,ready_to_publish:status2==="ready-to-publish",verified_no_change:status2==="verified-no-change",gate_cleared:status2==="completed"||status2==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...terminalReport?{terminal_report:terminalReport}:{},...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha,report_verdict:CompletePrWorkflowArgsSchema.shape.report_verdict},execute:executeCompletePrWorkflow}),_internals244={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,readPrReviewTerminalCoverageForReport,readPrReviewFinalFindingPolicyForReport,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs171 from"node:fs";import*as path297 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs171.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath=filePath.replace(/\\/g,"/"),resolvedPath=path297.resolve(directory,normalizedPath),projectRoot=path297.resolve(directory),relative76=path297.relative(projectRoot,resolvedPath);if(!(relative76===""||!relative76.startsWith("..")&&!path297.isAbsolute(relative76))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs171.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path297.join(directory,".swarm","evidence",`${phase}`),evidencePath=path297.join(evidenceDir,"completion-verify.json");fs171.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs171.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import{Buffer as Buffer4}from"node:buffer";import*as fs172 from"node:fs";import*as path298 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals245={bunSpawn,resolveGitExecutable},GIT_CHURN_TIMEOUT_MS=1e4,GIT_CHURN_MAX_BUFFER_BYTES=5242880;async function getGitChurn(days,directory){let churnMap=new Map,proc=_internals245.bunSpawn([_internals245.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",stdin:"ignore",cwd:directory,timeout:GIT_CHURN_TIMEOUT_MS,maxBuffer:GIT_CHURN_MAX_BUFFER_BYTES,killProcessTree:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),churnTimeout;try{let[stdout,outcome]=await Promise.race([Promise.all([proc.stdout.text(),proc.exited]).then((churnOutput)=>churnOutput),new Promise((resolve121)=>{churnTimeout=setTimeout(()=>resolve121([null,"timeout"]),GIT_CHURN_TIMEOUT_MS)})]);if(typeof churnTimeout<"u")clearTimeout(churnTimeout);if(outcome==="timeout")throw Error(`git churn analysis failed: git log did not finish within ${GIT_CHURN_TIMEOUT_MS} ms (bounded; child tree killed)`);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);if(proc.signalCode)throw Error(`git churn analysis failed: git log was killed by ${proc.signalCode} after exceeding the ${GIT_CHURN_TIMEOUT_MS} ms / ${GIT_CHURN_MAX_BUFFER_BYTES}-byte bound`);if(Buffer4.byteLength(stdout)>=GIT_CHURN_MAX_BUFFER_BYTES)throw Error(`git churn analysis failed: git log output reached the ${GIT_CHURN_MAX_BUFFER_BYTES}-byte buffer limit`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath=line.replace(/\\/g,"/");if(!normalizedPath||normalizedPath.trim()==="")continue;if(normalizedPath.includes("node_modules")||normalizedPath.includes("/.git/")||normalizedPath.includes("/dist/")||normalizedPath.includes("/build/")||normalizedPath.includes("__tests__"))continue;if(normalizedPath.includes(".test.")||normalizedPath.includes(".spec."))continue;churnMap.set(normalizedPath,(churnMap.get(normalizedPath)||0)+1)}}finally{if(typeof churnTimeout<"u")clearTimeout(churnTimeout);try{proc.kill()}catch{}}return churnMap}function getComplexityForFile2(filePath){try{if(fs172.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs172.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path298.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs172.existsSync(fullPath))fullPath=path298.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store4();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store4();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals246.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected2=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected2+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected:rejected2,failed,...error93?{error:error93}:{}}}var _internals246={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_state2();init_create_tool();var _internals247={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity,directory){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimitResolution=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit,directory),modelLimit=modelLimitResolution.limit,usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,modelLimitSource:modelLimitResolution.source,modelLimitResolution:modelLimitResolution.resolution,fallbackActive:modelLimitResolution.source==="provider_cap"||modelLimitResolution.source==="native"||modelLimitResolution.source==="fallback",usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Report current context-window headroom for the active session. Returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none|warn|critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals247.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals247.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID},directory);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
7282
7282
  ${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_gate_evidence();init_project_boundary();init_council_review_identity();import{existsSync as existsSync157,mkdirSync as mkdirSync83,readFileSync as readFileSync125}from"node:fs";import{join as join237}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals248={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key2 of Object.keys(source)){if(FORBIDDEN_KEYS.has(key2))continue;let value=source[key2];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key2]=nested}else if(Array.isArray(value))target[key2]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key2]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId,expectedGeneration,identity){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join237(workingDir,EVIDENCE_DIR2);assertProjectRoot(workingDir),mkdirSync83(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals248.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{assertTaskEvidenceWriteAllowed(workingDir,synthesis.taskId);let existingRoot=Object.create(null);if(existsSync157(filePath))try{let raw=readFileSync125(filePath,"utf-8");if(expectedGeneration!==void 0){let exactEvidence=parseTaskEvidence(raw,synthesis.taskId),workflow=getTaskWorkflowSnapshot(exactEvidence);if(!workflow.authoritative||workflow.generation!==expectedGeneration||workflow.state!=="pre_check_passed")throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: expected pre_check_passed@${expectedGeneration}, found ${workflow.state}@${workflow.generation}`)}let parsed=EvidenceFileSchema.parse(JSON.parse(raw));safeAssignOwnProps(existingRoot,parsed)}catch(error93){if(expectedGeneration!==void 0)throw error93}else if(expectedGeneration!==void 0)throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: no exact evidence exists for generation ${expectedGeneration}`);let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...identity?councilIdentityEvidenceFields(identity):{},...expectedGeneration!==void 0?{workflowGeneration:expectedGeneration}:{},...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync125(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_council_review_identity();init_lock();init_task_file();import{createHash as createHash94,randomUUID as randomUUID39}from"node:crypto";import{closeSync as closeSync36,existsSync as existsSync158,fsyncSync as fsyncSync10,mkdirSync as mkdirSync84,openSync as openSync36,readFileSync as readFileSync126,readSync as readSync24,statSync as statSync86,writeSync as writeSync6}from"node:fs";import{dirname as dirname112,join as join238}from"node:path";init_telemetry();function scopeIdentityPayload(scope){return{level:scope.kind,...scope.kind==="task"&&scope.taskId!==void 0?{taskId:scope.taskId}:{},...scope.kind==="phase"&&scope.phaseNumber!==void 0?{phase:scope.phaseNumber}:{},identityDigest:scope.identityDigest}}function observeCouncilAuditAppend(scope,sessionID,councilRoundId,record3){try{emit("council_attempt",{...sessionID!==void 0?{sessionId:sessionID}:{},councilRoundId,...scopeIdentityPayload(scope),stage:record3.event,attemptId:record3.attemptId,disposition:record3.disposition,authoritativeRound:record3.authoritativeRound,...record3.clientRound!==void 0?{clientRound:record3.clientRound}:{},verdictCount:record3.verdictCount,memberCount:record3.members.length,...record3.quorumSize!==void 0?{quorumSize:record3.quorumSize}:{},...record3.verdict!==void 0?{verdict:record3.verdict}:{},...record3.transition!==void 0?{transition:record3.transition}:{},...record3.gateEffect!==void 0?{gateEffect:record3.gateEffect}:{}});let next=record3.nextState;if(record3.event!=="received"&&(record3.transition==="advance"||record3.transition==="close")&&next!==void 0)emit("council_round_transition",{...sessionID!==void 0?{sessionId:sessionID}:{},councilRoundId,...scopeIdentityPayload(scope),attemptId:record3.attemptId,transition:record3.transition,gateEffect:record3.gateEffect,round:record3.authoritativeRound,nextRound:next.currentRound,roundStatus:next.status,maxRoundsExhausted:next.maxRoundsExhausted,...record3.verdict!==void 0?{verdict:record3.verdict}:{},...record3.quorumSize!==void 0?{quorumSize:record3.quorumSize}:{}})}catch{}}function emitUnscopedCouncilAttemptObservation(sessionID,level,disposition,fingerprint2,attemptId){try{emit("council_attempt_unscoped",{...sessionID!==void 0?{sessionId:sessionID}:{},level,disposition,fingerprint:fingerprint2,attemptId})}catch{}}init_council_review_identity();var VERSION=2,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state",EXHAUSTION_EVENT_RELATIVE_PATH="council/events/max-rounds-exhaustion.jsonl";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha25610(value){return createHash94("sha256").update(value).digest("hex")}var UUID_PATTERN2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN2=/^[a-f0-9]{64}$/;function isUuid2(value){return typeof value==="string"&&UUID_PATTERN2.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN2.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");if(!isIdentityDigest(scope.identityDigest))throw Error("invalid task council scope identity");return`task-${sha25610(JSON.stringify({k:"task",taskId:scope.taskId,id:scope.identityDigest}))}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");if(!isIdentityDigest(scope.identityDigest))throw Error("invalid phase council scope identity");return`phase-${sha25610(JSON.stringify({k:"phase",phaseNumber:scope.phaseNumber,id:scope.identityDigest}))}`}if(!isIdentityDigest(scope.identityDigest))throw Error("invalid final council scope identity");return`final-${sha25610(JSON.stringify({k:"final",id:scope.identityDigest}))}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha25610(scope.taskId),identityDigest:scope.identityDigest};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber,identityDigest:scope.identityDigest};return{kind:"final",scopeHash:sha25610(scope.identityDigest),identityDigest:scope.identityDigest}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.identityDigest!==right.identityDigest)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join238(directory,".swarm","council","round-state",`${token}.json`),audit:join238(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join238("council","round-state",`${token}.json`)}}function canonicalize3(value){if(Array.isArray(value))return value.map(canonicalize3);if(value&&typeof value==="object"){let result=Object.create(null);for(let key2 of Object.keys(value).sort()){if(key2==="working_directory"||key2==="roundNumber"||key2==="provenanceAgentName"||key2==="provenanceSessionId")continue;result[key2]=canonicalize3(value[key2])}return result}return value}function councilRequestDigest(request,round){return sha25610(JSON.stringify({round,request:canonicalize3(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state2=value;return state2.version===VERSION&&isIdentityDigest(state2.identityDigest)&&isRound(state2.currentRound)&&(state2.status==="open"||state2.status==="closed")&&typeof state2.maxRoundsExhausted==="boolean"&&(state2.lastAttemptId===void 0||isUuid2(state2.lastAttemptId))&&(state2.lastDigest===void 0||isDigest(state2.lastDigest))&&state2.lastAttemptId===void 0===(state2.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2,identityDigest){let current=tail2.truncated?void 0:initialState(identityDigest),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state2,pending){if(state2.status!=="open"||pending.round!==state2.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===state2.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===state2.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state2.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw,expectedIdentityDigest){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state2=value;if(state2.identityDigest!==expectedIdentityDigest)throw new CouncilRoundStateUncertainError("council round state identity does not match the request scope");if(state2.pending){let pending=state2.pending;if(!isUuid2(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state2,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state2}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid2(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path299,record3){mkdirSync84(dirname112(path299),{recursive:!0});let descriptor=openSync36(path299,"a");try{writeSync6(descriptor,`${JSON.stringify(record3)}
7283
7283
  `,void 0,"utf8"),fsyncSync10(descriptor)}finally{closeSync36(descriptor)}}function appendAuditAndObserve(input,paths,councilRoundId,record3){_internals249.appendAudit(paths.audit,record3),observeCouncilAuditAppend(input.scope,input.sessionID,councilRoundId,record3)}function readAuditTail(path299,scope){if(!existsSync158(path299))return{records:[],truncated:!1};let size=statSync86(path299).size;if(size===0)return{records:[],truncated:!1};let offset=Math.max(0,size-MAX_AUDIT_TAIL),length=size-offset,descriptor=openSync36(path299,"r"),buffer=Buffer.alloc(length);try{readSync24(descriptor,buffer,0,length,offset)}finally{closeSync36(descriptor)}let text=buffer.toString("utf8");if(!text.endsWith(`
7284
7284
  `))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`